; Update ChangeLog.2 and AUTHORS files
[emacs.git] / src / nsterm.m
blob4f99a13c44e74c06c4da77868b852e3f8b739172
1 /* NeXT/Open/GNUstep / macOS 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 macOS/Aqua port by Christophe de Dinechin (descubes@earthlink.net)
26 GNUstep port and post-20 update by Adrian Robert (arobert@cogsci.ucsd.edu)
29 /* This should be the first include, as it may set up #defines affecting
30    interpretation of even the system includes. */
31 #include <config.h>
33 #include <fcntl.h>
34 #include <math.h>
35 #include <pthread.h>
36 #include <sys/types.h>
37 #include <time.h>
38 #include <signal.h>
39 #include <unistd.h>
41 #include <c-ctype.h>
42 #include <c-strcase.h>
43 #include <ftoastr.h>
45 #include "lisp.h"
46 #include "blockinput.h"
47 #include "sysselect.h"
48 #include "nsterm.h"
49 #include "systime.h"
50 #include "character.h"
51 #include "fontset.h"
52 #include "composite.h"
53 #include "ccl.h"
55 #include "termhooks.h"
56 #include "termchar.h"
57 #include "menu.h"
58 #include "window.h"
59 #include "keyboard.h"
60 #include "buffer.h"
61 #include "font.h"
63 #ifdef NS_IMPL_GNUSTEP
64 #include "process.h"
65 #endif
67 #ifdef NS_IMPL_COCOA
68 #include "macfont.h"
69 #endif
72 extern NSString *NSMenuDidBeginTrackingNotification;
75 /* ==========================================================================
77    NSTRACE, Trace support.
79    ========================================================================== */
81 #if NSTRACE_ENABLED
83 /* The following use "volatile" since they can be accessed from
84    parallel threads. */
85 volatile int nstrace_num = 0;
86 volatile int nstrace_depth = 0;
88 /* When 0, no trace is emitted.  This is used by NSTRACE_WHEN and
89    NSTRACE_UNLESS to silence functions called.
91    TODO: This should really be a thread-local variable, to avoid that
92    a function with disabled trace thread silence trace output in
93    another.  However, in practice this seldom is a problem. */
94 volatile int nstrace_enabled_global = 1;
96 /* Called when nstrace_enabled goes out of scope. */
97 void nstrace_leave(int * pointer_to_nstrace_enabled)
99   if (*pointer_to_nstrace_enabled)
100     {
101       --nstrace_depth;
102     }
106 /* Called when nstrace_saved_enabled_global goes out of scope. */
107 void nstrace_restore_global_trace_state(int * pointer_to_saved_enabled_global)
109   nstrace_enabled_global = *pointer_to_saved_enabled_global;
113 char const * nstrace_fullscreen_type_name (int fs_type)
115   switch (fs_type)
116     {
117     case -1:                   return "-1";
118     case FULLSCREEN_NONE:      return "FULLSCREEN_NONE";
119     case FULLSCREEN_WIDTH:     return "FULLSCREEN_WIDTH";
120     case FULLSCREEN_HEIGHT:    return "FULLSCREEN_HEIGHT";
121     case FULLSCREEN_BOTH:      return "FULLSCREEN_BOTH";
122     case FULLSCREEN_MAXIMIZED: return "FULLSCREEN_MAXIMIZED";
123     default:                   return "FULLSCREEN_?????";
124     }
126 #endif
129 /* ==========================================================================
131    NSColor, EmacsColor category.
133    ========================================================================== */
134 @implementation NSColor (EmacsColor)
135 + (NSColor *)colorForEmacsRed:(CGFloat)red green:(CGFloat)green
136                          blue:(CGFloat)blue alpha:(CGFloat)alpha
138 #ifdef NS_IMPL_COCOA
139 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
140   if (ns_use_srgb_colorspace)
141       return [NSColor colorWithSRGBRed: red
142                                  green: green
143                                   blue: blue
144                                  alpha: alpha];
145 #endif
146 #endif
147   return [NSColor colorWithCalibratedRed: red
148                                    green: green
149                                     blue: blue
150                                    alpha: alpha];
153 - (NSColor *)colorUsingDefaultColorSpace
155 #ifdef NS_IMPL_COCOA
156 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
157   if (ns_use_srgb_colorspace)
158     return [self colorUsingColorSpace: [NSColorSpace sRGBColorSpace]];
159 #endif
160 #endif
161   return [self colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
164 @end
166 /* ==========================================================================
168     Local declarations
170    ========================================================================== */
172 /* Convert a symbol indexed with an NSxxx value to a value as defined
173    in keyboard.c (lispy_function_key). I hope this is a correct way
174    of doing things... */
175 static unsigned convert_ns_to_X_keysym[] =
177   NSHomeFunctionKey,            0x50,
178   NSLeftArrowFunctionKey,       0x51,
179   NSUpArrowFunctionKey,         0x52,
180   NSRightArrowFunctionKey,      0x53,
181   NSDownArrowFunctionKey,       0x54,
182   NSPageUpFunctionKey,          0x55,
183   NSPageDownFunctionKey,        0x56,
184   NSEndFunctionKey,             0x57,
185   NSBeginFunctionKey,           0x58,
186   NSSelectFunctionKey,          0x60,
187   NSPrintFunctionKey,           0x61,
188   NSClearLineFunctionKey,       0x0B,
189   NSExecuteFunctionKey,         0x62,
190   NSInsertFunctionKey,          0x63,
191   NSUndoFunctionKey,            0x65,
192   NSRedoFunctionKey,            0x66,
193   NSMenuFunctionKey,            0x67,
194   NSFindFunctionKey,            0x68,
195   NSHelpFunctionKey,            0x6A,
196   NSBreakFunctionKey,           0x6B,
198   NSF1FunctionKey,              0xBE,
199   NSF2FunctionKey,              0xBF,
200   NSF3FunctionKey,              0xC0,
201   NSF4FunctionKey,              0xC1,
202   NSF5FunctionKey,              0xC2,
203   NSF6FunctionKey,              0xC3,
204   NSF7FunctionKey,              0xC4,
205   NSF8FunctionKey,              0xC5,
206   NSF9FunctionKey,              0xC6,
207   NSF10FunctionKey,             0xC7,
208   NSF11FunctionKey,             0xC8,
209   NSF12FunctionKey,             0xC9,
210   NSF13FunctionKey,             0xCA,
211   NSF14FunctionKey,             0xCB,
212   NSF15FunctionKey,             0xCC,
213   NSF16FunctionKey,             0xCD,
214   NSF17FunctionKey,             0xCE,
215   NSF18FunctionKey,             0xCF,
216   NSF19FunctionKey,             0xD0,
217   NSF20FunctionKey,             0xD1,
218   NSF21FunctionKey,             0xD2,
219   NSF22FunctionKey,             0xD3,
220   NSF23FunctionKey,             0xD4,
221   NSF24FunctionKey,             0xD5,
223   NSBackspaceCharacter,         0x08,  /* 8: Not on some KBs. */
224   NSDeleteCharacter,            0xFF,  /* 127: Big 'delete' key upper right. */
225   NSDeleteFunctionKey,          0x9F,  /* 63272: Del forw key off main array. */
227   NSTabCharacter,               0x09,
228   0x19,                         0x09,  /* left tab->regular since pass shift */
229   NSCarriageReturnCharacter,    0x0D,
230   NSNewlineCharacter,           0x0D,
231   NSEnterCharacter,             0x8D,
233   0x41|NSNumericPadKeyMask,     0xAE,  /* KP_Decimal */
234   0x43|NSNumericPadKeyMask,     0xAA,  /* KP_Multiply */
235   0x45|NSNumericPadKeyMask,     0xAB,  /* KP_Add */
236   0x4B|NSNumericPadKeyMask,     0xAF,  /* KP_Divide */
237   0x4E|NSNumericPadKeyMask,     0xAD,  /* KP_Subtract */
238   0x51|NSNumericPadKeyMask,     0xBD,  /* KP_Equal */
239   0x52|NSNumericPadKeyMask,     0xB0,  /* KP_0 */
240   0x53|NSNumericPadKeyMask,     0xB1,  /* KP_1 */
241   0x54|NSNumericPadKeyMask,     0xB2,  /* KP_2 */
242   0x55|NSNumericPadKeyMask,     0xB3,  /* KP_3 */
243   0x56|NSNumericPadKeyMask,     0xB4,  /* KP_4 */
244   0x57|NSNumericPadKeyMask,     0xB5,  /* KP_5 */
245   0x58|NSNumericPadKeyMask,     0xB6,  /* KP_6 */
246   0x59|NSNumericPadKeyMask,     0xB7,  /* KP_7 */
247   0x5B|NSNumericPadKeyMask,     0xB8,  /* KP_8 */
248   0x5C|NSNumericPadKeyMask,     0xB9,  /* KP_9 */
250   0x1B,                         0x1B   /* escape */
253 /* On macOS picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
254    the maximum font size to NOT antialias.  On GNUstep there is currently
255    no way to control this behavior. */
256 float ns_antialias_threshold;
258 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
259 NSString *ns_app_name = @"Emacs";  /* default changed later */
261 /* Display variables */
262 struct ns_display_info *x_display_list; /* Chain of existing displays */
263 long context_menu_value = 0;
265 /* display update */
266 static struct frame *ns_updating_frame;
267 static NSView *focus_view = NULL;
268 static int ns_window_num = 0;
269 #ifdef NS_IMPL_GNUSTEP
270 static NSRect uRect;            // TODO: This is dead, remove it?
271 #endif
272 static BOOL gsaved = NO;
273 static BOOL ns_fake_keydown = NO;
274 #ifdef NS_IMPL_COCOA
275 static BOOL ns_menu_bar_is_hidden = NO;
276 #endif
277 /*static int debug_lock = 0; */
279 /* event loop */
280 static BOOL send_appdefined = YES;
281 #define NO_APPDEFINED_DATA (-8)
282 static int last_appdefined_event_data = NO_APPDEFINED_DATA;
283 static NSTimer *timed_entry = 0;
284 static NSTimer *scroll_repeat_entry = nil;
285 static fd_set select_readfds, select_writefds;
286 enum { SELECT_HAVE_READ = 1, SELECT_HAVE_WRITE = 2, SELECT_HAVE_TMO = 4 };
287 static int select_nfds = 0, select_valid = 0;
288 static struct timespec select_timeout = { 0, 0 };
289 static int selfds[2] = { -1, -1 };
290 static pthread_mutex_t select_mutex;
291 static int apploopnr = 0;
292 static NSAutoreleasePool *outerpool;
293 static struct input_event *emacs_event = NULL;
294 static struct input_event *q_event_ptr = NULL;
295 static int n_emacs_events_pending = 0;
296 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
297   *ns_pending_service_args;
298 static BOOL ns_do_open_file = NO;
299 static BOOL ns_last_use_native_fullscreen;
301 /* Non-zero means that a HELP_EVENT has been generated since Emacs
302    start.  */
304 static BOOL any_help_event_p = NO;
306 static struct {
307   struct input_event *q;
308   int nr, cap;
309 } hold_event_q = {
310   NULL, 0, 0
313 static NSString *represented_filename = nil;
314 static struct frame *represented_frame = 0;
316 #ifdef NS_IMPL_COCOA
318  * State for pending menu activation:
319  * MENU_NONE     Normal state
320  * MENU_PENDING  A menu has been clicked on, but has been canceled so we can
321  *               run lisp to update the menu.
322  * MENU_OPENING  Menu is up to date, and the click event is redone so the menu
323  *               will open.
324  */
325 #define MENU_NONE 0
326 #define MENU_PENDING 1
327 #define MENU_OPENING 2
328 static int menu_will_open_state = MENU_NONE;
330 /* Saved position for menu click.  */
331 static CGPoint menu_mouse_point;
332 #endif
334 /* Convert modifiers in a NeXTstep event to emacs style modifiers.  */
335 #define NS_FUNCTION_KEY_MASK 0x800000
336 #define NSLeftControlKeyMask    (0x000001 | NSControlKeyMask)
337 #define NSRightControlKeyMask   (0x002000 | NSControlKeyMask)
338 #define NSLeftCommandKeyMask    (0x000008 | NSCommandKeyMask)
339 #define NSRightCommandKeyMask   (0x000010 | NSCommandKeyMask)
340 #define NSLeftAlternateKeyMask  (0x000020 | NSAlternateKeyMask)
341 #define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
342 #define EV_MODIFIERS2(flags)                          \
343     (((flags & NSHelpKeyMask) ?           \
344            hyper_modifier : 0)                        \
345      | (!EQ (ns_right_alternate_modifier, Qleft) && \
346         ((flags & NSRightAlternateKeyMask) \
347          == NSRightAlternateKeyMask) ? \
348            parse_solitary_modifier (ns_right_alternate_modifier) : 0) \
349      | ((flags & NSAlternateKeyMask) ?                 \
350            parse_solitary_modifier (ns_alternate_modifier) : 0)   \
351      | ((flags & NSShiftKeyMask) ?     \
352            shift_modifier : 0)                        \
353      | (!EQ (ns_right_control_modifier, Qleft) && \
354         ((flags & NSRightControlKeyMask) \
355          == NSRightControlKeyMask) ? \
356            parse_solitary_modifier (ns_right_control_modifier) : 0) \
357      | ((flags & NSControlKeyMask) ?      \
358            parse_solitary_modifier (ns_control_modifier) : 0)     \
359      | ((flags & NS_FUNCTION_KEY_MASK) ?  \
360            parse_solitary_modifier (ns_function_modifier) : 0)    \
361      | (!EQ (ns_right_command_modifier, Qleft) && \
362         ((flags & NSRightCommandKeyMask) \
363          == NSRightCommandKeyMask) ? \
364            parse_solitary_modifier (ns_right_command_modifier) : 0) \
365      | ((flags & NSCommandKeyMask) ?      \
366            parse_solitary_modifier (ns_command_modifier):0))
367 #define EV_MODIFIERS(e) EV_MODIFIERS2 ([e modifierFlags])
369 #define EV_UDMODIFIERS(e)                                      \
370     ((([e type] == NSLeftMouseDown) ? down_modifier : 0)       \
371      | (([e type] == NSRightMouseDown) ? down_modifier : 0)    \
372      | (([e type] == NSOtherMouseDown) ? down_modifier : 0)    \
373      | (([e type] == NSLeftMouseDragged) ? down_modifier : 0)  \
374      | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
375      | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
376      | (([e type] == NSLeftMouseUp)   ? up_modifier   : 0)     \
377      | (([e type] == NSRightMouseUp)   ? up_modifier   : 0)    \
378      | (([e type] == NSOtherMouseUp)   ? up_modifier   : 0))
380 #define EV_BUTTON(e)                                                         \
381     ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 :    \
382       (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
383      [e buttonNumber] - 1)
385 /* Convert the time field to a timestamp in milliseconds. */
386 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
388 /* This is a piece of code which is common to all the event handling
389    methods.  Maybe it should even be a function.  */
390 #define EV_TRAILER(e)                                                   \
391   {                                                                     \
392     XSETFRAME (emacs_event->frame_or_window, emacsframe);               \
393     EV_TRAILER2 (e);                                                    \
394   }
396 #define EV_TRAILER2(e)                                                  \
397   {                                                                     \
398       if (e) emacs_event->timestamp = EV_TIMESTAMP (e);                 \
399       if (q_event_ptr)                                                  \
400         {                                                               \
401           Lisp_Object tem = Vinhibit_quit;                              \
402           Vinhibit_quit = Qt;                                           \
403           n_emacs_events_pending++;                                     \
404           kbd_buffer_store_event_hold (emacs_event, q_event_ptr);       \
405           Vinhibit_quit = tem;                                          \
406         }                                                               \
407       else                                                              \
408         hold_event (emacs_event);                                       \
409       EVENT_INIT (*emacs_event);                                        \
410       ns_send_appdefined (-1);                                          \
411     }
413 /* TODO: get rid of need for these forward declarations */
414 static void ns_condemn_scroll_bars (struct frame *f);
415 static void ns_judge_scroll_bars (struct frame *f);
416 void x_set_frame_alpha (struct frame *f);
419 /* ==========================================================================
421     Utilities
423    ========================================================================== */
425 void
426 ns_set_represented_filename (NSString* fstr, struct frame *f)
428   represented_filename = [fstr retain];
429   represented_frame = f;
432 void
433 ns_init_events (struct input_event* ev)
435   EVENT_INIT (*ev);
436   emacs_event = ev;
439 void
440 ns_finish_events ()
442   emacs_event = NULL;
445 static void
446 hold_event (struct input_event *event)
448   if (hold_event_q.nr == hold_event_q.cap)
449     {
450       if (hold_event_q.cap == 0) hold_event_q.cap = 10;
451       else hold_event_q.cap *= 2;
452       hold_event_q.q =
453         xrealloc (hold_event_q.q, hold_event_q.cap * sizeof *hold_event_q.q);
454     }
456   hold_event_q.q[hold_event_q.nr++] = *event;
457   /* Make sure ns_read_socket is called, i.e. we have input.  */
458   raise (SIGIO);
459   send_appdefined = YES;
462 static Lisp_Object
463 append2 (Lisp_Object list, Lisp_Object item)
464 /* --------------------------------------------------------------------------
465    Utility to append to a list
466    -------------------------------------------------------------------------- */
468   return CALLN (Fnconc, list, list1 (item));
472 const char *
473 ns_etc_directory (void)
474 /* If running as a self-contained app bundle, return as a string the
475    filename of the etc directory, if present; else nil.  */
477   NSBundle *bundle = [NSBundle mainBundle];
478   NSString *resourceDir = [bundle resourcePath];
479   NSString *resourcePath;
480   NSFileManager *fileManager = [NSFileManager defaultManager];
481   BOOL isDir;
483   resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
484   if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
485     {
486       if (isDir) return [resourcePath UTF8String];
487     }
488   return NULL;
492 const char *
493 ns_exec_path (void)
494 /* If running as a self-contained app bundle, return as a path string
495    the filenames of the libexec and bin directories, ie libexec:bin.
496    Otherwise, return nil.
497    Normally, Emacs does not add its own bin/ directory to the PATH.
498    However, a self-contained NS build has a different layout, with
499    bin/ and libexec/ subdirectories in the directory that contains
500    Emacs.app itself.
501    We put libexec first, because init_callproc_1 uses the first
502    element to initialize exec-directory.  An alternative would be
503    for init_callproc to check for invocation-directory/libexec.
506   NSBundle *bundle = [NSBundle mainBundle];
507   NSString *resourceDir = [bundle resourcePath];
508   NSString *binDir = [bundle bundlePath];
509   NSString *resourcePath, *resourcePaths;
510   NSRange range;
511   NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
512   NSFileManager *fileManager = [NSFileManager defaultManager];
513   NSArray *paths;
514   NSEnumerator *pathEnum;
515   BOOL isDir;
517   range = [resourceDir rangeOfString: @"Contents"];
518   if (range.location != NSNotFound)
519     {
520       binDir = [binDir stringByAppendingPathComponent: @"Contents"];
521 #ifdef NS_IMPL_COCOA
522       binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
523 #endif
524     }
526   paths = [binDir stringsByAppendingPaths:
527                 [NSArray arrayWithObjects: @"libexec", @"bin", nil]];
528   pathEnum = [paths objectEnumerator];
529   resourcePaths = @"";
531   while ((resourcePath = [pathEnum nextObject]))
532     {
533       if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
534         if (isDir)
535           {
536             if ([resourcePaths length] > 0)
537               resourcePaths
538                 = [resourcePaths stringByAppendingString: pathSeparator];
539             resourcePaths
540               = [resourcePaths stringByAppendingString: resourcePath];
541           }
542     }
543   if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
545   return NULL;
549 const char *
550 ns_load_path (void)
551 /* If running as a self-contained app bundle, return as a path string
552    the filenames of the site-lisp and lisp directories.
553    Ie, site-lisp:lisp.  Otherwise, return nil.  */
555   NSBundle *bundle = [NSBundle mainBundle];
556   NSString *resourceDir = [bundle resourcePath];
557   NSString *resourcePath, *resourcePaths;
558   NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
559   NSFileManager *fileManager = [NSFileManager defaultManager];
560   BOOL isDir;
561   NSArray *paths = [resourceDir stringsByAppendingPaths:
562                               [NSArray arrayWithObjects:
563                                          @"site-lisp", @"lisp", nil]];
564   NSEnumerator *pathEnum = [paths objectEnumerator];
565   resourcePaths = @"";
567   /* Hack to skip site-lisp.  */
568   if (no_site_lisp) resourcePath = [pathEnum nextObject];
570   while ((resourcePath = [pathEnum nextObject]))
571     {
572       if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
573         if (isDir)
574           {
575             if ([resourcePaths length] > 0)
576               resourcePaths
577                 = [resourcePaths stringByAppendingString: pathSeparator];
578             resourcePaths
579               = [resourcePaths stringByAppendingString: resourcePath];
580           }
581     }
582   if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
584   return NULL;
588 void
589 ns_init_locale (void)
590 /* macOS doesn't set any environment variables for the locale when run
591    from the GUI. Get the locale from the OS and set LANG. */
593   NSLocale *locale = [NSLocale currentLocale];
595   NSTRACE ("ns_init_locale");
597   @try
598     {
599       /* It seems macOS should probably use UTF-8 everywhere.
600          'localeIdentifier' does not specify the encoding, and I can't
601          find any way to get the OS to tell us which encoding to use,
602          so hard-code '.UTF-8'. */
603       NSString *localeID = [NSString stringWithFormat:@"%@.UTF-8",
604                                      [locale localeIdentifier]];
606       /* Set LANG to locale, but not if LANG is already set. */
607       setenv("LANG", [localeID UTF8String], 0);
608     }
609   @catch (NSException *e)
610     {
611       NSLog (@"Locale detection failed: %@: %@", [e name], [e reason]);
612     }
616 void
617 ns_release_object (void *obj)
618 /* --------------------------------------------------------------------------
619     Release an object (callable from C)
620    -------------------------------------------------------------------------- */
622     [(id)obj release];
626 void
627 ns_retain_object (void *obj)
628 /* --------------------------------------------------------------------------
629     Retain an object (callable from C)
630    -------------------------------------------------------------------------- */
632     [(id)obj retain];
636 void *
637 ns_alloc_autorelease_pool (void)
638 /* --------------------------------------------------------------------------
639      Allocate a pool for temporary objects (callable from C)
640    -------------------------------------------------------------------------- */
642   return [[NSAutoreleasePool alloc] init];
646 void
647 ns_release_autorelease_pool (void *pool)
648 /* --------------------------------------------------------------------------
649      Free a pool and temporary objects it refers to (callable from C)
650    -------------------------------------------------------------------------- */
652   ns_release_object (pool);
656 static BOOL
657 ns_menu_bar_should_be_hidden (void)
658 /* True, if the menu bar should be hidden.  */
660   return !NILP (ns_auto_hide_menu_bar)
661     && [NSApp respondsToSelector:@selector(setPresentationOptions:)];
665 struct EmacsMargins
667   CGFloat top;
668   CGFloat bottom;
669   CGFloat left;
670   CGFloat right;
674 static struct EmacsMargins
675 ns_screen_margins (NSScreen *screen)
676 /* The parts of SCREEN used by the operating system.  */
678   NSTRACE ("ns_screen_margins");
680   struct EmacsMargins margins;
682   NSRect screenFrame = [screen frame];
683   NSRect screenVisibleFrame = [screen visibleFrame];
685   /* Sometimes, visibleFrame isn't up-to-date with respect to a hidden
686      menu bar, check this explicitly.  */
687   if (ns_menu_bar_should_be_hidden())
688     {
689       margins.top = 0;
690     }
691   else
692     {
693       CGFloat frameTop = screenFrame.origin.y + screenFrame.size.height;
694       CGFloat visibleFrameTop = (screenVisibleFrame.origin.y
695                                  + screenVisibleFrame.size.height);
697       margins.top = frameTop - visibleFrameTop;
698     }
700   {
701     CGFloat frameRight = screenFrame.origin.x + screenFrame.size.width;
702     CGFloat visibleFrameRight = (screenVisibleFrame.origin.x
703                                  + screenVisibleFrame.size.width);
704     margins.right = frameRight - visibleFrameRight;
705   }
707   margins.bottom = screenVisibleFrame.origin.y - screenFrame.origin.y;
708   margins.left   = screenVisibleFrame.origin.x - screenFrame.origin.x;
710   NSTRACE_MSG ("left:%g right:%g top:%g bottom:%g",
711                margins.left,
712                margins.right,
713                margins.top,
714                margins.bottom);
716   return margins;
720 /* A screen margin between 1 and DOCK_IGNORE_LIMIT (inclusive) is
721    assumed to contain a hidden dock.  macOS currently use 4 pixels for
722    this, however, to be future compatible, a larger value is used.  */
723 #define DOCK_IGNORE_LIMIT 6
725 static struct EmacsMargins
726 ns_screen_margins_ignoring_hidden_dock (NSScreen *screen)
727 /* The parts of SCREEN used by the operating system, excluding the parts
728 reserved for an hidden dock.  */
730   NSTRACE ("ns_screen_margins_ignoring_hidden_dock");
732   struct EmacsMargins margins = ns_screen_margins(screen);
734   /* macOS (currently) reserved 4 pixels along the edge where a hidden
735      dock is located.  Unfortunately, it's not possible to find the
736      location and information about if the dock is hidden.  Instead,
737      it is assumed that if the margin of an edge is less than
738      DOCK_IGNORE_LIMIT, it contains a hidden dock.  */
739   if (margins.left <= DOCK_IGNORE_LIMIT)
740     {
741       margins.left = 0;
742     }
743   if (margins.right <= DOCK_IGNORE_LIMIT)
744     {
745       margins.right = 0;
746     }
747   if (margins.top <= DOCK_IGNORE_LIMIT)
748     {
749       margins.top = 0;
750     }
751   /* Note: This doesn't occur in current versions of macOS, but
752      included for completeness and future compatibility.  */
753   if (margins.bottom <= DOCK_IGNORE_LIMIT)
754     {
755       margins.bottom = 0;
756     }
758   NSTRACE_MSG ("left:%g right:%g top:%g bottom:%g",
759                margins.left,
760                margins.right,
761                margins.top,
762                margins.bottom);
764   return margins;
768 static CGFloat
769 ns_menu_bar_height (NSScreen *screen)
770 /* The height of the menu bar, if visible.
772    Note: Don't use this when fullscreen is enabled -- the screen
773    sometimes includes, sometimes excludes the menu bar area.  */
775   struct EmacsMargins margins = ns_screen_margins(screen);
777   CGFloat res = margins.top;
779   NSTRACE ("ns_menu_bar_height " NSTRACE_FMT_RETURN " %.0f", res);
781   return res;
785 /* ==========================================================================
787     Focus (clipping) and screen update
789    ========================================================================== */
792 // Window constraining
793 // -------------------
795 // To ensure that the windows are not placed under the menu bar, they
796 // are typically moved by the call-back constrainFrameRect. However,
797 // by overriding it, it's possible to inhibit this, leaving the window
798 // in it's original position.
800 // It's possible to hide the menu bar. However, technically, it's only
801 // possible to hide it when the application is active. To ensure that
802 // this work properly, the menu bar and window constraining are
803 // deferred until the application becomes active.
805 // Even though it's not possible to manually move a window above the
806 // top of the screen, it is allowed if it's done programmatically,
807 // when the menu is hidden. This allows the editable area to cover the
808 // full screen height.
810 // Test cases
811 // ----------
813 // Use the following extra files:
815 //    init.el:
816 //       ;; Hide menu and place frame slightly above the top of the screen.
817 //       (setq ns-auto-hide-menu-bar t)
818 //       (set-frame-position (selected-frame) 0 -20)
820 // Test 1:
822 //    emacs -Q -l init.el
824 //    Result: No menu bar, and the title bar should be above the screen.
826 // Test 2:
828 //    emacs -Q
830 //    Result: Menu bar visible, frame placed immediately below the menu.
833 static NSRect constrain_frame_rect(NSRect frameRect, bool isFullscreen)
835   NSTRACE ("constrain_frame_rect(" NSTRACE_FMT_RECT ")",
836              NSTRACE_ARG_RECT (frameRect));
838   // --------------------
839   // Collect information about the screen the frame is covering.
840   //
842   NSArray *screens = [NSScreen screens];
843   NSUInteger nr_screens = [screens count];
845   int i;
847   // The height of the menu bar, if present in any screen the frame is
848   // displayed in.
849   int menu_bar_height = 0;
851   // A rectangle covering all the screen the frame is displayed in.
852   NSRect multiscreenRect = NSMakeRect(0, 0, 0, 0);
853   for (i = 0; i < nr_screens; ++i )
854     {
855       NSScreen *s = [screens objectAtIndex: i];
856       NSRect scrRect = [s frame];
858       NSTRACE_MSG ("Screen %d: " NSTRACE_FMT_RECT,
859                    i, NSTRACE_ARG_RECT (scrRect));
861       if (NSIntersectionRect (frameRect, scrRect).size.height != 0)
862         {
863           multiscreenRect = NSUnionRect (multiscreenRect, scrRect);
865           if (!isFullscreen)
866             {
867               CGFloat screen_menu_bar_height = ns_menu_bar_height (s);
868               menu_bar_height = max(menu_bar_height, screen_menu_bar_height);
869             }
870         }
871     }
873   NSTRACE_RECT ("multiscreenRect", multiscreenRect);
875   NSTRACE_MSG ("menu_bar_height: %d", menu_bar_height);
877   if (multiscreenRect.size.width == 0
878       || multiscreenRect.size.height == 0)
879     {
880       // Failed to find any monitor, give up.
881       NSTRACE_MSG ("multiscreenRect empty");
882       NSTRACE_RETURN_RECT (frameRect);
883       return frameRect;
884     }
887   // --------------------
888   // Find a suitable placement.
889   //
891   if (ns_menu_bar_should_be_hidden())
892     {
893       // When the menu bar is hidden, the user may place part of the
894       // frame above the top of the screen, for example to hide the
895       // title bar.
896       //
897       // Hence, keep the original position.
898     }
899   else
900     {
901       // Ensure that the frame is below the menu bar, or below the top
902       // of the screen.
903       //
904       // This assume that the menu bar is placed at the top in the
905       // rectangle that covers the monitors.  (It doesn't have to be,
906       // but if it's not it's hard to do anything useful.)
907       CGFloat topOfWorkArea = (multiscreenRect.origin.y
908                                + multiscreenRect.size.height
909                                - menu_bar_height);
911       CGFloat topOfFrame = frameRect.origin.y + frameRect.size.height;
912       if (topOfFrame > topOfWorkArea)
913         {
914           frameRect.origin.y -= topOfFrame - topOfWorkArea;
915           NSTRACE_RECT ("After placement adjust", frameRect);
916         }
917     }
919   // Include the following section to restrict frame to the screens.
920   // (If so, update it to allow the frame to stretch down below the
921   // screen.)
922 #if 0
923   // --------------------
924   // Ensure frame doesn't stretch below the screens.
925   //
927   CGFloat diff = multiscreenRect.origin.y - frameRect.origin.y;
929   if (diff > 0)
930     {
931       frameRect.origin.y = multiscreenRect.origin.y;
932       frameRect.size.height -= diff;
933     }
934 #endif
936   NSTRACE_RETURN_RECT (frameRect);
937   return frameRect;
941 static void
942 ns_constrain_all_frames (void)
943 /* --------------------------------------------------------------------------
944      Ensure that the menu bar doesn't cover any frames.
945    -------------------------------------------------------------------------- */
947   Lisp_Object tail, frame;
949   NSTRACE ("ns_constrain_all_frames");
951   block_input ();
953   FOR_EACH_FRAME (tail, frame)
954     {
955       struct frame *f = XFRAME (frame);
956       if (FRAME_NS_P (f))
957         {
958           EmacsView *view = FRAME_NS_VIEW (f);
960           if (![view isFullscreen])
961             {
962               [[view window]
963                 setFrame:constrain_frame_rect([[view window] frame], false)
964                  display:NO];
965             }
966         }
967     }
969   unblock_input ();
973 static void
974 ns_update_auto_hide_menu_bar (void)
975 /* --------------------------------------------------------------------------
976      Show or hide the menu bar, based on user setting.
977    -------------------------------------------------------------------------- */
979 #ifdef NS_IMPL_COCOA
980   NSTRACE ("ns_update_auto_hide_menu_bar");
982   block_input ();
984   if (NSApp != nil && [NSApp isActive])
985     {
986       // Note, "setPresentationOptions" triggers an error unless the
987       // application is active.
988       BOOL menu_bar_should_be_hidden = ns_menu_bar_should_be_hidden ();
990       if (menu_bar_should_be_hidden != ns_menu_bar_is_hidden)
991         {
992           NSApplicationPresentationOptions options
993             = NSApplicationPresentationDefault;
995           if (menu_bar_should_be_hidden)
996             options |= NSApplicationPresentationAutoHideMenuBar
997               | NSApplicationPresentationAutoHideDock;
999           [NSApp setPresentationOptions: options];
1001           ns_menu_bar_is_hidden = menu_bar_should_be_hidden;
1003           if (!ns_menu_bar_is_hidden)
1004             {
1005               ns_constrain_all_frames ();
1006             }
1007         }
1008     }
1010   unblock_input ();
1011 #endif
1015 static void
1016 ns_update_begin (struct frame *f)
1017 /* --------------------------------------------------------------------------
1018    Prepare for a grouped sequence of drawing calls
1019    external (RIF) call; whole frame, called before update_window_begin
1020    -------------------------------------------------------------------------- */
1022   EmacsView *view = FRAME_NS_VIEW (f);
1023   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_begin");
1025   ns_update_auto_hide_menu_bar ();
1027 #ifdef NS_IMPL_COCOA
1028   if ([view isFullscreen] && [view fsIsNative])
1029   {
1030     // Fix reappearing tool bar in fullscreen for Mac OS X 10.7
1031     BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (f) ? YES : NO;
1032     NSToolbar *toolbar = [FRAME_NS_VIEW (f) toolbar];
1033     if (! tbar_visible != ! [toolbar isVisible])
1034       [toolbar setVisible: tbar_visible];
1035   }
1036 #endif
1038   ns_updating_frame = f;
1039   [view lockFocus];
1041   /* drawRect may have been called for say the minibuffer, and then clip path
1042      is for the minibuffer.  But the display engine may draw more because
1043      we have set the frame as garbaged.  So reset clip path to the whole
1044      view.  */
1045 #ifdef NS_IMPL_COCOA
1046   {
1047     NSBezierPath *bp;
1048     NSRect r = [view frame];
1049     NSRect cr = [[view window] frame];
1050     /* If a large frame size is set, r may be larger than the window frame
1051        before constrained.  In that case don't change the clip path, as we
1052        will clear in to the tool bar and title bar.  */
1053     if (r.size.height
1054         + FRAME_NS_TITLEBAR_HEIGHT (f)
1055         + FRAME_TOOLBAR_HEIGHT (f) <= cr.size.height)
1056       {
1057         bp = [[NSBezierPath bezierPathWithRect: r] retain];
1058         [bp setClip];
1059         [bp release];
1060       }
1061   }
1062 #endif
1064 #ifdef NS_IMPL_GNUSTEP
1065   uRect = NSMakeRect (0, 0, 0, 0);
1066 #endif
1070 static void
1071 ns_update_window_begin (struct window *w)
1072 /* --------------------------------------------------------------------------
1073    Prepare for a grouped sequence of drawing calls
1074    external (RIF) call; for one window, called after update_begin
1075    -------------------------------------------------------------------------- */
1077   struct frame *f = XFRAME (WINDOW_FRAME (w));
1078   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1080   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_window_begin");
1081   w->output_cursor = w->cursor;
1083   block_input ();
1085   if (f == hlinfo->mouse_face_mouse_frame)
1086     {
1087       /* Don't do highlighting for mouse motion during the update.  */
1088       hlinfo->mouse_face_defer = 1;
1090         /* If the frame needs to be redrawn,
1091            simply forget about any prior mouse highlighting.  */
1092       if (FRAME_GARBAGED_P (f))
1093         hlinfo->mouse_face_window = Qnil;
1095       /* (further code for mouse faces ifdef'd out in other terms elided) */
1096     }
1098   unblock_input ();
1102 static void
1103 ns_update_window_end (struct window *w, bool cursor_on_p,
1104                       bool mouse_face_overwritten_p)
1105 /* --------------------------------------------------------------------------
1106    Finished a grouped sequence of drawing calls
1107    external (RIF) call; for one window called before update_end
1108    -------------------------------------------------------------------------- */
1110   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_window_end");
1112   /* note: this fn is nearly identical in all terms */
1113   if (!w->pseudo_window_p)
1114     {
1115       block_input ();
1117       if (cursor_on_p)
1118         display_and_set_cursor (w, 1,
1119                                 w->output_cursor.hpos, w->output_cursor.vpos,
1120                                 w->output_cursor.x, w->output_cursor.y);
1122       if (draw_window_fringes (w, 1))
1123         {
1124           if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
1125             x_draw_right_divider (w);
1126           else
1127             x_draw_vertical_border (w);
1128         }
1130       unblock_input ();
1131     }
1133   /* If a row with mouse-face was overwritten, arrange for
1134      frame_up_to_date to redisplay the mouse highlight.  */
1135   if (mouse_face_overwritten_p)
1136     reset_mouse_highlight (MOUSE_HL_INFO (XFRAME (w->frame)));
1140 static void
1141 ns_update_end (struct frame *f)
1142 /* --------------------------------------------------------------------------
1143    Finished a grouped sequence of drawing calls
1144    external (RIF) call; for whole frame, called after update_window_end
1145    -------------------------------------------------------------------------- */
1147   EmacsView *view = FRAME_NS_VIEW (f);
1149   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_end");
1151 /*   if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
1152   MOUSE_HL_INFO (f)->mouse_face_defer = 0;
1154   block_input ();
1156   [view unlockFocus];
1157   [[view window] flushWindow];
1159   unblock_input ();
1160   ns_updating_frame = NULL;
1163 static void
1164 ns_focus (struct frame *f, NSRect *r, int n)
1165 /* --------------------------------------------------------------------------
1166    Internal: Focus on given frame.  During small local updates this is used to
1167      draw, however during large updates, ns_update_begin and ns_update_end are
1168      called to wrap the whole thing, in which case these calls are stubbed out.
1169      Except, on GNUstep, we accumulate the rectangle being drawn into, because
1170      the back end won't do this automatically, and will just end up flushing
1171      the entire window.
1172    -------------------------------------------------------------------------- */
1174   NSTRACE_WHEN (NSTRACE_GROUP_FOCUS, "ns_focus");
1175   if (r != NULL)
1176     {
1177       NSTRACE_RECT ("r", *r);
1178     }
1180   if (f != ns_updating_frame)
1181     {
1182       NSView *view = FRAME_NS_VIEW (f);
1183       if (view != focus_view)
1184         {
1185           if (focus_view != NULL)
1186             {
1187               [focus_view unlockFocus];
1188               [[focus_view window] flushWindow];
1189 /*debug_lock--; */
1190             }
1192           if (view)
1193             [view lockFocus];
1194           focus_view = view;
1195 /*if (view) debug_lock++; */
1196         }
1197     }
1199   /* clipping */
1200   if (r)
1201     {
1202       [[NSGraphicsContext currentContext] saveGraphicsState];
1203       if (n == 2)
1204         NSRectClipList (r, 2);
1205       else
1206         NSRectClip (*r);
1207       gsaved = YES;
1208     }
1212 static void
1213 ns_unfocus (struct frame *f)
1214 /* --------------------------------------------------------------------------
1215      Internal: Remove focus on given frame
1216    -------------------------------------------------------------------------- */
1218   NSTRACE_WHEN (NSTRACE_GROUP_FOCUS, "ns_unfocus");
1220   if (gsaved)
1221     {
1222       [[NSGraphicsContext currentContext] restoreGraphicsState];
1223       gsaved = NO;
1224     }
1226   if (f != ns_updating_frame)
1227     {
1228       if (focus_view != NULL)
1229         {
1230           [focus_view unlockFocus];
1231           [[focus_view window] flushWindow];
1232           focus_view = NULL;
1233 /*debug_lock--; */
1234         }
1235     }
1239 static void
1240 ns_clip_to_row (struct window *w, struct glyph_row *row,
1241                 enum glyph_row_area area, BOOL gc)
1242 /* --------------------------------------------------------------------------
1243      Internal (but parallels other terms): Focus drawing on given row
1244    -------------------------------------------------------------------------- */
1246   struct frame *f = XFRAME (WINDOW_FRAME (w));
1247   NSRect clip_rect;
1248   int window_x, window_y, window_width;
1250   window_box (w, area, &window_x, &window_y, &window_width, 0);
1252   clip_rect.origin.x = window_x;
1253   clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
1254   clip_rect.origin.y = max (clip_rect.origin.y, window_y);
1255   clip_rect.size.width = window_width;
1256   clip_rect.size.height = row->visible_height;
1258   ns_focus (f, &clip_rect, 1);
1262 /* ==========================================================================
1264     Visible bell and beep.
1266    ========================================================================== */
1269 // This bell implementation shows the visual bell image asynchronously
1270 // from the rest of Emacs. This is done by adding a NSView to the
1271 // superview of the Emacs window and removing it using a timer.
1273 // Unfortunately, some Emacs operations, like scrolling, is done using
1274 // low-level primitives that copy the content of the window, including
1275 // the bell image. To some extent, this is handled by removing the
1276 // image prior to scrolling and marking that the window is in need for
1277 // redisplay.
1279 // To test this code, make sure that there is no artifacts of the bell
1280 // image in the following situations. Use a non-empty buffer (like the
1281 // tutorial) to ensure that a scroll is performed:
1283 // * Single-window: C-g C-v
1285 // * Side-by-windows: C-x 3 C-g C-v
1287 // * Windows above each other: C-x 2 C-g C-v
1289 @interface EmacsBell : NSImageView
1291   // Number of currently active bell:s.
1292   unsigned int nestCount;
1293   NSView * mView;
1294   bool isAttached;
1296 - (void)show:(NSView *)view;
1297 - (void)hide;
1298 - (void)remove;
1299 @end
1301 @implementation EmacsBell
1303 - (id)init;
1305   NSTRACE ("[EmacsBell init]");
1306   if ((self = [super init]))
1307     {
1308       nestCount = 0;
1309       isAttached = false;
1310 #ifdef NS_IMPL_GNUSTEP
1311       // GNUstep doesn't provide named images.  This was reported in
1312       // 2011, see https://savannah.gnu.org/bugs/?33396
1313       //
1314       // As a drop in replacement, a semitransparent gray square is used.
1315       self.image = [[NSImage alloc] initWithSize:NSMakeSize(32 * 5, 32 * 5)];
1316       [self.image lockFocus];
1317       [[NSColor colorForEmacsRed:0.5 green:0.5 blue:0.5 alpha:0.5] set];
1318       NSRectFill(NSMakeRect(0, 0, 32, 32));
1319       [self.image unlockFocus];
1320 #else
1321       self.image = [NSImage imageNamed:NSImageNameCaution];
1322       [self.image setSize:NSMakeSize(self.image.size.width * 5,
1323                                      self.image.size.height * 5)];
1324 #endif
1325     }
1326   return self;
1329 - (void)show:(NSView *)view
1331   NSTRACE ("[EmacsBell show:]");
1332   NSTRACE_MSG ("nestCount: %u", nestCount);
1334   // Show the image, unless it's already shown.
1335   if (nestCount == 0)
1336     {
1337       NSRect rect = [view bounds];
1338       NSPoint pos;
1339       pos.x = rect.origin.x + (rect.size.width  - self.image.size.width )/2;
1340       pos.y = rect.origin.y + (rect.size.height - self.image.size.height)/2;
1342       [self setFrameOrigin:pos];
1343       [self setFrameSize:self.image.size];
1345       isAttached = true;
1346       mView = view;
1347       [[[view window] contentView] addSubview:self
1348                                    positioned:NSWindowAbove
1349                                    relativeTo:nil];
1350     }
1352   ++nestCount;
1354   [self performSelector:@selector(hide) withObject:self afterDelay:0.5];
1358 - (void)hide
1360   // Note: Trace output from this method isn't shown, reason unknown.
1361   // NSTRACE ("[EmacsBell hide]");
1363   if (nestCount > 0)
1364     --nestCount;
1366   // Remove the image once the last bell became inactive.
1367   if (nestCount == 0)
1368     {
1369       [self remove];
1370     }
1374 -(void)remove
1376   NSTRACE ("[EmacsBell remove]");
1377   if (isAttached)
1378     {
1379       NSTRACE_MSG ("removeFromSuperview");
1380       [self removeFromSuperview];
1381       mView.needsDisplay = YES;
1382       isAttached = false;
1383     }
1386 @end
1389 static EmacsBell * bell_view = nil;
1391 static void
1392 ns_ring_bell (struct frame *f)
1393 /* --------------------------------------------------------------------------
1394      "Beep" routine
1395    -------------------------------------------------------------------------- */
1397   NSTRACE ("ns_ring_bell");
1398   if (visible_bell)
1399     {
1400       struct frame *frame = SELECTED_FRAME ();
1401       NSView *view;
1403       if (bell_view == nil)
1404         {
1405           bell_view = [[EmacsBell alloc] init];
1406           [bell_view retain];
1407         }
1409       block_input ();
1411       view = FRAME_NS_VIEW (frame);
1412       if (view != nil)
1413         {
1414           [bell_view show:view];
1415         }
1417       unblock_input ();
1418     }
1419   else
1420     {
1421       NSBeep ();
1422     }
1426 static void hide_bell ()
1427 /* --------------------------------------------------------------------------
1428      Ensure the bell is hidden.
1429    -------------------------------------------------------------------------- */
1431   NSTRACE ("hide_bell");
1433   if (bell_view != nil)
1434     {
1435       [bell_view remove];
1436     }
1440 /* ==========================================================================
1442     Frame / window manager related functions
1444    ========================================================================== */
1447 static void
1448 ns_raise_frame (struct frame *f)
1449 /* --------------------------------------------------------------------------
1450      Bring window to foreground and make it active
1451    -------------------------------------------------------------------------- */
1453   NSView *view;
1455   check_window_system (f);
1456   view = FRAME_NS_VIEW (f);
1457   block_input ();
1458   if (FRAME_VISIBLE_P (f))
1459     [[view window] makeKeyAndOrderFront: NSApp];
1460   unblock_input ();
1464 static void
1465 ns_lower_frame (struct frame *f)
1466 /* --------------------------------------------------------------------------
1467      Send window to back
1468    -------------------------------------------------------------------------- */
1470   NSView *view;
1472   check_window_system (f);
1473   view = FRAME_NS_VIEW (f);
1474   block_input ();
1475   [[view window] orderBack: NSApp];
1476   unblock_input ();
1480 static void
1481 ns_frame_raise_lower (struct frame *f, bool raise)
1482 /* --------------------------------------------------------------------------
1483      External (hook)
1484    -------------------------------------------------------------------------- */
1486   NSTRACE ("ns_frame_raise_lower");
1488   if (raise)
1489     ns_raise_frame (f);
1490   else
1491     ns_lower_frame (f);
1495 static void
1496 ns_frame_rehighlight (struct frame *frame)
1497 /* --------------------------------------------------------------------------
1498      External (hook): called on things like window switching within frame
1499    -------------------------------------------------------------------------- */
1501   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
1502   struct frame *old_highlight = dpyinfo->x_highlight_frame;
1504   NSTRACE ("ns_frame_rehighlight");
1505   if (dpyinfo->x_focus_frame)
1506     {
1507       dpyinfo->x_highlight_frame
1508         = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1509            ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1510            : dpyinfo->x_focus_frame);
1511       if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
1512         {
1513           fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
1514           dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
1515         }
1516     }
1517   else
1518       dpyinfo->x_highlight_frame = 0;
1520   if (dpyinfo->x_highlight_frame &&
1521          dpyinfo->x_highlight_frame != old_highlight)
1522     {
1523       if (old_highlight)
1524         {
1525           x_update_cursor (old_highlight, 1);
1526           x_set_frame_alpha (old_highlight);
1527         }
1528       if (dpyinfo->x_highlight_frame)
1529         {
1530           x_update_cursor (dpyinfo->x_highlight_frame, 1);
1531           x_set_frame_alpha (dpyinfo->x_highlight_frame);
1532         }
1533     }
1537 void
1538 x_make_frame_visible (struct frame *f)
1539 /* --------------------------------------------------------------------------
1540      External: Show the window (X11 semantics)
1541    -------------------------------------------------------------------------- */
1543   NSTRACE ("x_make_frame_visible");
1544   /* XXX: at some points in past this was not needed, as the only place that
1545      called this (frame.c:Fraise_frame ()) also called raise_lower;
1546      if this ends up the case again, comment this out again. */
1547   if (!FRAME_VISIBLE_P (f))
1548     {
1549       EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1551       SET_FRAME_VISIBLE (f, 1);
1552       ns_raise_frame (f);
1554       /* Making a new frame from a fullscreen frame will make the new frame
1555          fullscreen also.  So skip handleFS as this will print an error.  */
1556       if ([view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH
1557           && [view isFullscreen])
1558         return;
1560       if (f->want_fullscreen != FULLSCREEN_NONE)
1561         {
1562           block_input ();
1563           [view handleFS];
1564           unblock_input ();
1565         }
1566     }
1570 void
1571 x_make_frame_invisible (struct frame *f)
1572 /* --------------------------------------------------------------------------
1573      External: Hide the window (X11 semantics)
1574    -------------------------------------------------------------------------- */
1576   NSView *view;
1577   NSTRACE ("x_make_frame_invisible");
1578   check_window_system (f);
1579   view = FRAME_NS_VIEW (f);
1580   [[view window] orderOut: NSApp];
1581   SET_FRAME_VISIBLE (f, 0);
1582   SET_FRAME_ICONIFIED (f, 0);
1586 void
1587 x_iconify_frame (struct frame *f)
1588 /* --------------------------------------------------------------------------
1589      External: Iconify window
1590    -------------------------------------------------------------------------- */
1592   NSView *view;
1593   struct ns_display_info *dpyinfo;
1595   NSTRACE ("x_iconify_frame");
1596   check_window_system (f);
1597   view = FRAME_NS_VIEW (f);
1598   dpyinfo = FRAME_DISPLAY_INFO (f);
1600   if (dpyinfo->x_highlight_frame == f)
1601     dpyinfo->x_highlight_frame = 0;
1603   if ([[view window] windowNumber] <= 0)
1604     {
1605       /* the window is still deferred.  Make it very small, bring it
1606          on screen and order it out. */
1607       NSRect s = { { 100, 100}, {0, 0} };
1608       NSRect t;
1609       t = [[view window] frame];
1610       [[view window] setFrame: s display: NO];
1611       [[view window] orderBack: NSApp];
1612       [[view window] orderOut: NSApp];
1613       [[view window] setFrame: t display: NO];
1614     }
1616   /* Processing input while Emacs is being minimized can cause a
1617      crash, so block it for the duration. */
1618   block_input();
1619   [[view window] miniaturize: NSApp];
1620   unblock_input();
1623 /* Free X resources of frame F.  */
1625 void
1626 x_free_frame_resources (struct frame *f)
1628   NSView *view;
1629   struct ns_display_info *dpyinfo;
1630   Mouse_HLInfo *hlinfo;
1632   NSTRACE ("x_free_frame_resources");
1633   check_window_system (f);
1634   view = FRAME_NS_VIEW (f);
1635   dpyinfo = FRAME_DISPLAY_INFO (f);
1636   hlinfo = MOUSE_HL_INFO (f);
1638   [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1640   block_input ();
1642   free_frame_menubar (f);
1643   free_frame_faces (f);
1645   if (f == dpyinfo->x_focus_frame)
1646     dpyinfo->x_focus_frame = 0;
1647   if (f == dpyinfo->x_highlight_frame)
1648     dpyinfo->x_highlight_frame = 0;
1649   if (f == hlinfo->mouse_face_mouse_frame)
1650     reset_mouse_highlight (hlinfo);
1652   if (f->output_data.ns->miniimage != nil)
1653     [f->output_data.ns->miniimage release];
1655   [[view window] close];
1656   [view release];
1658   xfree (f->output_data.ns);
1660   unblock_input ();
1663 void
1664 x_destroy_window (struct frame *f)
1665 /* --------------------------------------------------------------------------
1666      External: Delete the window
1667    -------------------------------------------------------------------------- */
1669   NSTRACE ("x_destroy_window");
1670   check_window_system (f);
1671   x_free_frame_resources (f);
1672   ns_window_num--;
1676 void
1677 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1678 /* --------------------------------------------------------------------------
1679      External: Position the window
1680    -------------------------------------------------------------------------- */
1682   NSView *view = FRAME_NS_VIEW (f);
1683   NSArray *screens = [NSScreen screens];
1684   NSScreen *fscreen = [screens objectAtIndex: 0];
1685   NSScreen *screen = [[view window] screen];
1687   NSTRACE ("x_set_offset");
1689   block_input ();
1691   f->left_pos = xoff;
1692   f->top_pos = yoff;
1694   if (view != nil && screen && fscreen)
1695     {
1696       f->left_pos = f->size_hint_flags & XNegative
1697         ? [screen visibleFrame].size.width + f->left_pos - FRAME_PIXEL_WIDTH (f)
1698         : f->left_pos;
1699       /* We use visibleFrame here to take menu bar into account.
1700          Ideally we should also adjust left/top with visibleFrame.origin.  */
1702       f->top_pos = f->size_hint_flags & YNegative
1703         ? ([screen visibleFrame].size.height + f->top_pos
1704            - FRAME_PIXEL_HEIGHT (f) - FRAME_NS_TITLEBAR_HEIGHT (f)
1705            - FRAME_TOOLBAR_HEIGHT (f))
1706         : f->top_pos;
1707 #ifdef NS_IMPL_GNUSTEP
1708       if (f->left_pos < 100)
1709         f->left_pos = 100;  /* don't overlap menu */
1710 #endif
1711       /* Constrain the setFrameTopLeftPoint so we don't move behind the
1712          menu bar.  */
1713       NSPoint pt = NSMakePoint (SCREENMAXBOUND (f->left_pos),
1714                                 SCREENMAXBOUND ([fscreen frame].size.height
1715                                                 - NS_TOP_POS (f)));
1716       NSTRACE_POINT ("setFrameTopLeftPoint", pt);
1717       [[view window] setFrameTopLeftPoint: pt];
1718       f->size_hint_flags &= ~(XNegative|YNegative);
1719     }
1721   unblock_input ();
1725 void
1726 x_set_window_size (struct frame *f,
1727                    bool change_gravity,
1728                    int width,
1729                    int height,
1730                    bool pixelwise)
1731 /* --------------------------------------------------------------------------
1732      Adjust window pixel size based on given character grid size
1733      Impl is a bit more complex than other terms, need to do some
1734      internal clipping.
1735    -------------------------------------------------------------------------- */
1737   EmacsView *view = FRAME_NS_VIEW (f);
1738   NSWindow *window = [view window];
1739   NSRect wr = [window frame];
1740   int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1741   int pixelwidth, pixelheight;
1742   int orig_height = wr.size.height;
1744   NSTRACE ("x_set_window_size");
1746   if (view == nil)
1747     return;
1749   NSTRACE_RECT ("current", wr);
1750   NSTRACE_MSG ("Width:%d Height:%d Pixelwise:%d", width, height, pixelwise);
1751   NSTRACE_MSG ("Font %d x %d", FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f));
1753   block_input ();
1755   if (pixelwise)
1756     {
1757       pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
1758       pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
1759     }
1760   else
1761     {
1762       pixelwidth =  FRAME_TEXT_COLS_TO_PIXEL_WIDTH   (f, width);
1763       pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, height);
1764     }
1766   /* If we have a toolbar, take its height into account. */
1767   if (tb && ! [view isFullscreen])
1768     {
1769     /* NOTE: previously this would generate wrong result if toolbar not
1770              yet displayed and fixing toolbar_height=32 helped, but
1771              now (200903) seems no longer needed */
1772     FRAME_TOOLBAR_HEIGHT (f) =
1773       NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1774         - FRAME_NS_TITLEBAR_HEIGHT (f);
1775 #if 0
1776       /* Only breaks things here, removed by martin 2015-09-30.  */
1777 #ifdef NS_IMPL_GNUSTEP
1778       FRAME_TOOLBAR_HEIGHT (f) -= 3;
1779 #endif
1780 #endif
1781     }
1782   else
1783     FRAME_TOOLBAR_HEIGHT (f) = 0;
1785   wr.size.width = pixelwidth + f->border_width;
1786   wr.size.height = pixelheight;
1787   if (! [view isFullscreen])
1788     wr.size.height += FRAME_NS_TITLEBAR_HEIGHT (f)
1789       + FRAME_TOOLBAR_HEIGHT (f);
1791   /* Do not try to constrain to this screen.  We may have multiple
1792      screens, and want Emacs to span those.  Constraining to screen
1793      prevents that, and that is not nice to the user.  */
1794  if (f->output_data.ns->zooming)
1795    f->output_data.ns->zooming = 0;
1796  else
1797    wr.origin.y += orig_height - wr.size.height;
1799  frame_size_history_add
1800    (f, Qx_set_window_size_1, width, height,
1801     list5 (Fcons (make_number (pixelwidth), make_number (pixelheight)),
1802            Fcons (make_number (wr.size.width), make_number (wr.size.height)),
1803            make_number (f->border_width),
1804            make_number (FRAME_NS_TITLEBAR_HEIGHT (f)),
1805            make_number (FRAME_TOOLBAR_HEIGHT (f))));
1807   [window setFrame: wr display: YES];
1809   /* This is a trick to compensate for Emacs' managing the scrollbar area
1810      as a fixed number of standard character columns.  Instead of leaving
1811      blank space for the extra, we chopped it off above.  Now for
1812      left-hand scrollbars, we shift all rendering to the left by the
1813      difference between the real width and Emacs' imagined one.  For
1814      right-hand bars, don't worry about it since the extra is never used.
1815      (Obviously doesn't work for vertically split windows tho..) */
1816   {
1817     NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1818       ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1819                      - NS_SCROLL_BAR_WIDTH (f), 0)
1820       : NSMakePoint (0, 0);
1822     [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1823     [view setBoundsOrigin: origin];
1824   }
1826   [view updateFrameSize: NO];
1827   unblock_input ();
1831 static void
1832 ns_fullscreen_hook (struct frame *f)
1834   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1836   NSTRACE ("ns_fullscreen_hook");
1838   if (!FRAME_VISIBLE_P (f))
1839     return;
1841    if (! [view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH)
1842     {
1843       /* Old style fs don't initiate correctly if created from
1844          init/default-frame alist, so use a timer (not nice...).
1845       */
1846       [NSTimer scheduledTimerWithTimeInterval: 0.5 target: view
1847                                      selector: @selector (handleFS)
1848                                      userInfo: nil repeats: NO];
1849       return;
1850     }
1852   block_input ();
1853   [view handleFS];
1854   unblock_input ();
1857 /* ==========================================================================
1859     Color management
1861    ========================================================================== */
1864 NSColor *
1865 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1867   struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1868   if (idx < 1 || idx >= color_table->avail)
1869     return nil;
1870   return color_table->colors[idx];
1874 unsigned long
1875 ns_index_color (NSColor *color, struct frame *f)
1877   struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1878   ptrdiff_t idx;
1879   ptrdiff_t i;
1881   if (!color_table->colors)
1882     {
1883       color_table->size = NS_COLOR_CAPACITY;
1884       color_table->avail = 1; /* skip idx=0 as marker */
1885       color_table->colors = xmalloc (color_table->size * sizeof (NSColor *));
1886       color_table->colors[0] = nil;
1887       color_table->empty_indices = [[NSMutableSet alloc] init];
1888     }
1890   /* Do we already have this color?  */
1891   for (i = 1; i < color_table->avail; i++)
1892     if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1893       return i;
1895   if ([color_table->empty_indices count] > 0)
1896     {
1897       NSNumber *index = [color_table->empty_indices anyObject];
1898       [color_table->empty_indices removeObject: index];
1899       idx = [index unsignedLongValue];
1900     }
1901   else
1902     {
1903       if (color_table->avail == color_table->size)
1904         color_table->colors =
1905           xpalloc (color_table->colors, &color_table->size, 1,
1906                    min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1907       idx = color_table->avail++;
1908     }
1910   color_table->colors[idx] = color;
1911   [color retain];
1912 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1913   return idx;
1917 void
1918 ns_free_indexed_color (unsigned long idx, struct frame *f)
1920   struct ns_color_table *color_table;
1921   NSColor *color;
1922   NSNumber *index;
1924   if (!f)
1925     return;
1927   color_table = FRAME_DISPLAY_INFO (f)->color_table;
1929   if (idx <= 0 || idx >= color_table->size) {
1930     message1 ("ns_free_indexed_color: Color index out of range.\n");
1931     return;
1932   }
1934   index = [NSNumber numberWithUnsignedInt: idx];
1935   if ([color_table->empty_indices containsObject: index]) {
1936     message1 ("ns_free_indexed_color: attempt to free already freed color.\n");
1937     return;
1938   }
1940   color = color_table->colors[idx];
1941   [color release];
1942   color_table->colors[idx] = nil;
1943   [color_table->empty_indices addObject: index];
1944 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1948 static int
1949 ns_get_color (const char *name, NSColor **col)
1950 /* --------------------------------------------------------------------------
1951      Parse a color name
1952    -------------------------------------------------------------------------- */
1953 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1954    X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1955    See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1957   NSColor *new = nil;
1958   static char hex[20];
1959   int scaling = 0;
1960   float r = -1.0, g, b;
1961   NSString *nsname = [NSString stringWithUTF8String: name];
1963   NSTRACE ("ns_get_color(%s, **)", name);
1965   block_input ();
1967   if ([nsname isEqualToString: @"ns_selection_bg_color"])
1968     {
1969 #ifdef NS_IMPL_COCOA
1970       NSString *defname = [[NSUserDefaults standardUserDefaults]
1971                             stringForKey: @"AppleHighlightColor"];
1972       if (defname != nil)
1973         nsname = defname;
1974       else
1975 #endif
1976       if ((new = [NSColor selectedTextBackgroundColor]) != nil)
1977         {
1978           *col = [new colorUsingDefaultColorSpace];
1979           unblock_input ();
1980           return 0;
1981         }
1982       else
1983         nsname = NS_SELECTION_BG_COLOR_DEFAULT;
1985       name = [nsname UTF8String];
1986     }
1987   else if ([nsname isEqualToString: @"ns_selection_fg_color"])
1988     {
1989       /* NOTE: macOS applications normally don't set foreground
1990          selection, but text may be unreadable if we don't.
1991       */
1992       if ((new = [NSColor selectedTextColor]) != nil)
1993         {
1994           *col = [new colorUsingDefaultColorSpace];
1995           unblock_input ();
1996           return 0;
1997         }
1999       nsname = NS_SELECTION_FG_COLOR_DEFAULT;
2000       name = [nsname UTF8String];
2001     }
2003   /* First, check for some sort of numeric specification. */
2004   hex[0] = '\0';
2006   if (name[0] == '0' || name[0] == '1' || name[0] == '.')  /* RGB decimal */
2007     {
2008       NSScanner *scanner = [NSScanner scannerWithString: nsname];
2009       [scanner scanFloat: &r];
2010       [scanner scanFloat: &g];
2011       [scanner scanFloat: &b];
2012     }
2013   else if (!strncmp(name, "rgb:", 4))  /* A newer X11 format -- rgb:r/g/b */
2014     scaling = (snprintf (hex, sizeof hex, "%s", name + 4) - 2) / 3;
2015   else if (name[0] == '#')        /* An old X11 format; convert to newer */
2016     {
2017       int len = (strlen(name) - 1);
2018       int start = (len % 3 == 0) ? 1 : len / 4 + 1;
2019       int i;
2020       scaling = strlen(name+start) / 3;
2021       for (i = 0; i < 3; i++)
2022         sprintf (hex + i * (scaling + 1), "%.*s/", scaling,
2023                  name + start + i * scaling);
2024       hex[3 * (scaling + 1) - 1] = '\0';
2025     }
2027   if (hex[0])
2028     {
2029       int rr, gg, bb;
2030       float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
2031       if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
2032         {
2033           r = rr / fscale;
2034           g = gg / fscale;
2035           b = bb / fscale;
2036         }
2037     }
2039   if (r >= 0.0F)
2040     {
2041       *col = [NSColor colorForEmacsRed: r green: g blue: b alpha: 1.0];
2042       unblock_input ();
2043       return 0;
2044     }
2046   /* Otherwise, color is expected to be from a list */
2047   {
2048     NSEnumerator *lenum, *cenum;
2049     NSString *name;
2050     NSColorList *clist;
2052 #ifdef NS_IMPL_GNUSTEP
2053     /* XXX: who is wrong, the requestor or the implementation? */
2054     if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
2055         == NSOrderedSame)
2056       nsname = @"highlightColor";
2057 #endif
2059     lenum = [[NSColorList availableColorLists] objectEnumerator];
2060     while ( (clist = [lenum nextObject]) && new == nil)
2061       {
2062         cenum = [[clist allKeys] objectEnumerator];
2063         while ( (name = [cenum nextObject]) && new == nil )
2064           {
2065             if ([name compare: nsname
2066                       options: NSCaseInsensitiveSearch] == NSOrderedSame )
2067               new = [clist colorWithKey: name];
2068           }
2069       }
2070   }
2072   if (new)
2073     *col = [new colorUsingDefaultColorSpace];
2074   unblock_input ();
2075   return new ? 0 : 1;
2080 ns_lisp_to_color (Lisp_Object color, NSColor **col)
2081 /* --------------------------------------------------------------------------
2082      Convert a Lisp string object to a NS color
2083    -------------------------------------------------------------------------- */
2085   NSTRACE ("ns_lisp_to_color");
2086   if (STRINGP (color))
2087     return ns_get_color (SSDATA (color), col);
2088   else if (SYMBOLP (color))
2089     return ns_get_color (SSDATA (SYMBOL_NAME (color)), col);
2090   return 1;
2094 Lisp_Object
2095 ns_color_to_lisp (NSColor *col)
2096 /* --------------------------------------------------------------------------
2097      Convert a color to a lisp string with the RGB equivalent
2098    -------------------------------------------------------------------------- */
2100   EmacsCGFloat red, green, blue, alpha, gray;
2101   char buf[1024];
2102   const char *str;
2103   NSTRACE ("ns_color_to_lisp");
2105   block_input ();
2106   if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
2108       if ((str =[[col colorNameComponent] UTF8String]))
2109         {
2110           unblock_input ();
2111           return build_string ((char *)str);
2112         }
2114     [[col colorUsingDefaultColorSpace]
2115         getRed: &red green: &green blue: &blue alpha: &alpha];
2116   if (red == green && red == blue)
2117     {
2118       [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
2119             getWhite: &gray alpha: &alpha];
2120       snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
2121                 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
2122       unblock_input ();
2123       return build_string (buf);
2124     }
2126   snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
2127             lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
2129   unblock_input ();
2130   return build_string (buf);
2134 void
2135 ns_query_color(void *col, XColor *color_def, int setPixel)
2136 /* --------------------------------------------------------------------------
2137          Get ARGB values out of NSColor col and put them into color_def.
2138          If setPixel, set the pixel to a concatenated version.
2139          and set color_def pixel to the resulting index.
2140    -------------------------------------------------------------------------- */
2142   EmacsCGFloat r, g, b, a;
2144   [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
2145   color_def->red   = r * 65535;
2146   color_def->green = g * 65535;
2147   color_def->blue  = b * 65535;
2149   if (setPixel == YES)
2150     color_def->pixel
2151       = ARGB_TO_ULONG((int)(a*255),
2152                       (int)(r*255), (int)(g*255), (int)(b*255));
2156 bool
2157 ns_defined_color (struct frame *f,
2158                   const char *name,
2159                   XColor *color_def,
2160                   bool alloc,
2161                   bool makeIndex)
2162 /* --------------------------------------------------------------------------
2163          Return true if named color found, and set color_def rgb accordingly.
2164          If makeIndex and alloc are nonzero put the color in the color_table,
2165          and set color_def pixel to the resulting index.
2166          If makeIndex is zero, set color_def pixel to ARGB.
2167          Return false if not found
2168    -------------------------------------------------------------------------- */
2170   NSColor *col;
2171   NSTRACE_WHEN (NSTRACE_GROUP_COLOR, "ns_defined_color");
2173   block_input ();
2174   if (ns_get_color (name, &col) != 0) /* Color not found  */
2175     {
2176       unblock_input ();
2177       return 0;
2178     }
2179   if (makeIndex && alloc)
2180     color_def->pixel = ns_index_color (col, f);
2181   ns_query_color (col, color_def, !makeIndex);
2182   unblock_input ();
2183   return 1;
2187 void
2188 x_set_frame_alpha (struct frame *f)
2189 /* --------------------------------------------------------------------------
2190      change the entire-frame transparency
2191    -------------------------------------------------------------------------- */
2193   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2194   double alpha = 1.0;
2195   double alpha_min = 1.0;
2197   NSTRACE ("x_set_frame_alpha");
2199   if (dpyinfo->x_highlight_frame == f)
2200     alpha = f->alpha[0];
2201   else
2202     alpha = f->alpha[1];
2204   if (FLOATP (Vframe_alpha_lower_limit))
2205     alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
2206   else if (INTEGERP (Vframe_alpha_lower_limit))
2207     alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
2209   if (alpha < 0.0)
2210     return;
2211   else if (1.0 < alpha)
2212     alpha = 1.0;
2213   else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
2214     alpha = alpha_min;
2216 #ifdef NS_IMPL_COCOA
2217   {
2218     EmacsView *view = FRAME_NS_VIEW (f);
2219   [[view window] setAlphaValue: alpha];
2220   }
2221 #endif
2225 /* ==========================================================================
2227     Mouse handling
2229    ========================================================================== */
2232 void
2233 frame_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
2234 /* --------------------------------------------------------------------------
2235      Programmatically reposition mouse pointer in pixel coordinates
2236    -------------------------------------------------------------------------- */
2238   NSTRACE ("frame_set_mouse_pixel_position");
2239   ns_raise_frame (f);
2240 #if 0
2241   /* FIXME: this does not work, and what about GNUstep? */
2242 #ifdef NS_IMPL_COCOA
2243   [FRAME_NS_VIEW (f) lockFocus];
2244   PSsetmouse ((float)pix_x, (float)pix_y);
2245   [FRAME_NS_VIEW (f) unlockFocus];
2246 #endif
2247 #endif
2250 static int
2251 note_mouse_movement (struct frame *frame, CGFloat x, CGFloat y)
2252 /*   ------------------------------------------------------------------------
2253      Called by EmacsView on mouseMovement events.  Passes on
2254      to emacs mainstream code if we moved off of a rect of interest
2255      known as last_mouse_glyph.
2256      ------------------------------------------------------------------------ */
2258   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
2259   NSRect *r;
2261 //  NSTRACE ("note_mouse_movement");
2263   dpyinfo->last_mouse_motion_frame = frame;
2264   r = &dpyinfo->last_mouse_glyph;
2266   /* Note, this doesn't get called for enter/leave, since we don't have a
2267      position.  Those are taken care of in the corresponding NSView methods. */
2269   /* has movement gone beyond last rect we were tracking? */
2270   if (x < r->origin.x || x >= r->origin.x + r->size.width
2271       || y < r->origin.y || y >= r->origin.y + r->size.height)
2272     {
2273       ns_update_begin (frame);
2274       frame->mouse_moved = 1;
2275       note_mouse_highlight (frame, x, y);
2276       remember_mouse_glyph (frame, x, y, r);
2277       ns_update_end (frame);
2278       return 1;
2279     }
2281   return 0;
2285 static void
2286 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
2287                    enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
2288                    Time *time)
2289 /* --------------------------------------------------------------------------
2290     External (hook): inform emacs about mouse position and hit parts.
2291     If a scrollbar is being dragged, set bar_window, part, x, y, time.
2292     x & y should be position in the scrollbar (the whole bar, not the handle)
2293     and length of scrollbar respectively
2294    -------------------------------------------------------------------------- */
2296   id view;
2297   NSPoint position;
2298   Lisp_Object frame, tail;
2299   struct frame *f;
2300   struct ns_display_info *dpyinfo;
2302   NSTRACE ("ns_mouse_position");
2304   if (*fp == NULL)
2305     {
2306       fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
2307       return;
2308     }
2310   dpyinfo = FRAME_DISPLAY_INFO (*fp);
2312   block_input ();
2314   /* Clear the mouse-moved flag for every frame on this display.  */
2315   FOR_EACH_FRAME (tail, frame)
2316     if (FRAME_NS_P (XFRAME (frame))
2317         && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
2318       XFRAME (frame)->mouse_moved = 0;
2320   dpyinfo->last_mouse_scroll_bar = nil;
2321   if (dpyinfo->last_mouse_frame
2322       && FRAME_LIVE_P (dpyinfo->last_mouse_frame))
2323     f = dpyinfo->last_mouse_frame;
2324   else
2325     f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame : SELECTED_FRAME ();
2327   if (f && FRAME_NS_P (f))
2328     {
2329       view = FRAME_NS_VIEW (*fp);
2331       position = [[view window] mouseLocationOutsideOfEventStream];
2332       position = [view convertPoint: position fromView: nil];
2333       remember_mouse_glyph (f, position.x, position.y,
2334                             &dpyinfo->last_mouse_glyph);
2335       NSTRACE_POINT ("position", position);
2337       if (bar_window) *bar_window = Qnil;
2338       if (part) *part = scroll_bar_above_handle;
2340       if (x) XSETINT (*x, lrint (position.x));
2341       if (y) XSETINT (*y, lrint (position.y));
2342       if (time)
2343         *time = dpyinfo->last_mouse_movement_time;
2344       *fp = f;
2345     }
2347   unblock_input ();
2351 static void
2352 ns_frame_up_to_date (struct frame *f)
2353 /* --------------------------------------------------------------------------
2354     External (hook): Fix up mouse highlighting right after a full update.
2355     Can't use FRAME_MOUSE_UPDATE due to ns_frame_begin and ns_frame_end calls.
2356    -------------------------------------------------------------------------- */
2358   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_frame_up_to_date");
2360   if (FRAME_NS_P (f))
2361     {
2362       Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
2363       if (f == hlinfo->mouse_face_mouse_frame)
2364         {
2365           block_input ();
2366           ns_update_begin(f);
2367           note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
2368                                 hlinfo->mouse_face_mouse_x,
2369                                 hlinfo->mouse_face_mouse_y);
2370           ns_update_end(f);
2371           unblock_input ();
2372         }
2373     }
2377 static void
2378 ns_define_frame_cursor (struct frame *f, Cursor cursor)
2379 /* --------------------------------------------------------------------------
2380     External (RIF): set frame mouse pointer type.
2381    -------------------------------------------------------------------------- */
2383   NSTRACE ("ns_define_frame_cursor");
2384   if (FRAME_POINTER_TYPE (f) != cursor)
2385     {
2386       EmacsView *view = FRAME_NS_VIEW (f);
2387       FRAME_POINTER_TYPE (f) = cursor;
2388       [[view window] invalidateCursorRectsForView: view];
2389       /* Redisplay assumes this function also draws the changed frame
2390          cursor, but this function doesn't, so do it explicitly.  */
2391       x_update_cursor (f, 1);
2392     }
2397 /* ==========================================================================
2399     Keyboard handling
2401    ========================================================================== */
2404 static unsigned
2405 ns_convert_key (unsigned code)
2406 /* --------------------------------------------------------------------------
2407     Internal call used by NSView-keyDown.
2408    -------------------------------------------------------------------------- */
2410   const unsigned last_keysym = ARRAYELTS (convert_ns_to_X_keysym);
2411   unsigned keysym;
2412   /* An array would be faster, but less easy to read. */
2413   for (keysym = 0; keysym < last_keysym; keysym += 2)
2414     if (code == convert_ns_to_X_keysym[keysym])
2415       return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
2416   return 0;
2417 /* if decide to use keyCode and Carbon table, use this line:
2418      return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
2422 char *
2423 x_get_keysym_name (int keysym)
2424 /* --------------------------------------------------------------------------
2425     Called by keyboard.c.  Not sure if the return val is important, except
2426     that it be unique.
2427    -------------------------------------------------------------------------- */
2429   static char value[16];
2430   NSTRACE ("x_get_keysym_name");
2431   sprintf (value, "%d", keysym);
2432   return value;
2437 /* ==========================================================================
2439     Block drawing operations
2441    ========================================================================== */
2444 static void
2445 ns_redraw_scroll_bars (struct frame *f)
2447   int i;
2448   id view;
2449   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
2450   NSTRACE ("ns_redraw_scroll_bars");
2451   for (i =[subviews count]-1; i >= 0; i--)
2452     {
2453       view = [subviews objectAtIndex: i];
2454       if (![view isKindOfClass: [EmacsScroller class]]) continue;
2455       [view display];
2456     }
2460 void
2461 ns_clear_frame (struct frame *f)
2462 /* --------------------------------------------------------------------------
2463       External (hook): Erase the entire frame
2464    -------------------------------------------------------------------------- */
2466   NSView *view = FRAME_NS_VIEW (f);
2467   NSRect r;
2469   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_clear_frame");
2471  /* comes on initial frame because we have
2472     after-make-frame-functions = select-frame */
2473  if (!FRAME_DEFAULT_FACE (f))
2474    return;
2476   mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2478   r = [view bounds];
2480   block_input ();
2481   ns_focus (f, &r, 1);
2482   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
2483   NSRectFill (r);
2484   ns_unfocus (f);
2486   /* as of 2006/11 or so this is now needed */
2487   ns_redraw_scroll_bars (f);
2488   unblock_input ();
2492 static void
2493 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2494 /* --------------------------------------------------------------------------
2495     External (RIF):  Clear section of frame
2496    -------------------------------------------------------------------------- */
2498   NSRect r = NSMakeRect (x, y, width, height);
2499   NSView *view = FRAME_NS_VIEW (f);
2500   struct face *face = FRAME_DEFAULT_FACE (f);
2502   if (!view || !face)
2503     return;
2505   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_clear_frame_area");
2507   r = NSIntersectionRect (r, [view frame]);
2508   ns_focus (f, &r, 1);
2509   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2511   NSRectFill (r);
2513   ns_unfocus (f);
2514   return;
2517 static void
2518 ns_copy_bits (struct frame *f, NSRect src, NSRect dest)
2520   NSTRACE ("ns_copy_bits");
2522   if (FRAME_NS_VIEW (f))
2523     {
2524       hide_bell();              // Ensure the bell image isn't scrolled.
2526       ns_focus (f, &dest, 1);
2527       [FRAME_NS_VIEW (f) scrollRect: src
2528                                  by: NSMakeSize (dest.origin.x - src.origin.x,
2529                                                  dest.origin.y - src.origin.y)];
2530       ns_unfocus (f);
2531     }
2534 static void
2535 ns_scroll_run (struct window *w, struct run *run)
2536 /* --------------------------------------------------------------------------
2537     External (RIF):  Insert or delete n lines at line vpos
2538    -------------------------------------------------------------------------- */
2540   struct frame *f = XFRAME (w->frame);
2541   int x, y, width, height, from_y, to_y, bottom_y;
2543   NSTRACE ("ns_scroll_run");
2545   /* begin copy from other terms */
2546   /* Get frame-relative bounding box of the text display area of W,
2547      without mode lines.  Include in this box the left and right
2548      fringe of W.  */
2549   window_box (w, ANY_AREA, &x, &y, &width, &height);
2551   from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2552   to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2553   bottom_y = y + height;
2555   if (to_y < from_y)
2556     {
2557       /* Scrolling up.  Make sure we don't copy part of the mode
2558          line at the bottom.  */
2559       if (from_y + run->height > bottom_y)
2560         height = bottom_y - from_y;
2561       else
2562         height = run->height;
2563     }
2564   else
2565     {
2566       /* Scrolling down.  Make sure we don't copy over the mode line.
2567          at the bottom.  */
2568       if (to_y + run->height > bottom_y)
2569         height = bottom_y - to_y;
2570       else
2571         height = run->height;
2572     }
2573   /* end copy from other terms */
2575   if (height == 0)
2576       return;
2578   block_input ();
2580   x_clear_cursor (w);
2582   {
2583     NSRect srcRect = NSMakeRect (x, from_y, width, height);
2584     NSRect dstRect = NSMakeRect (x, to_y, width, height);
2586     ns_copy_bits (f, srcRect , dstRect);
2587   }
2589   unblock_input ();
2593 static void
2594 ns_after_update_window_line (struct window *w, struct glyph_row *desired_row)
2595 /* --------------------------------------------------------------------------
2596     External (RIF): preparatory to fringe update after text was updated
2597    -------------------------------------------------------------------------- */
2599   struct frame *f;
2600   int width, height;
2602   NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_after_update_window_line");
2604   /* begin copy from other terms */
2605   eassert (w);
2607   if (!desired_row->mode_line_p && !w->pseudo_window_p)
2608     desired_row->redraw_fringe_bitmaps_p = 1;
2610   /* When a window has disappeared, make sure that no rest of
2611      full-width rows stays visible in the internal border.  */
2612   if (windows_or_buffers_changed
2613       && desired_row->full_width_p
2614       && (f = XFRAME (w->frame),
2615           width = FRAME_INTERNAL_BORDER_WIDTH (f),
2616           width != 0)
2617       && (height = desired_row->visible_height,
2618           height > 0))
2619     {
2620       int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2622       block_input ();
2623       ns_clear_frame_area (f, 0, y, width, height);
2624       ns_clear_frame_area (f,
2625                            FRAME_PIXEL_WIDTH (f) - width,
2626                            y, width, height);
2627       unblock_input ();
2628     }
2632 static void
2633 ns_shift_glyphs_for_insert (struct frame *f,
2634                            int x, int y, int width, int height,
2635                            int shift_by)
2636 /* --------------------------------------------------------------------------
2637     External (RIF): copy an area horizontally, don't worry about clearing src
2638    -------------------------------------------------------------------------- */
2640   NSRect srcRect = NSMakeRect (x, y, width, height);
2641   NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2643   NSTRACE ("ns_shift_glyphs_for_insert");
2645   ns_copy_bits (f, srcRect, dstRect);
2650 /* ==========================================================================
2652     Character encoding and metrics
2654    ========================================================================== */
2657 static void
2658 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2659 /* --------------------------------------------------------------------------
2660      External (RIF); compute left/right overhang of whole string and set in s
2661    -------------------------------------------------------------------------- */
2663   struct font *font = s->font;
2665   if (s->char2b)
2666     {
2667       struct font_metrics metrics;
2668       unsigned int codes[2];
2669       codes[0] = *(s->char2b);
2670       codes[1] = *(s->char2b + s->nchars - 1);
2672       font->driver->text_extents (font, codes, 2, &metrics);
2673       s->left_overhang = -metrics.lbearing;
2674       s->right_overhang
2675         = metrics.rbearing > metrics.width
2676         ? metrics.rbearing - metrics.width : 0;
2677     }
2678   else
2679     {
2680       s->left_overhang = 0;
2681       if (EQ (font->driver->type, Qns))
2682         s->right_overhang = ((struct nsfont_info *)font)->ital ?
2683           FONT_HEIGHT (font) * 0.2 : 0;
2684       else
2685         s->right_overhang = 0;
2686     }
2691 /* ==========================================================================
2693     Fringe and cursor drawing
2695    ========================================================================== */
2698 extern int max_used_fringe_bitmap;
2699 static void
2700 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2701                       struct draw_fringe_bitmap_params *p)
2702 /* --------------------------------------------------------------------------
2703     External (RIF); fringe-related
2704    -------------------------------------------------------------------------- */
2706   /* Fringe bitmaps comes in two variants, normal and periodic.  A
2707      periodic bitmap is used to create a continuous pattern.  Since a
2708      bitmap is rendered one text line at a time, the start offset (dh)
2709      of the bitmap varies.  Concretely, this is used for the empty
2710      line indicator.
2712      For a bitmap, "h + dh" is the full height and is always
2713      invariant.  For a normal bitmap "dh" is zero.
2715      For example, when the period is three and the full height is 72
2716      the following combinations exists:
2718        h=72 dh=0
2719        h=71 dh=1
2720        h=70 dh=2 */
2722   struct frame *f = XFRAME (WINDOW_FRAME (w));
2723   struct face *face = p->face;
2724   static EmacsImage **bimgs = NULL;
2725   static int nBimgs = 0;
2727   NSTRACE_WHEN (NSTRACE_GROUP_FRINGE, "ns_draw_fringe_bitmap");
2728   NSTRACE_MSG ("which:%d cursor:%d overlay:%d width:%d height:%d period:%d",
2729                p->which, p->cursor_p, p->overlay_p, p->wd, p->h, p->dh);
2731   /* grow bimgs if needed */
2732   if (nBimgs < max_used_fringe_bitmap)
2733     {
2734       bimgs = xrealloc (bimgs, max_used_fringe_bitmap * sizeof *bimgs);
2735       memset (bimgs + nBimgs, 0,
2736               (max_used_fringe_bitmap - nBimgs) * sizeof *bimgs);
2737       nBimgs = max_used_fringe_bitmap;
2738     }
2740   /* Must clip because of partially visible lines.  */
2741   ns_clip_to_row (w, row, ANY_AREA, YES);
2743   if (!p->overlay_p)
2744     {
2745       int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
2747       if (bx >= 0 && nx > 0)
2748         {
2749           NSRect r = NSMakeRect (bx, by, nx, ny);
2750           NSRectClip (r);
2751           [ns_lookup_indexed_color (face->background, f) set];
2752           NSRectFill (r);
2753         }
2754     }
2756   if (p->which)
2757     {
2758       NSRect r = NSMakeRect (p->x, p->y, p->wd, p->h);
2759       EmacsImage *img = bimgs[p->which - 1];
2761       if (!img)
2762         {
2763           // Note: For "periodic" images, allocate one EmacsImage for
2764           // the base image, and use it for all dh:s.
2765           unsigned short *bits = p->bits;
2766           int full_height = p->h + p->dh;
2767           int i;
2768           unsigned char *cbits = xmalloc (full_height);
2770           for (i = 0; i < full_height; i++)
2771             cbits[i] = bits[i];
2772           img = [[EmacsImage alloc] initFromXBM: cbits width: 8
2773                                          height: full_height
2774                                              fg: 0 bg: 0];
2775           bimgs[p->which - 1] = img;
2776           xfree (cbits);
2777         }
2779       NSTRACE_RECT ("r", r);
2781       NSRectClip (r);
2782       /* Since we composite the bitmap instead of just blitting it, we need
2783          to erase the whole background. */
2784       [ns_lookup_indexed_color(face->background, f) set];
2785       NSRectFill (r);
2787       {
2788         NSColor *bm_color;
2789         if (!p->cursor_p)
2790           bm_color = ns_lookup_indexed_color(face->foreground, f);
2791         else if (p->overlay_p)
2792           bm_color = ns_lookup_indexed_color(face->background, f);
2793         else
2794           bm_color = f->output_data.ns->cursor_color;
2795         [img setXBMColor: bm_color];
2796       }
2798 #ifdef NS_IMPL_COCOA
2799       // Note: For periodic images, the full image height is "h + hd".
2800       // By using the height h, a suitable part of the image is used.
2801       NSRect fromRect = NSMakeRect(0, 0, p->wd, p->h);
2803       NSTRACE_RECT ("fromRect", fromRect);
2805       [img drawInRect: r
2806               fromRect: fromRect
2807              operation: NSCompositeSourceOver
2808               fraction: 1.0
2809            respectFlipped: YES
2810                 hints: nil];
2811 #else
2812       {
2813         NSPoint pt = r.origin;
2814         pt.y += p->h;
2815         [img compositeToPoint: pt operation: NSCompositeSourceOver];
2816       }
2817 #endif
2818     }
2819   ns_unfocus (f);
2823 static void
2824 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2825                        int x, int y, enum text_cursor_kinds cursor_type,
2826                        int cursor_width, bool on_p, bool active_p)
2827 /* --------------------------------------------------------------------------
2828      External call (RIF): draw cursor.
2829      Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2830    -------------------------------------------------------------------------- */
2832   NSRect r, s;
2833   int fx, fy, h, cursor_height;
2834   struct frame *f = WINDOW_XFRAME (w);
2835   struct glyph *phys_cursor_glyph;
2836   struct glyph *cursor_glyph;
2837   struct face *face;
2838   NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2840   /* If cursor is out of bounds, don't draw garbage.  This can happen
2841      in mini-buffer windows when switching between echo area glyphs
2842      and mini-buffer.  */
2844   NSTRACE ("ns_draw_window_cursor");
2846   if (!on_p)
2847     return;
2849   w->phys_cursor_type = cursor_type;
2850   w->phys_cursor_on_p = on_p;
2852   if (cursor_type == NO_CURSOR)
2853     {
2854       w->phys_cursor_width = 0;
2855       return;
2856     }
2858   if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2859     {
2860       if (glyph_row->exact_window_width_line_p
2861           && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2862         {
2863           glyph_row->cursor_in_fringe_p = 1;
2864           draw_fringe_bitmap (w, glyph_row, 0);
2865         }
2866       return;
2867     }
2869   /* We draw the cursor (with NSRectFill), then draw the glyph on top
2870      (other terminals do it the other way round).  We must set
2871      w->phys_cursor_width to the cursor width.  For bar cursors, that
2872      is CURSOR_WIDTH; for box cursors, it is the glyph width.  */
2873   get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2875   /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2876      to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2877   if (cursor_type == BAR_CURSOR)
2878     {
2879       if (cursor_width < 1)
2880         cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2881       w->phys_cursor_width = cursor_width;
2882     }
2883   /* If we have an HBAR, "cursor_width" MAY specify height. */
2884   else if (cursor_type == HBAR_CURSOR)
2885     {
2886       cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2887       if (cursor_height > glyph_row->height)
2888         cursor_height = glyph_row->height;
2889       if (h > cursor_height) // Cursor smaller than line height, move down
2890         fy += h - cursor_height;
2891       h = cursor_height;
2892     }
2894   r.origin.x = fx, r.origin.y = fy;
2895   r.size.height = h;
2896   r.size.width = w->phys_cursor_width;
2898   /* TODO: only needed in rare cases with last-resort font in HELLO..
2899      should we do this more efficiently? */
2900   ns_clip_to_row (w, glyph_row, ANY_AREA, NO); /* do ns_focus(f, &r, 1); if remove */
2903   face = FACE_FROM_ID (f, phys_cursor_glyph->face_id);
2904   if (face && NS_FACE_BACKGROUND (face)
2905       == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2906     {
2907       [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2908       hollow_color = FRAME_CURSOR_COLOR (f);
2909     }
2910   else
2911     [FRAME_CURSOR_COLOR (f) set];
2913 #ifdef NS_IMPL_COCOA
2914   /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2915            atomic.  Cleaner ways of doing this should be investigated.
2916            One way would be to set a global variable DRAWING_CURSOR
2917            when making the call to draw_phys..(), don't focus in that
2918            case, then move the ns_unfocus() here after that call. */
2919   NSDisableScreenUpdates ();
2920 #endif
2922   switch (cursor_type)
2923     {
2924     case DEFAULT_CURSOR:
2925     case NO_CURSOR:
2926       break;
2927     case FILLED_BOX_CURSOR:
2928       NSRectFill (r);
2929       break;
2930     case HOLLOW_BOX_CURSOR:
2931       NSRectFill (r);
2932       [hollow_color set];
2933       NSRectFill (NSInsetRect (r, 1, 1));
2934       [FRAME_CURSOR_COLOR (f) set];
2935       break;
2936     case HBAR_CURSOR:
2937       NSRectFill (r);
2938       break;
2939     case BAR_CURSOR:
2940       s = r;
2941       /* If the character under cursor is R2L, draw the bar cursor
2942          on the right of its glyph, rather than on the left.  */
2943       cursor_glyph = get_phys_cursor_glyph (w);
2944       if ((cursor_glyph->resolved_level & 1) != 0)
2945         s.origin.x += cursor_glyph->pixel_width - s.size.width;
2947       NSRectFill (s);
2948       break;
2949     }
2950   ns_unfocus (f);
2952   /* draw the character under the cursor */
2953   if (cursor_type != NO_CURSOR)
2954     draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2956 #ifdef NS_IMPL_COCOA
2957   NSEnableScreenUpdates ();
2958 #endif
2963 static void
2964 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2965 /* --------------------------------------------------------------------------
2966      External (RIF): Draw a vertical line.
2967    -------------------------------------------------------------------------- */
2969   struct frame *f = XFRAME (WINDOW_FRAME (w));
2970   struct face *face;
2971   NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2973   NSTRACE ("ns_draw_vertical_window_border");
2975   face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2976   if (face)
2977       [ns_lookup_indexed_color(face->foreground, f) set];
2979   ns_focus (f, &r, 1);
2980   NSRectFill(r);
2981   ns_unfocus (f);
2985 static void
2986 ns_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
2987 /* --------------------------------------------------------------------------
2988      External (RIF): Draw a window divider.
2989    -------------------------------------------------------------------------- */
2991   struct frame *f = XFRAME (WINDOW_FRAME (w));
2992   struct face *face;
2993   NSRect r = NSMakeRect (x0, y0, x1-x0, y1-y0);
2995   NSTRACE ("ns_draw_window_divider");
2997   face = FACE_FROM_ID (f, WINDOW_DIVIDER_FACE_ID);
2998   if (face)
2999       [ns_lookup_indexed_color(face->foreground, f) set];
3001   ns_focus (f, &r, 1);
3002   NSRectFill(r);
3003   ns_unfocus (f);
3006 static void
3007 ns_show_hourglass (struct frame *f)
3009   /* TODO: add NSProgressIndicator to all frames.  */
3012 static void
3013 ns_hide_hourglass (struct frame *f)
3015   /* TODO: remove NSProgressIndicator from all frames.  */
3018 /* ==========================================================================
3020     Glyph drawing operations
3022    ========================================================================== */
3024 static int
3025 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
3026 /* --------------------------------------------------------------------------
3027     Wrapper utility to account for internal border width on full-width lines,
3028     and allow top full-width rows to hit the frame top.  nr should be pointer
3029     to two successive NSRects.  Number of rects actually used is returned.
3030    -------------------------------------------------------------------------- */
3032   int n = get_glyph_string_clip_rects (s, nr, 2);
3033   return n;
3036 /* --------------------------------------------------------------------
3037    Draw a wavy line under glyph string s. The wave fills wave_height
3038    pixels from y.
3040                     x          wave_length = 2
3041                                  --
3042                 y    *   *   *   *   *
3043                      |* * * * * * * * *
3044     wave_height = 3  | *   *   *   *
3045   --------------------------------------------------------------------- */
3047 static void
3048 ns_draw_underwave (struct glyph_string *s, EmacsCGFloat width, EmacsCGFloat x)
3050   int wave_height = 3, wave_length = 2;
3051   int y, dx, dy, odd, xmax;
3052   NSPoint a, b;
3053   NSRect waveClip;
3055   dx = wave_length;
3056   dy = wave_height - 1;
3057   y =  s->ybase - wave_height + 3;
3058   xmax = x + width;
3060   /* Find and set clipping rectangle */
3061   waveClip = NSMakeRect (x, y, width, wave_height);
3062   [[NSGraphicsContext currentContext] saveGraphicsState];
3063   NSRectClip (waveClip);
3065   /* Draw the waves */
3066   a.x = x - ((int)(x) % dx) + (EmacsCGFloat) 0.5;
3067   b.x = a.x + dx;
3068   odd = (int)(a.x/dx) % 2;
3069   a.y = b.y = y + 0.5;
3071   if (odd)
3072     a.y += dy;
3073   else
3074     b.y += dy;
3076   while (a.x <= xmax)
3077     {
3078       [NSBezierPath strokeLineFromPoint:a toPoint:b];
3079       a.x = b.x, a.y = b.y;
3080       b.x += dx, b.y = y + 0.5 + odd*dy;
3081       odd = !odd;
3082     }
3084   /* Restore previous clipping rectangle(s) */
3085   [[NSGraphicsContext currentContext] restoreGraphicsState];
3090 void
3091 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
3092                          NSColor *defaultCol, CGFloat width, CGFloat x)
3093 /* --------------------------------------------------------------------------
3094    Draw underline, overline, and strike-through on glyph string s.
3095    -------------------------------------------------------------------------- */
3097   if (s->for_overlaps)
3098     return;
3100   /* Do underline. */
3101   if (face->underline_p)
3102     {
3103       if (s->face->underline_type == FACE_UNDER_WAVE)
3104         {
3105           if (face->underline_defaulted_p)
3106             [defaultCol set];
3107           else
3108             [ns_lookup_indexed_color (face->underline_color, s->f) set];
3110           ns_draw_underwave (s, width, x);
3111         }
3112       else if (s->face->underline_type == FACE_UNDER_LINE)
3113         {
3115           NSRect r;
3116           unsigned long thickness, position;
3118           /* If the prev was underlined, match its appearance. */
3119           if (s->prev && s->prev->face->underline_p
3120               && s->prev->face->underline_type == FACE_UNDER_LINE
3121               && s->prev->underline_thickness > 0)
3122             {
3123               thickness = s->prev->underline_thickness;
3124               position = s->prev->underline_position;
3125             }
3126           else
3127             {
3128               struct font *font;
3129               unsigned long descent;
3131               font=s->font;
3132               descent = s->y + s->height - s->ybase;
3134               /* Use underline thickness of font, defaulting to 1. */
3135               thickness = (font && font->underline_thickness > 0)
3136                 ? font->underline_thickness : 1;
3138               /* Determine the offset of underlining from the baseline. */
3139               if (x_underline_at_descent_line)
3140                 position = descent - thickness;
3141               else if (x_use_underline_position_properties
3142                        && font && font->underline_position >= 0)
3143                 position = font->underline_position;
3144               else if (font)
3145                 position = lround (font->descent / 2);
3146               else
3147                 position = underline_minimum_offset;
3149               position = max (position, underline_minimum_offset);
3151               /* Ensure underlining is not cropped. */
3152               if (descent <= position)
3153                 {
3154                   position = descent - 1;
3155                   thickness = 1;
3156                 }
3157               else if (descent < position + thickness)
3158                 thickness = 1;
3159             }
3161           s->underline_thickness = thickness;
3162           s->underline_position = position;
3164           r = NSMakeRect (x, s->ybase + position, width, thickness);
3166           if (face->underline_defaulted_p)
3167             [defaultCol set];
3168           else
3169             [ns_lookup_indexed_color (face->underline_color, s->f) set];
3170           NSRectFill (r);
3171         }
3172     }
3173   /* Do overline. We follow other terms in using a thickness of 1
3174      and ignoring overline_margin. */
3175   if (face->overline_p)
3176     {
3177       NSRect r;
3178       r = NSMakeRect (x, s->y, width, 1);
3180       if (face->overline_color_defaulted_p)
3181         [defaultCol set];
3182       else
3183         [ns_lookup_indexed_color (face->overline_color, s->f) set];
3184       NSRectFill (r);
3185     }
3187   /* Do strike-through.  We follow other terms for thickness and
3188      vertical position.*/
3189   if (face->strike_through_p)
3190     {
3191       NSRect r;
3192       unsigned long dy;
3194       dy = lrint ((s->height - 1) / 2);
3195       r = NSMakeRect (x, s->y + dy, width, 1);
3197       if (face->strike_through_color_defaulted_p)
3198         [defaultCol set];
3199       else
3200         [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
3201       NSRectFill (r);
3202     }
3205 static void
3206 ns_draw_box (NSRect r, CGFloat thickness, NSColor *col,
3207              char left_p, char right_p)
3208 /* --------------------------------------------------------------------------
3209     Draw an unfilled rect inside r, optionally leaving left and/or right open.
3210     Note we can't just use an NSDrawRect command, because of the possibility
3211     of some sides not being drawn, and because the rect will be filled.
3212    -------------------------------------------------------------------------- */
3214   NSRect s = r;
3215   [col set];
3217   /* top, bottom */
3218   s.size.height = thickness;
3219   NSRectFill (s);
3220   s.origin.y += r.size.height - thickness;
3221   NSRectFill (s);
3223   s.size.height = r.size.height;
3224   s.origin.y = r.origin.y;
3226   /* left, right (optional) */
3227   s.size.width = thickness;
3228   if (left_p)
3229     NSRectFill (s);
3230   if (right_p)
3231     {
3232       s.origin.x += r.size.width - thickness;
3233       NSRectFill (s);
3234     }
3238 static void
3239 ns_draw_relief (NSRect r, int thickness, char raised_p,
3240                char top_p, char bottom_p, char left_p, char right_p,
3241                struct glyph_string *s)
3242 /* --------------------------------------------------------------------------
3243     Draw a relief rect inside r, optionally leaving some sides open.
3244     Note we can't just use an NSDrawBezel command, because of the possibility
3245     of some sides not being drawn, and because the rect will be filled.
3246    -------------------------------------------------------------------------- */
3248   static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
3249   NSColor *newBaseCol = nil;
3250   NSRect sr = r;
3252   NSTRACE ("ns_draw_relief");
3254   /* set up colors */
3256   if (s->face->use_box_color_for_shadows_p)
3257     {
3258       newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
3259     }
3260 /*     else if (s->first_glyph->type == IMAGE_GLYPH
3261            && s->img->pixmap
3262            && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
3263        {
3264          newBaseCol = IMAGE_BACKGROUND  (s->img, s->f, 0);
3265        } */
3266   else
3267     {
3268       newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
3269     }
3271   if (newBaseCol == nil)
3272     newBaseCol = [NSColor grayColor];
3274   if (newBaseCol != baseCol)  /* TODO: better check */
3275     {
3276       [baseCol release];
3277       baseCol = [newBaseCol retain];
3278       [lightCol release];
3279       lightCol = [[baseCol highlightWithLevel: 0.2] retain];
3280       [darkCol release];
3281       darkCol = [[baseCol shadowWithLevel: 0.3] retain];
3282     }
3284   [(raised_p ? lightCol : darkCol) set];
3286   /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
3288   /* top */
3289   sr.size.height = thickness;
3290   if (top_p) NSRectFill (sr);
3292   /* left */
3293   sr.size.height = r.size.height;
3294   sr.size.width = thickness;
3295   if (left_p) NSRectFill (sr);
3297   [(raised_p ? darkCol : lightCol) set];
3299   /* bottom */
3300   sr.size.width = r.size.width;
3301   sr.size.height = thickness;
3302   sr.origin.y += r.size.height - thickness;
3303   if (bottom_p) NSRectFill (sr);
3305   /* right */
3306   sr.size.height = r.size.height;
3307   sr.origin.y = r.origin.y;
3308   sr.size.width = thickness;
3309   sr.origin.x += r.size.width - thickness;
3310   if (right_p) NSRectFill (sr);
3314 static void
3315 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
3316 /* --------------------------------------------------------------------------
3317       Function modeled after x_draw_glyph_string_box ().
3318       Sets up parameters for drawing.
3319    -------------------------------------------------------------------------- */
3321   int right_x, last_x;
3322   char left_p, right_p;
3323   struct glyph *last_glyph;
3324   NSRect r;
3325   int thickness;
3326   struct face *face;
3328   if (s->hl == DRAW_MOUSE_FACE)
3329     {
3330       face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3331       if (!face)
3332         face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3333     }
3334   else
3335     face = s->face;
3337   thickness = face->box_line_width;
3339   NSTRACE ("ns_dumpglyphs_box_or_relief");
3341   last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
3342             ? WINDOW_RIGHT_EDGE_X (s->w)
3343             : window_box_right (s->w, s->area));
3344   last_glyph = (s->cmp || s->img
3345                 ? s->first_glyph : s->first_glyph + s->nchars-1);
3347   right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
3348               ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
3350   left_p = (s->first_glyph->left_box_line_p
3351             || (s->hl == DRAW_MOUSE_FACE
3352                 && (s->prev == NULL || s->prev->hl != s->hl)));
3353   right_p = (last_glyph->right_box_line_p
3354              || (s->hl == DRAW_MOUSE_FACE
3355                  && (s->next == NULL || s->next->hl != s->hl)));
3357   r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
3359   /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
3360   if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
3361     {
3362       ns_draw_box (r, abs (thickness),
3363                    ns_lookup_indexed_color (face->box_color, s->f),
3364                   left_p, right_p);
3365     }
3366   else
3367     {
3368       ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
3369                      1, 1, left_p, right_p, s);
3370     }
3374 static void
3375 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
3376 /* --------------------------------------------------------------------------
3377       Modeled after x_draw_glyph_string_background, which draws BG in
3378       certain cases.  Others are left to the text rendering routine.
3379    -------------------------------------------------------------------------- */
3381   NSTRACE ("ns_maybe_dumpglyphs_background");
3383   if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
3384     {
3385       int box_line_width = max (s->face->box_line_width, 0);
3386       if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
3387           /* When xdisp.c ignores FONT_HEIGHT, we cannot trust font
3388              dimensions, since the actual glyphs might be much
3389              smaller.  So in that case we always clear the rectangle
3390              with background color.  */
3391           || FONT_TOO_HIGH (s->font)
3392           || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
3393         {
3394           struct face *face;
3395           if (s->hl == DRAW_MOUSE_FACE)
3396             {
3397               face = FACE_FROM_ID (s->f,
3398                                    MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3399               if (!face)
3400                 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3401             }
3402           else
3403             face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3404           if (!face->stipple)
3405             [(NS_FACE_BACKGROUND (face) != 0
3406               ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
3407               : FRAME_BACKGROUND_COLOR (s->f)) set];
3408           else
3409             {
3410               struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (s->f);
3411               [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
3412             }
3414           if (s->hl != DRAW_CURSOR)
3415             {
3416               NSRect r = NSMakeRect (s->x, s->y + box_line_width,
3417                                     s->background_width,
3418                                     s->height-2*box_line_width);
3419               NSRectFill (r);
3420             }
3422           s->background_filled_p = 1;
3423         }
3424     }
3428 static void
3429 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
3430 /* --------------------------------------------------------------------------
3431       Renders an image and associated borders.
3432    -------------------------------------------------------------------------- */
3434   EmacsImage *img = s->img->pixmap;
3435   int box_line_vwidth = max (s->face->box_line_width, 0);
3436   int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3437   int bg_x, bg_y, bg_height;
3438   int th;
3439   char raised_p;
3440   NSRect br;
3441   struct face *face;
3442   NSColor *tdCol;
3444   NSTRACE ("ns_dumpglyphs_image");
3446   if (s->face->box != FACE_NO_BOX
3447       && s->first_glyph->left_box_line_p && s->slice.x == 0)
3448     x += abs (s->face->box_line_width);
3450   bg_x = x;
3451   bg_y =  s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
3452   bg_height = s->height;
3453   /* other terms have this, but was causing problems w/tabbar mode */
3454   /* - 2 * box_line_vwidth; */
3456   if (s->slice.x == 0) x += s->img->hmargin;
3457   if (s->slice.y == 0) y += s->img->vmargin;
3459   /* Draw BG: if we need larger area than image itself cleared, do that,
3460      otherwise, since we composite the image under NS (instead of mucking
3461      with its background color), we must clear just the image area. */
3462   if (s->hl == DRAW_MOUSE_FACE)
3463     {
3464       face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3465       if (!face)
3466        face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3467     }
3468   else
3469     face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3471   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
3473   if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
3474       || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
3475     {
3476       br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
3477       s->background_filled_p = 1;
3478     }
3479   else
3480     {
3481       br = NSMakeRect (x, y, s->slice.width, s->slice.height);
3482     }
3484   NSRectFill (br);
3486   /* Draw the image.. do we need to draw placeholder if img ==nil? */
3487   if (img != nil)
3488     {
3489 #ifdef NS_IMPL_COCOA
3490       NSRect dr = NSMakeRect (x, y, s->slice.width, s->slice.height);
3491       NSRect ir = NSMakeRect (s->slice.x, s->slice.y,
3492                               s->slice.width, s->slice.height);
3493       [img drawInRect: dr
3494              fromRect: ir
3495              operation: NSCompositeSourceOver
3496               fraction: 1.0
3497            respectFlipped: YES
3498                 hints: nil];
3499 #else
3500       [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3501                   operation: NSCompositeSourceOver];
3502 #endif
3503     }
3505   if (s->hl == DRAW_CURSOR)
3506     {
3507     [FRAME_CURSOR_COLOR (s->f) set];
3508     if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3509       tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3510     else
3511       /* Currently on NS img->mask is always 0. Since
3512          get_window_cursor_type specifies a hollow box cursor when on
3513          a non-masked image we never reach this clause. But we put it
3514          in in anticipation of better support for image masks on
3515          NS. */
3516       tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3517     }
3518   else
3519     {
3520       tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3521     }
3523   /* Draw underline, overline, strike-through. */
3524   ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3526   /* Draw relief, if requested */
3527   if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3528     {
3529       if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3530         {
3531           th = tool_bar_button_relief >= 0 ?
3532             tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3533           raised_p = (s->hl == DRAW_IMAGE_RAISED);
3534         }
3535       else
3536         {
3537           th = abs (s->img->relief);
3538           raised_p = (s->img->relief > 0);
3539         }
3541       r.origin.x = x - th;
3542       r.origin.y = y - th;
3543       r.size.width = s->slice.width + 2*th-1;
3544       r.size.height = s->slice.height + 2*th-1;
3545       ns_draw_relief (r, th, raised_p,
3546                       s->slice.y == 0,
3547                       s->slice.y + s->slice.height == s->img->height,
3548                       s->slice.x == 0,
3549                       s->slice.x + s->slice.width == s->img->width, s);
3550     }
3552   /* If there is no mask, the background won't be seen,
3553      so draw a rectangle on the image for the cursor.
3554      Do this for all images, getting transparency right is not reliable.  */
3555   if (s->hl == DRAW_CURSOR)
3556     {
3557       int thickness = abs (s->img->relief);
3558       if (thickness == 0) thickness = 1;
3559       ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3560     }
3564 static void
3565 ns_dumpglyphs_stretch (struct glyph_string *s)
3567   NSRect r[2];
3568   int n, i;
3569   struct face *face;
3570   NSColor *fgCol, *bgCol;
3572   if (!s->background_filled_p)
3573     {
3574       n = ns_get_glyph_string_clip_rect (s, r);
3575       *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3577       ns_focus (s->f, r, n);
3579       if (s->hl == DRAW_MOUSE_FACE)
3580        {
3581          face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3582          if (!face)
3583            face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3584        }
3585       else
3586        face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3588       bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3589       fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3591       for (i = 0; i < n; ++i)
3592         {
3593           if (!s->row->full_width_p)
3594             {
3595               int overrun, leftoverrun;
3597               /* truncate to avoid overwriting fringe and/or scrollbar */
3598               overrun = max (0, (s->x + s->background_width)
3599                              - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3600                                 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3601               r[i].size.width -= overrun;
3603               /* truncate to avoid overwriting to left of the window box */
3604               leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3605                              + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3607               if (leftoverrun > 0)
3608                 {
3609                   r[i].origin.x += leftoverrun;
3610                   r[i].size.width -= leftoverrun;
3611                 }
3613               /* XXX: Try to work between problem where a stretch glyph on
3614                  a partially-visible bottom row will clear part of the
3615                  modeline, and another where list-buffers headers and similar
3616                  rows erroneously have visible_height set to 0.  Not sure
3617                  where this is coming from as other terms seem not to show. */
3618               r[i].size.height = min (s->height, s->row->visible_height);
3619             }
3621           [bgCol set];
3623           /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3624              overwriting cursor (usually when cursor on a tab) */
3625           if (s->hl == DRAW_CURSOR)
3626             {
3627               CGFloat x, width;
3629               x = r[i].origin.x;
3630               width = s->w->phys_cursor_width;
3631               r[i].size.width -= width;
3632               r[i].origin.x += width;
3634               NSRectFill (r[i]);
3636               /* Draw overlining, etc. on the cursor. */
3637               if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3638                 ns_draw_text_decoration (s, face, bgCol, width, x);
3639               else
3640                 ns_draw_text_decoration (s, face, fgCol, width, x);
3641             }
3642           else
3643             {
3644               NSRectFill (r[i]);
3645             }
3647           /* Draw overlining, etc. on the stretch glyph (or the part
3648              of the stretch glyph after the cursor). */
3649           ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3650                                    r[i].origin.x);
3651         }
3652       ns_unfocus (s->f);
3653       s->background_filled_p = 1;
3654     }
3658 static void
3659 ns_draw_composite_glyph_string_foreground (struct glyph_string *s)
3661   int i, j, x;
3662   struct font *font = s->font;
3664   /* If first glyph of S has a left box line, start drawing the text
3665      of S to the right of that box line.  */
3666   if (s->face && s->face->box != FACE_NO_BOX
3667       && s->first_glyph->left_box_line_p)
3668     x = s->x + eabs (s->face->box_line_width);
3669   else
3670     x = s->x;
3672   /* S is a glyph string for a composition.  S->cmp_from is the index
3673      of the first character drawn for glyphs of this composition.
3674      S->cmp_from == 0 means we are drawing the very first character of
3675      this composition.  */
3677   /* Draw a rectangle for the composition if the font for the very
3678      first character of the composition could not be loaded.  */
3679   if (s->font_not_found_p)
3680     {
3681       if (s->cmp_from == 0)
3682         {
3683           NSRect r = NSMakeRect (s->x, s->y, s->width-1, s->height -1);
3684           ns_draw_box (r, 1, FRAME_CURSOR_COLOR (s->f), 1, 1);
3685         }
3686     }
3687   else if (! s->first_glyph->u.cmp.automatic)
3688     {
3689       int y = s->ybase;
3691       for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
3692         /* TAB in a composition means display glyphs with padding
3693            space on the left or right.  */
3694         if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
3695           {
3696             int xx = x + s->cmp->offsets[j * 2];
3697             int yy = y - s->cmp->offsets[j * 2 + 1];
3699             font->driver->draw (s, j, j + 1, xx, yy, false);
3700             if (s->face->overstrike)
3701               font->driver->draw (s, j, j + 1, xx + 1, yy, false);
3702           }
3703     }
3704   else
3705     {
3706       Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
3707       Lisp_Object glyph;
3708       int y = s->ybase;
3709       int width = 0;
3711       for (i = j = s->cmp_from; i < s->cmp_to; i++)
3712         {
3713           glyph = LGSTRING_GLYPH (gstring, i);
3714           if (NILP (LGLYPH_ADJUSTMENT (glyph)))
3715             width += LGLYPH_WIDTH (glyph);
3716           else
3717             {
3718               int xoff, yoff, wadjust;
3720               if (j < i)
3721                 {
3722                   font->driver->draw (s, j, i, x, y, false);
3723                   if (s->face->overstrike)
3724                     font->driver->draw (s, j, i, x + 1, y, false);
3725                   x += width;
3726                 }
3727               xoff = LGLYPH_XOFF (glyph);
3728               yoff = LGLYPH_YOFF (glyph);
3729               wadjust = LGLYPH_WADJUST (glyph);
3730               font->driver->draw (s, i, i + 1, x + xoff, y + yoff, false);
3731               if (s->face->overstrike)
3732                 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff,
3733                                     false);
3734               x += wadjust;
3735               j = i + 1;
3736               width = 0;
3737             }
3738         }
3739       if (j < i)
3740         {
3741           font->driver->draw (s, j, i, x, y, false);
3742           if (s->face->overstrike)
3743             font->driver->draw (s, j, i, x + 1, y, false);
3744         }
3745     }
3748 static void
3749 ns_draw_glyph_string (struct glyph_string *s)
3750 /* --------------------------------------------------------------------------
3751       External (RIF): Main draw-text call.
3752    -------------------------------------------------------------------------- */
3754   /* TODO (optimize): focus for box and contents draw */
3755   NSRect r[2];
3756   int n, flags;
3757   char box_drawn_p = 0;
3758   struct font *font = s->face->font;
3759   if (! font) font = FRAME_FONT (s->f);
3761   NSTRACE_WHEN (NSTRACE_GROUP_GLYPHS, "ns_draw_glyph_string");
3763   if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3764     {
3765       int width;
3766       struct glyph_string *next;
3768       for (width = 0, next = s->next;
3769            next && width < s->right_overhang;
3770            width += next->width, next = next->next)
3771         if (next->first_glyph->type != IMAGE_GLYPH)
3772           {
3773             if (next->first_glyph->type != STRETCH_GLYPH)
3774               {
3775                 n = ns_get_glyph_string_clip_rect (s->next, r);
3776                 ns_focus (s->f, r, n);
3777                 ns_maybe_dumpglyphs_background (s->next, 1);
3778                 ns_unfocus (s->f);
3779               }
3780             else
3781               {
3782                 ns_dumpglyphs_stretch (s->next);
3783               }
3784             next->num_clips = 0;
3785           }
3786     }
3788   if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3789         && (s->first_glyph->type == CHAR_GLYPH
3790             || s->first_glyph->type == COMPOSITE_GLYPH))
3791     {
3792       n = ns_get_glyph_string_clip_rect (s, r);
3793       ns_focus (s->f, r, n);
3794       ns_maybe_dumpglyphs_background (s, 1);
3795       ns_dumpglyphs_box_or_relief (s);
3796       ns_unfocus (s->f);
3797       box_drawn_p = 1;
3798     }
3800   switch (s->first_glyph->type)
3801     {
3803     case IMAGE_GLYPH:
3804       n = ns_get_glyph_string_clip_rect (s, r);
3805       ns_focus (s->f, r, n);
3806       ns_dumpglyphs_image (s, r[0]);
3807       ns_unfocus (s->f);
3808       break;
3810     case STRETCH_GLYPH:
3811       ns_dumpglyphs_stretch (s);
3812       break;
3814     case CHAR_GLYPH:
3815     case COMPOSITE_GLYPH:
3816       n = ns_get_glyph_string_clip_rect (s, r);
3817       ns_focus (s->f, r, n);
3819       if (s->for_overlaps || (s->cmp_from > 0
3820                               && ! s->first_glyph->u.cmp.automatic))
3821         s->background_filled_p = 1;
3822       else
3823         ns_maybe_dumpglyphs_background
3824           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3826       flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3827         (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3828          (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3829           NS_DUMPGLYPH_NORMAL));
3831       if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3832         {
3833           unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3834           NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3835           NS_FACE_FOREGROUND (s->face) = tmp;
3836         }
3838       {
3839         BOOL isComposite = s->first_glyph->type == COMPOSITE_GLYPH;
3841         if (isComposite)
3842           ns_draw_composite_glyph_string_foreground (s);
3843         else
3844           font->driver->draw
3845             (s, s->cmp_from, s->nchars, s->x, s->ybase,
3846              (flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3847              || flags == NS_DUMPGLYPH_MOUSEFACE);
3848       }
3850       {
3851         NSColor *col = (NS_FACE_FOREGROUND (s->face) != 0
3852                         ? ns_lookup_indexed_color (NS_FACE_FOREGROUND (s->face),
3853                                                    s->f)
3854                         : FRAME_FOREGROUND_COLOR (s->f));
3855         [col set];
3857         /* Draw underline, overline, strike-through. */
3858         ns_draw_text_decoration (s, s->face, col, s->width, s->x);
3859       }
3861       if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3862         {
3863           unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3864           NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3865           NS_FACE_FOREGROUND (s->face) = tmp;
3866         }
3868       ns_unfocus (s->f);
3869       break;
3871     case GLYPHLESS_GLYPH:
3872       n = ns_get_glyph_string_clip_rect (s, r);
3873       ns_focus (s->f, r, n);
3875       if (s->for_overlaps || (s->cmp_from > 0
3876                               && ! s->first_glyph->u.cmp.automatic))
3877         s->background_filled_p = 1;
3878       else
3879         ns_maybe_dumpglyphs_background
3880           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3881       /* ... */
3882       /* Not yet implemented.  */
3883       /* ... */
3884       ns_unfocus (s->f);
3885       break;
3887     default:
3888       emacs_abort ();
3889     }
3891   /* Draw box if not done already. */
3892   if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3893     {
3894       n = ns_get_glyph_string_clip_rect (s, r);
3895       ns_focus (s->f, r, n);
3896       ns_dumpglyphs_box_or_relief (s);
3897       ns_unfocus (s->f);
3898     }
3900   s->num_clips = 0;
3905 /* ==========================================================================
3907     Event loop
3909    ========================================================================== */
3912 static void
3913 ns_send_appdefined (int value)
3914 /* --------------------------------------------------------------------------
3915     Internal: post an appdefined event which EmacsApp-sendEvent will
3916               recognize and take as a command to halt the event loop.
3917    -------------------------------------------------------------------------- */
3919   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_send_appdefined(%d)", value);
3921   // GNUstep needs postEvent to happen on the main thread.
3922   // Cocoa needs nextEventMatchingMask to happen on the main thread too.
3923   if (! [[NSThread currentThread] isMainThread])
3924     {
3925       EmacsApp *app = (EmacsApp *)NSApp;
3926       app->nextappdefined = value;
3927       [app performSelectorOnMainThread:@selector (sendFromMainThread:)
3928                             withObject:nil
3929                          waitUntilDone:YES];
3930       return;
3931     }
3933   /* Only post this event if we haven't already posted one.  This will end
3934        the [NXApp run] main loop after having processed all events queued at
3935        this moment.  */
3937 #ifdef NS_IMPL_COCOA
3938   if (! send_appdefined)
3939     {
3940       /* OS X 10.10.1 swallows the AppDefined event we are sending ourselves
3941          in certain situations (rapid incoming events).
3942          So check if we have one, if not add one.  */
3943       NSEvent *appev = [NSApp nextEventMatchingMask:NSApplicationDefinedMask
3944                                           untilDate:[NSDate distantPast]
3945                                              inMode:NSDefaultRunLoopMode
3946                                             dequeue:NO];
3947       if (! appev) send_appdefined = YES;
3948     }
3949 #endif
3951   if (send_appdefined)
3952     {
3953       NSEvent *nxev;
3955       /* We only need one NX_APPDEFINED event to stop NXApp from running.  */
3956       send_appdefined = NO;
3958       /* Don't need wakeup timer any more */
3959       if (timed_entry)
3960         {
3961           [timed_entry invalidate];
3962           [timed_entry release];
3963           timed_entry = nil;
3964         }
3966       nxev = [NSEvent otherEventWithType: NSApplicationDefined
3967                                 location: NSMakePoint (0, 0)
3968                            modifierFlags: 0
3969                                timestamp: 0
3970                             windowNumber: [[NSApp mainWindow] windowNumber]
3971                                  context: [NSApp context]
3972                                  subtype: 0
3973                                    data1: value
3974                                    data2: 0];
3976       /* Post an application defined event on the event queue.  When this is
3977          received the [NXApp run] will return, thus having processed all
3978          events which are currently queued.  */
3979       [NSApp postEvent: nxev atStart: NO];
3980     }
3983 #ifdef HAVE_NATIVE_FS
3984 static void
3985 check_native_fs ()
3987   Lisp_Object frame, tail;
3989   if (ns_last_use_native_fullscreen == ns_use_native_fullscreen)
3990     return;
3992   ns_last_use_native_fullscreen = ns_use_native_fullscreen;
3994   FOR_EACH_FRAME (tail, frame)
3995     {
3996       struct frame *f = XFRAME (frame);
3997       if (FRAME_NS_P (f))
3998         {
3999           EmacsView *view = FRAME_NS_VIEW (f);
4000           [view updateCollectionBehavior];
4001         }
4002     }
4004 #endif
4006 /* GNUstep does not have cancelTracking.  */
4007 #ifdef NS_IMPL_COCOA
4008 /* Check if menu open should be canceled or continued as normal.  */
4009 void
4010 ns_check_menu_open (NSMenu *menu)
4012   /* Click in menu bar? */
4013   NSArray *a = [[NSApp mainMenu] itemArray];
4014   int i;
4015   BOOL found = NO;
4017   if (menu == nil) // Menu tracking ended.
4018     {
4019       if (menu_will_open_state == MENU_OPENING)
4020         menu_will_open_state = MENU_NONE;
4021       return;
4022     }
4024   for (i = 0; ! found && i < [a count]; i++)
4025     found = menu == [[a objectAtIndex:i] submenu];
4026   if (found)
4027     {
4028       if (menu_will_open_state == MENU_NONE && emacs_event)
4029         {
4030           NSEvent *theEvent = [NSApp currentEvent];
4031           struct frame *emacsframe = SELECTED_FRAME ();
4033           [menu cancelTracking];
4034           menu_will_open_state = MENU_PENDING;
4035           emacs_event->kind = MENU_BAR_ACTIVATE_EVENT;
4036           EV_TRAILER (theEvent);
4038           CGEventRef ourEvent = CGEventCreate (NULL);
4039           menu_mouse_point = CGEventGetLocation (ourEvent);
4040           CFRelease (ourEvent);
4041         }
4042       else if (menu_will_open_state == MENU_OPENING)
4043         {
4044           menu_will_open_state = MENU_NONE;
4045         }
4046     }
4049 /* Redo saved menu click if state is MENU_PENDING.  */
4050 void
4051 ns_check_pending_open_menu ()
4053   if (menu_will_open_state == MENU_PENDING)
4054     {
4055       CGEventSourceRef source
4056         = CGEventSourceCreate (kCGEventSourceStateHIDSystemState);
4058       CGEventRef event = CGEventCreateMouseEvent (source,
4059                                                   kCGEventLeftMouseDown,
4060                                                   menu_mouse_point,
4061                                                   kCGMouseButtonLeft);
4062       CGEventSetType (event, kCGEventLeftMouseDown);
4063       CGEventPost (kCGHIDEventTap, event);
4064       CFRelease (event);
4065       CFRelease (source);
4067       menu_will_open_state = MENU_OPENING;
4068     }
4070 #endif /* NS_IMPL_COCOA */
4072 static void
4073 unwind_apploopnr (Lisp_Object not_used)
4075   --apploopnr;
4076   n_emacs_events_pending = 0;
4077   ns_finish_events ();
4078   q_event_ptr = NULL;
4081 static int
4082 ns_read_socket (struct terminal *terminal, struct input_event *hold_quit)
4083 /* --------------------------------------------------------------------------
4084      External (hook): Post an event to ourself and keep reading events until
4085      we read it back again.  In effect process all events which were waiting.
4086      From 21+ we have to manage the event buffer ourselves.
4087    -------------------------------------------------------------------------- */
4089   struct input_event ev;
4090   int nevents;
4092   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_read_socket");
4094 #ifdef HAVE_NATIVE_FS
4095   check_native_fs ();
4096 #endif
4098   if ([NSApp modalWindow] != nil)
4099     return -1;
4101   if (hold_event_q.nr > 0)
4102     {
4103       int i;
4104       for (i = 0; i < hold_event_q.nr; ++i)
4105         kbd_buffer_store_event_hold (&hold_event_q.q[i], hold_quit);
4106       hold_event_q.nr = 0;
4107       return i;
4108     }
4110   block_input ();
4111   n_emacs_events_pending = 0;
4112   ns_init_events (&ev);
4113   q_event_ptr = hold_quit;
4115   /* we manage autorelease pools by allocate/reallocate each time around
4116      the loop; strict nesting is occasionally violated but seems not to
4117      matter.. earlier methods using full nesting caused major memory leaks */
4118   [outerpool release];
4119   outerpool = [[NSAutoreleasePool alloc] init];
4121   /* If have pending open-file requests, attend to the next one of those. */
4122   if (ns_pending_files && [ns_pending_files count] != 0
4123       && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
4124     {
4125       [ns_pending_files removeObjectAtIndex: 0];
4126     }
4127   /* Deal with pending service requests. */
4128   else if (ns_pending_service_names && [ns_pending_service_names count] != 0
4129     && [(EmacsApp *)
4130          NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
4131                       withArg: [ns_pending_service_args objectAtIndex: 0]])
4132     {
4133       [ns_pending_service_names removeObjectAtIndex: 0];
4134       [ns_pending_service_args removeObjectAtIndex: 0];
4135     }
4136   else
4137     {
4138       ptrdiff_t specpdl_count = SPECPDL_INDEX ();
4139       /* Run and wait for events.  We must always send one NX_APPDEFINED event
4140          to ourself, otherwise [NXApp run] will never exit.  */
4141       send_appdefined = YES;
4142       ns_send_appdefined (-1);
4144       if (++apploopnr != 1)
4145         {
4146           emacs_abort ();
4147         }
4148       record_unwind_protect (unwind_apploopnr, Qt);
4149       [NSApp run];
4150       unbind_to (specpdl_count, Qnil);  /* calls unwind_apploopnr */
4151     }
4153   nevents = n_emacs_events_pending;
4154   n_emacs_events_pending = 0;
4155   ns_finish_events ();
4156   q_event_ptr = NULL;
4157   unblock_input ();
4159   return nevents;
4164 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
4165            fd_set *exceptfds, struct timespec const *timeout,
4166            sigset_t const *sigmask)
4167 /* --------------------------------------------------------------------------
4168      Replacement for select, checking for events
4169    -------------------------------------------------------------------------- */
4171   int result;
4172   int t, k, nr = 0;
4173   struct input_event event;
4174   char c;
4176   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_select");
4178 #ifdef HAVE_NATIVE_FS
4179   check_native_fs ();
4180 #endif
4182   if (hold_event_q.nr > 0)
4183     {
4184       /* We already have events pending. */
4185       raise (SIGIO);
4186       errno = EINTR;
4187       return -1;
4188     }
4190   for (k = 0; k < nfds+1; k++)
4191     {
4192       if (readfds && FD_ISSET(k, readfds)) ++nr;
4193       if (writefds && FD_ISSET(k, writefds)) ++nr;
4194     }
4196   if (NSApp == nil
4197       || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0))
4198     return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
4200   [outerpool release];
4201   outerpool = [[NSAutoreleasePool alloc] init];
4204   send_appdefined = YES;
4205   if (nr > 0)
4206     {
4207       pthread_mutex_lock (&select_mutex);
4208       select_nfds = nfds;
4209       select_valid = 0;
4210       if (readfds)
4211         {
4212           select_readfds = *readfds;
4213           select_valid += SELECT_HAVE_READ;
4214         }
4215       if (writefds)
4216         {
4217           select_writefds = *writefds;
4218           select_valid += SELECT_HAVE_WRITE;
4219         }
4221       if (timeout)
4222         {
4223           select_timeout = *timeout;
4224           select_valid += SELECT_HAVE_TMO;
4225         }
4227       pthread_mutex_unlock (&select_mutex);
4229       /* Inform fd_handler that select should be called */
4230       c = 'g';
4231       emacs_write_sig (selfds[1], &c, 1);
4232     }
4233   else if (nr == 0 && timeout)
4234     {
4235       /* No file descriptor, just a timeout, no need to wake fd_handler  */
4236       double time = timespectod (*timeout);
4237       timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
4238                                                       target: NSApp
4239                                                     selector:
4240                                   @selector (timeout_handler:)
4241                                                     userInfo: 0
4242                                                      repeats: NO]
4243                       retain];
4244     }
4245   else /* No timeout and no file descriptors, can this happen?  */
4246     {
4247       /* Send appdefined so we exit from the loop */
4248       ns_send_appdefined (-1);
4249     }
4251   block_input ();
4252   ns_init_events (&event);
4253   if (++apploopnr != 1)
4254     {
4255       emacs_abort ();
4256     }
4258   {
4259     ptrdiff_t specpdl_count = SPECPDL_INDEX ();
4260     record_unwind_protect (unwind_apploopnr, Qt);
4261     [NSApp run];
4262     unbind_to (specpdl_count, Qnil);  /* calls unwind_apploopnr */
4263   }
4265   ns_finish_events ();
4266   if (nr > 0 && readfds)
4267     {
4268       c = 's';
4269       emacs_write_sig (selfds[1], &c, 1);
4270     }
4271   unblock_input ();
4273   t = last_appdefined_event_data;
4275   if (t != NO_APPDEFINED_DATA)
4276     {
4277       last_appdefined_event_data = NO_APPDEFINED_DATA;
4279       if (t == -2)
4280         {
4281           /* The NX_APPDEFINED event we received was a timeout. */
4282           result = 0;
4283         }
4284       else if (t == -1)
4285         {
4286           /* The NX_APPDEFINED event we received was the result of
4287              at least one real input event arriving.  */
4288           errno = EINTR;
4289           result = -1;
4290         }
4291       else
4292         {
4293           /* Received back from select () in fd_handler; copy the results */
4294           pthread_mutex_lock (&select_mutex);
4295           if (readfds) *readfds = select_readfds;
4296           if (writefds) *writefds = select_writefds;
4297           pthread_mutex_unlock (&select_mutex);
4298           result = t;
4299         }
4300     }
4301   else
4302     {
4303       errno = EINTR;
4304       result = -1;
4305     }
4307   return result;
4312 /* ==========================================================================
4314     Scrollbar handling
4316    ========================================================================== */
4319 static void
4320 ns_set_vertical_scroll_bar (struct window *window,
4321                            int portion, int whole, int position)
4322 /* --------------------------------------------------------------------------
4323       External (hook): Update or add scrollbar
4324    -------------------------------------------------------------------------- */
4326   Lisp_Object win;
4327   NSRect r, v;
4328   struct frame *f = XFRAME (WINDOW_FRAME (window));
4329   EmacsView *view = FRAME_NS_VIEW (f);
4330   EmacsScroller *bar;
4331   int window_y, window_height;
4332   int top, left, height, width;
4333   BOOL update_p = YES;
4335   /* optimization; display engine sends WAY too many of these.. */
4336   if (!NILP (window->vertical_scroll_bar))
4337     {
4338       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4339       if ([bar checkSamePosition: position portion: portion whole: whole])
4340         {
4341           if (view->scrollbarsNeedingUpdate == 0)
4342             {
4343               if (!windows_or_buffers_changed)
4344                   return;
4345             }
4346           else
4347             view->scrollbarsNeedingUpdate--;
4348           update_p = NO;
4349         }
4350     }
4352   NSTRACE ("ns_set_vertical_scroll_bar");
4354   /* Get dimensions.  */
4355   window_box (window, ANY_AREA, 0, &window_y, 0, &window_height);
4356   top = window_y;
4357   height = window_height;
4358   width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
4359   left = WINDOW_SCROLL_BAR_AREA_X (window);
4361   r = NSMakeRect (left, top, width, height);
4362   /* the parent view is flipped, so we need to flip y value */
4363   v = [view frame];
4364   r.origin.y = (v.size.height - r.size.height - r.origin.y);
4366   XSETWINDOW (win, window);
4367   block_input ();
4369   /* we want at least 5 lines to display a scrollbar */
4370   if (WINDOW_TOTAL_LINES (window) < 5)
4371     {
4372       if (!NILP (window->vertical_scroll_bar))
4373         {
4374           bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4375           [bar removeFromSuperview];
4376           wset_vertical_scroll_bar (window, Qnil);
4377           [bar release];
4378         }
4379       ns_clear_frame_area (f, left, top, width, height);
4380       unblock_input ();
4381       return;
4382     }
4384   if (NILP (window->vertical_scroll_bar))
4385     {
4386       if (width > 0 && height > 0)
4387         ns_clear_frame_area (f, left, top, width, height);
4389       bar = [[EmacsScroller alloc] initFrame: r window: win];
4390       wset_vertical_scroll_bar (window, make_save_ptr (bar));
4391       update_p = YES;
4392     }
4393   else
4394     {
4395       NSRect oldRect;
4396       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4397       oldRect = [bar frame];
4398       r.size.width = oldRect.size.width;
4399       if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4400         {
4401           if (oldRect.origin.x != r.origin.x)
4402               ns_clear_frame_area (f, left, top, width, height);
4403           [bar setFrame: r];
4404         }
4405     }
4407   if (update_p)
4408     [bar setPosition: position portion: portion whole: whole];
4409   unblock_input ();
4413 static void
4414 ns_set_horizontal_scroll_bar (struct window *window,
4415                               int portion, int whole, int position)
4416 /* --------------------------------------------------------------------------
4417       External (hook): Update or add scrollbar
4418    -------------------------------------------------------------------------- */
4420   Lisp_Object win;
4421   NSRect r, v;
4422   struct frame *f = XFRAME (WINDOW_FRAME (window));
4423   EmacsView *view = FRAME_NS_VIEW (f);
4424   EmacsScroller *bar;
4425   int top, height, left, width;
4426   int window_x, window_width;
4427   BOOL update_p = YES;
4429   /* optimization; display engine sends WAY too many of these.. */
4430   if (!NILP (window->horizontal_scroll_bar))
4431     {
4432       bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4433       if ([bar checkSamePosition: position portion: portion whole: whole])
4434         {
4435           if (view->scrollbarsNeedingUpdate == 0)
4436             {
4437               if (!windows_or_buffers_changed)
4438                   return;
4439             }
4440           else
4441             view->scrollbarsNeedingUpdate--;
4442           update_p = NO;
4443         }
4444     }
4446   NSTRACE ("ns_set_horizontal_scroll_bar");
4448   /* Get dimensions.  */
4449   window_box (window, ANY_AREA, 0, &window_x, &window_width, 0);
4450   left = window_x;
4451   width = window_width;
4452   height = WINDOW_CONFIG_SCROLL_BAR_LINES (window) * FRAME_LINE_HEIGHT (f);
4453   top = WINDOW_SCROLL_BAR_AREA_Y (window);
4455   r = NSMakeRect (left, top, width, height);
4456   /* the parent view is flipped, so we need to flip y value */
4457   v = [view frame];
4458   /* ??????? PXW/scrollbars !!!!!!!!!!!!!!!!!!!! */
4459   r.origin.y = (v.size.height - r.size.height - r.origin.y);
4461   XSETWINDOW (win, window);
4462   block_input ();
4464   if (WINDOW_TOTAL_COLS (window) < 5)
4465     {
4466       if (!NILP (window->horizontal_scroll_bar))
4467         {
4468           bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4469           [bar removeFromSuperview];
4470           wset_horizontal_scroll_bar (window, Qnil);
4471         }
4472       ns_clear_frame_area (f, left, top, width, height);
4473       unblock_input ();
4474       return;
4475     }
4477   if (NILP (window->horizontal_scroll_bar))
4478     {
4479       if (width > 0 && height > 0)
4480         ns_clear_frame_area (f, left, top, width, height);
4482       bar = [[EmacsScroller alloc] initFrame: r window: win];
4483       wset_horizontal_scroll_bar (window, make_save_ptr (bar));
4484       update_p = YES;
4485     }
4486   else
4487     {
4488       NSRect oldRect;
4489       bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4490       oldRect = [bar frame];
4491       r.size.width = oldRect.size.width;
4492       if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4493         {
4494           if (oldRect.origin.x != r.origin.x)
4495               ns_clear_frame_area (f, left, top, width, height);
4496           [bar setFrame: r];
4497           update_p = YES;
4498         }
4499     }
4501   if (update_p)
4502     [bar setPosition: position portion: portion whole: whole];
4503   unblock_input ();
4507 static void
4508 ns_condemn_scroll_bars (struct frame *f)
4509 /* --------------------------------------------------------------------------
4510      External (hook): arrange for all frame's scrollbars to be removed
4511      at next call to judge_scroll_bars, except for those redeemed.
4512    -------------------------------------------------------------------------- */
4514   int i;
4515   id view;
4516   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
4518   NSTRACE ("ns_condemn_scroll_bars");
4520   for (i =[subviews count]-1; i >= 0; i--)
4521     {
4522       view = [subviews objectAtIndex: i];
4523       if ([view isKindOfClass: [EmacsScroller class]])
4524         [view condemn];
4525     }
4529 static void
4530 ns_redeem_scroll_bar (struct window *window)
4531 /* --------------------------------------------------------------------------
4532      External (hook): arrange to spare this window's scrollbar
4533      at next call to judge_scroll_bars.
4534    -------------------------------------------------------------------------- */
4536   id bar;
4537   NSTRACE ("ns_redeem_scroll_bar");
4538   if (!NILP (window->vertical_scroll_bar))
4539     {
4540       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4541       [bar reprieve];
4542     }
4544   if (!NILP (window->horizontal_scroll_bar))
4545     {
4546       bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4547       [bar reprieve];
4548     }
4552 static void
4553 ns_judge_scroll_bars (struct frame *f)
4554 /* --------------------------------------------------------------------------
4555      External (hook): destroy all scrollbars on frame that weren't
4556      redeemed after call to condemn_scroll_bars.
4557    -------------------------------------------------------------------------- */
4559   int i;
4560   id view;
4561   EmacsView *eview = FRAME_NS_VIEW (f);
4562   NSArray *subviews = [[eview superview] subviews];
4563   BOOL removed = NO;
4565   NSTRACE ("ns_judge_scroll_bars");
4566   for (i = [subviews count]-1; i >= 0; --i)
4567     {
4568       view = [subviews objectAtIndex: i];
4569       if (![view isKindOfClass: [EmacsScroller class]]) continue;
4570       if ([view judge])
4571         removed = YES;
4572     }
4574   if (removed)
4575     [eview updateFrameSize: NO];
4578 /* ==========================================================================
4580     Initialization
4582    ========================================================================== */
4585 x_display_pixel_height (struct ns_display_info *dpyinfo)
4587   NSArray *screens = [NSScreen screens];
4588   NSEnumerator *enumerator = [screens objectEnumerator];
4589   NSScreen *screen;
4590   NSRect frame;
4592   frame = NSZeroRect;
4593   while ((screen = [enumerator nextObject]) != nil)
4594     frame = NSUnionRect (frame, [screen frame]);
4596   return NSHeight (frame);
4600 x_display_pixel_width (struct ns_display_info *dpyinfo)
4602   NSArray *screens = [NSScreen screens];
4603   NSEnumerator *enumerator = [screens objectEnumerator];
4604   NSScreen *screen;
4605   NSRect frame;
4607   frame = NSZeroRect;
4608   while ((screen = [enumerator nextObject]) != nil)
4609     frame = NSUnionRect (frame, [screen frame]);
4611   return NSWidth (frame);
4615 static Lisp_Object ns_string_to_lispmod (const char *s)
4616 /* --------------------------------------------------------------------------
4617      Convert modifier name to lisp symbol
4618    -------------------------------------------------------------------------- */
4620   if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
4621     return Qmeta;
4622   else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
4623     return Qsuper;
4624   else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
4625     return Qcontrol;
4626   else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
4627     return Qalt;
4628   else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
4629     return Qhyper;
4630   else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
4631     return Qnone;
4632   else
4633     return Qnil;
4637 static void
4638 ns_default (const char *parameter, Lisp_Object *result,
4639            Lisp_Object yesval, Lisp_Object noval,
4640            BOOL is_float, BOOL is_modstring)
4641 /* --------------------------------------------------------------------------
4642       Check a parameter value in user's preferences
4643    -------------------------------------------------------------------------- */
4645   const char *value = ns_get_defaults_value (parameter);
4647   if (value)
4648     {
4649       double f;
4650       char *pos;
4651       if (c_strcasecmp (value, "YES") == 0)
4652         *result = yesval;
4653       else if (c_strcasecmp (value, "NO") == 0)
4654         *result = noval;
4655       else if (is_float && (f = strtod (value, &pos), pos != value))
4656         *result = make_float (f);
4657       else if (is_modstring && value)
4658         *result = ns_string_to_lispmod (value);
4659       else fprintf (stderr,
4660                    "Bad value for default \"%s\": \"%s\"\n", parameter, value);
4661     }
4665 static void
4666 ns_initialize_display_info (struct ns_display_info *dpyinfo)
4667 /* --------------------------------------------------------------------------
4668       Initialize global info and storage for display.
4669    -------------------------------------------------------------------------- */
4671     NSScreen *screen = [NSScreen mainScreen];
4672     NSWindowDepth depth = [screen depth];
4674     dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
4675     dpyinfo->resy = 72.27;
4676     dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
4677                                                   NSColorSpaceFromDepth (depth)]
4678                 && ![NSCalibratedWhiteColorSpace isEqualToString:
4679                                                  NSColorSpaceFromDepth (depth)];
4680     dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
4681     dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
4682     dpyinfo->color_table->colors = NULL;
4683     dpyinfo->root_window = 42; /* a placeholder.. */
4684     dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
4685     dpyinfo->n_fonts = 0;
4686     dpyinfo->smallest_font_height = 1;
4687     dpyinfo->smallest_char_width = 1;
4689     reset_mouse_highlight (&dpyinfo->mouse_highlight);
4693 /* This and next define (many of the) public functions in this file. */
4694 /* x_... are generic versions in xdisp.c that we, and other terms, get away
4695          with using despite presence in the "system dependent" redisplay
4696          interface.  In addition, many of the ns_ methods have code that is
4697          shared with all terms, indicating need for further refactoring. */
4698 extern frame_parm_handler ns_frame_parm_handlers[];
4699 static struct redisplay_interface ns_redisplay_interface =
4701   ns_frame_parm_handlers,
4702   x_produce_glyphs,
4703   x_write_glyphs,
4704   x_insert_glyphs,
4705   x_clear_end_of_line,
4706   ns_scroll_run,
4707   ns_after_update_window_line,
4708   ns_update_window_begin,
4709   ns_update_window_end,
4710   0, /* flush_display */
4711   x_clear_window_mouse_face,
4712   x_get_glyph_overhangs,
4713   x_fix_overlapping_area,
4714   ns_draw_fringe_bitmap,
4715   0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
4716   0, /* destroy_fringe_bitmap */
4717   ns_compute_glyph_string_overhangs,
4718   ns_draw_glyph_string,
4719   ns_define_frame_cursor,
4720   ns_clear_frame_area,
4721   ns_draw_window_cursor,
4722   ns_draw_vertical_window_border,
4723   ns_draw_window_divider,
4724   ns_shift_glyphs_for_insert,
4725   ns_show_hourglass,
4726   ns_hide_hourglass
4730 static void
4731 ns_delete_display (struct ns_display_info *dpyinfo)
4733   /* TODO... */
4737 /* This function is called when the last frame on a display is deleted. */
4738 static void
4739 ns_delete_terminal (struct terminal *terminal)
4741   struct ns_display_info *dpyinfo = terminal->display_info.ns;
4743   NSTRACE ("ns_delete_terminal");
4745   /* Protect against recursive calls.  delete_frame in
4746      delete_terminal calls us back when it deletes our last frame.  */
4747   if (!terminal->name)
4748     return;
4750   block_input ();
4752   x_destroy_all_bitmaps (dpyinfo);
4753   ns_delete_display (dpyinfo);
4754   unblock_input ();
4758 static struct terminal *
4759 ns_create_terminal (struct ns_display_info *dpyinfo)
4760 /* --------------------------------------------------------------------------
4761       Set up use of NS before we make the first connection.
4762    -------------------------------------------------------------------------- */
4764   struct terminal *terminal;
4766   NSTRACE ("ns_create_terminal");
4768   terminal = create_terminal (output_ns, &ns_redisplay_interface);
4770   terminal->display_info.ns = dpyinfo;
4771   dpyinfo->terminal = terminal;
4773   terminal->clear_frame_hook = ns_clear_frame;
4774   terminal->ring_bell_hook = ns_ring_bell;
4775   terminal->update_begin_hook = ns_update_begin;
4776   terminal->update_end_hook = ns_update_end;
4777   terminal->read_socket_hook = ns_read_socket;
4778   terminal->frame_up_to_date_hook = ns_frame_up_to_date;
4779   terminal->mouse_position_hook = ns_mouse_position;
4780   terminal->frame_rehighlight_hook = ns_frame_rehighlight;
4781   terminal->frame_raise_lower_hook = ns_frame_raise_lower;
4782   terminal->fullscreen_hook = ns_fullscreen_hook;
4783   terminal->menu_show_hook = ns_menu_show;
4784   terminal->popup_dialog_hook = ns_popup_dialog;
4785   terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
4786   terminal->set_horizontal_scroll_bar_hook = ns_set_horizontal_scroll_bar;
4787   terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
4788   terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
4789   terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
4790   terminal->delete_frame_hook = x_destroy_window;
4791   terminal->delete_terminal_hook = ns_delete_terminal;
4792   /* Other hooks are NULL by default.  */
4794   return terminal;
4798 struct ns_display_info *
4799 ns_term_init (Lisp_Object display_name)
4800 /* --------------------------------------------------------------------------
4801      Start the Application and get things rolling.
4802    -------------------------------------------------------------------------- */
4804   struct terminal *terminal;
4805   struct ns_display_info *dpyinfo;
4806   static int ns_initialized = 0;
4807   Lisp_Object tmp;
4809   if (ns_initialized) return x_display_list;
4810   ns_initialized = 1;
4812   block_input ();
4814   NSTRACE ("ns_term_init");
4816   [outerpool release];
4817   outerpool = [[NSAutoreleasePool alloc] init];
4819   /* count object allocs (About, click icon); on macOS use ObjectAlloc tool */
4820   /*GSDebugAllocationActive (YES); */
4821   block_input ();
4823   baud_rate = 38400;
4824   Fset_input_interrupt_mode (Qnil);
4826   if (selfds[0] == -1)
4827     {
4828       if (emacs_pipe (selfds) != 0)
4829         {
4830           fprintf (stderr, "Failed to create pipe: %s\n",
4831                    emacs_strerror (errno));
4832           emacs_abort ();
4833         }
4835       fcntl (selfds[0], F_SETFL, O_NONBLOCK|fcntl (selfds[0], F_GETFL));
4836       FD_ZERO (&select_readfds);
4837       FD_ZERO (&select_writefds);
4838       pthread_mutex_init (&select_mutex, NULL);
4839     }
4841   ns_pending_files = [[NSMutableArray alloc] init];
4842   ns_pending_service_names = [[NSMutableArray alloc] init];
4843   ns_pending_service_args = [[NSMutableArray alloc] init];
4845 /* Start app and create the main menu, window, view.
4846      Needs to be here because ns_initialize_display_info () uses AppKit classes.
4847      The view will then ask the NSApp to stop and return to Emacs. */
4848   [EmacsApp sharedApplication];
4849   if (NSApp == nil)
4850     return NULL;
4851   [NSApp setDelegate: NSApp];
4853   /* Start the select thread.  */
4854   [NSThread detachNewThreadSelector:@selector (fd_handler:)
4855                            toTarget:NSApp
4856                          withObject:nil];
4858   /* debugging: log all notifications */
4859   /*   [[NSNotificationCenter defaultCenter] addObserver: NSApp
4860                                          selector: @selector (logNotification:)
4861                                              name: nil object: nil]; */
4863   dpyinfo = xzalloc (sizeof *dpyinfo);
4865   ns_initialize_display_info (dpyinfo);
4866   terminal = ns_create_terminal (dpyinfo);
4868   terminal->kboard = allocate_kboard (Qns);
4869   /* Don't let the initial kboard remain current longer than necessary.
4870      That would cause problems if a file loaded on startup tries to
4871      prompt in the mini-buffer.  */
4872   if (current_kboard == initial_kboard)
4873     current_kboard = terminal->kboard;
4874   terminal->kboard->reference_count++;
4876   dpyinfo->next = x_display_list;
4877   x_display_list = dpyinfo;
4879   dpyinfo->name_list_element = Fcons (display_name, Qnil);
4881   terminal->name = xlispstrdup (display_name);
4883   unblock_input ();
4885   if (!inhibit_x_resources)
4886     {
4887       ns_default ("GSFontAntiAlias", &ns_antialias_text,
4888                  Qt, Qnil, NO, NO);
4889       tmp = Qnil;
4890       /* this is a standard variable */
4891       ns_default ("AppleAntiAliasingThreshold", &tmp,
4892                  make_float (10.0), make_float (6.0), YES, NO);
4893       ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4894     }
4896   NSTRACE_MSG ("Colors");
4898   {
4899     NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4901     if ( cl == nil )
4902       {
4903         Lisp_Object color_file, color_map, color;
4904         unsigned long c;
4905         char *name;
4907         color_file = Fexpand_file_name (build_string ("rgb.txt"),
4908                          Fsymbol_value (intern ("data-directory")));
4910         color_map = Fx_load_color_file (color_file);
4911         if (NILP (color_map))
4912           fatal ("Could not read %s.\n", SDATA (color_file));
4914         cl = [[NSColorList alloc] initWithName: @"Emacs"];
4915         for ( ; CONSP (color_map); color_map = XCDR (color_map))
4916           {
4917             color = XCAR (color_map);
4918             name = SSDATA (XCAR (color));
4919             c = XINT (XCDR (color));
4920             [cl setColor:
4921                   [NSColor colorForEmacsRed: RED_FROM_ULONG (c) / 255.0
4922                                       green: GREEN_FROM_ULONG (c) / 255.0
4923                                        blue: BLUE_FROM_ULONG (c) / 255.0
4924                                       alpha: 1.0]
4925                   forKey: [NSString stringWithUTF8String: name]];
4926           }
4927         [cl writeToFile: nil];
4928       }
4929   }
4931   NSTRACE_MSG ("Versions");
4933   {
4934 #ifdef NS_IMPL_GNUSTEP
4935     Vwindow_system_version = build_string (gnustep_base_version);
4936 #else
4937     /*PSnextrelease (128, c); */
4938     char c[DBL_BUFSIZE_BOUND];
4939     int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4940     Vwindow_system_version = make_unibyte_string (c, len);
4941 #endif
4942   }
4944   delete_keyboard_wait_descriptor (0);
4946   ns_app_name = [[NSProcessInfo processInfo] processName];
4948   /* Set up macOS app menu */
4950   NSTRACE_MSG ("Menu init");
4952 #ifdef NS_IMPL_COCOA
4953   {
4954     NSMenu *appMenu;
4955     NSMenuItem *item;
4956     /* set up the application menu */
4957     svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4958     [svcsMenu setAutoenablesItems: NO];
4959     appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4960     [appMenu setAutoenablesItems: NO];
4961     mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4962     dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4964     [appMenu insertItemWithTitle: @"About Emacs"
4965                           action: @selector (orderFrontStandardAboutPanel:)
4966                    keyEquivalent: @""
4967                          atIndex: 0];
4968     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4969     [appMenu insertItemWithTitle: @"Preferences..."
4970                           action: @selector (showPreferencesWindow:)
4971                    keyEquivalent: @","
4972                          atIndex: 2];
4973     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4974     item = [appMenu insertItemWithTitle: @"Services"
4975                                  action: @selector (menuDown:)
4976                           keyEquivalent: @""
4977                                 atIndex: 4];
4978     [appMenu setSubmenu: svcsMenu forItem: item];
4979     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4980     [appMenu insertItemWithTitle: @"Hide Emacs"
4981                           action: @selector (hide:)
4982                    keyEquivalent: @"h"
4983                          atIndex: 6];
4984     item =  [appMenu insertItemWithTitle: @"Hide Others"
4985                           action: @selector (hideOtherApplications:)
4986                    keyEquivalent: @"h"
4987                          atIndex: 7];
4988     [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4989     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4990     [appMenu insertItemWithTitle: @"Quit Emacs"
4991                           action: @selector (terminate:)
4992                    keyEquivalent: @"q"
4993                          atIndex: 9];
4995     item = [mainMenu insertItemWithTitle: ns_app_name
4996                                   action: @selector (menuDown:)
4997                            keyEquivalent: @""
4998                                  atIndex: 0];
4999     [mainMenu setSubmenu: appMenu forItem: item];
5000     [dockMenu insertItemWithTitle: @"New Frame"
5001                            action: @selector (newFrame:)
5002                     keyEquivalent: @""
5003                           atIndex: 0];
5005     [NSApp setMainMenu: mainMenu];
5006     [NSApp setAppleMenu: appMenu];
5007     [NSApp setServicesMenu: svcsMenu];
5008     /* Needed at least on Cocoa, to get dock menu to show windows */
5009     [NSApp setWindowsMenu: [[NSMenu alloc] init]];
5011     [[NSNotificationCenter defaultCenter]
5012       addObserver: mainMenu
5013          selector: @selector (trackingNotification:)
5014              name: NSMenuDidBeginTrackingNotification object: mainMenu];
5015     [[NSNotificationCenter defaultCenter]
5016       addObserver: mainMenu
5017          selector: @selector (trackingNotification:)
5018              name: NSMenuDidEndTrackingNotification object: mainMenu];
5019   }
5020 #endif /* macOS menu setup */
5022   /* Register our external input/output types, used for determining
5023      applicable services and also drag/drop eligibility. */
5025   NSTRACE_MSG ("Input/output types");
5027   ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
5028   ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
5029                       retain];
5030   ns_drag_types = [[NSArray arrayWithObjects:
5031                             NSStringPboardType,
5032                             NSTabularTextPboardType,
5033                             NSFilenamesPboardType,
5034                             NSURLPboardType, nil] retain];
5036   /* If fullscreen is in init/default-frame-alist, focus isn't set
5037      right for fullscreen windows, so set this.  */
5038   [NSApp activateIgnoringOtherApps:YES];
5040   NSTRACE_MSG ("Call NSApp run");
5042   [NSApp run];
5043   ns_do_open_file = YES;
5045 #ifdef NS_IMPL_GNUSTEP
5046   /* GNUstep steals SIGCHLD for use in NSTask, but we don't use NSTask.
5047      We must re-catch it so subprocess works.  */
5048   catch_child_signal ();
5049 #endif
5051   NSTRACE_MSG ("ns_term_init done");
5053   unblock_input ();
5055   return dpyinfo;
5059 void
5060 ns_term_shutdown (int sig)
5062   [[NSUserDefaults standardUserDefaults] synchronize];
5064   /* code not reached in emacs.c after this is called by shut_down_emacs: */
5065   if (STRINGP (Vauto_save_list_file_name))
5066     unlink (SSDATA (Vauto_save_list_file_name));
5068   if (sig == 0 || sig == SIGTERM)
5069     {
5070       [NSApp terminate: NSApp];
5071     }
5072   else // force a stack trace to happen
5073     {
5074       emacs_abort ();
5075     }
5079 /* ==========================================================================
5081     EmacsApp implementation
5083    ========================================================================== */
5086 @implementation EmacsApp
5088 - (id)init
5090   NSTRACE ("[EmacsApp init]");
5092   if ((self = [super init]))
5093     {
5094 #ifdef NS_IMPL_COCOA
5095       self->isFirst = YES;
5096 #endif
5097 #ifdef NS_IMPL_GNUSTEP
5098       self->applicationDidFinishLaunchingCalled = NO;
5099 #endif
5100     }
5102   return self;
5105 #ifdef NS_IMPL_COCOA
5106 - (void)run
5108   NSTRACE ("[EmacsApp run]");
5110 #ifndef NSAppKitVersionNumber10_9
5111 #define NSAppKitVersionNumber10_9 1265
5112 #endif
5114     if ((int)NSAppKitVersionNumber != NSAppKitVersionNumber10_9)
5115       {
5116         [super run];
5117         return;
5118       }
5120   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
5122   if (isFirst) [self finishLaunching];
5123   isFirst = NO;
5125   shouldKeepRunning = YES;
5126   do
5127     {
5128       [pool release];
5129       pool = [[NSAutoreleasePool alloc] init];
5131       NSEvent *event =
5132         [self nextEventMatchingMask:NSAnyEventMask
5133                           untilDate:[NSDate distantFuture]
5134                              inMode:NSDefaultRunLoopMode
5135                             dequeue:YES];
5137       [self sendEvent:event];
5138       [self updateWindows];
5139     } while (shouldKeepRunning);
5141   [pool release];
5144 - (void)stop: (id)sender
5146   NSTRACE ("[EmacsApp stop:]");
5148     shouldKeepRunning = NO;
5149     // Stop possible dialog also.  Noop if no dialog present.
5150     // The file dialog still leaks 7k - 10k on 10.9 though.
5151     [super stop:sender];
5153 #endif /* NS_IMPL_COCOA */
5155 - (void)logNotification: (NSNotification *)notification
5157   NSTRACE ("[EmacsApp logNotification:]");
5159   const char *name = [[notification name] UTF8String];
5160   if (!strstr (name, "Update") && !strstr (name, "NSMenu")
5161       && !strstr (name, "WindowNumber"))
5162     NSLog (@"notification: '%@'", [notification name]);
5166 - (void)sendEvent: (NSEvent *)theEvent
5167 /* --------------------------------------------------------------------------
5168      Called when NSApp is running for each event received.  Used to stop
5169      the loop when we choose, since there's no way to just run one iteration.
5170    -------------------------------------------------------------------------- */
5172   int type = [theEvent type];
5173   NSWindow *window = [theEvent window];
5175   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "[EmacsApp sendEvent:]");
5176   NSTRACE_MSG ("Type: %d", type);
5178 #ifdef NS_IMPL_GNUSTEP
5179   // Keyboard events aren't propagated to file dialogs for some reason.
5180   if ([NSApp modalWindow] != nil &&
5181       (type == NSKeyDown || type == NSKeyUp || type == NSFlagsChanged))
5182     {
5183       [[NSApp modalWindow] sendEvent: theEvent];
5184       return;
5185     }
5186 #endif
5188   if (represented_filename != nil && represented_frame)
5189     {
5190       NSString *fstr = represented_filename;
5191       NSView *view = FRAME_NS_VIEW (represented_frame);
5192 #ifdef NS_IMPL_COCOA
5193       /* work around a bug observed on 10.3 and later where
5194          setTitleWithRepresentedFilename does not clear out previous state
5195          if given filename does not exist */
5196       if (! [[NSFileManager defaultManager] fileExistsAtPath: fstr])
5197         [[view window] setRepresentedFilename: @""];
5198 #endif
5199       [[view window] setRepresentedFilename: fstr];
5200       [represented_filename release];
5201       represented_filename = nil;
5202       represented_frame = NULL;
5203     }
5205   if (type == NSApplicationDefined)
5206     {
5207       switch ([theEvent data2])
5208         {
5209 #ifdef NS_IMPL_COCOA
5210         case NSAPP_DATA2_RUNASSCRIPT:
5211           ns_run_ascript ();
5212           [self stop: self];
5213           return;
5214 #endif
5215         case NSAPP_DATA2_RUNFILEDIALOG:
5216           ns_run_file_dialog ();
5217           [self stop: self];
5218           return;
5219         }
5220     }
5222   if (type == NSCursorUpdate && window == nil)
5223     {
5224       fprintf (stderr, "Dropping external cursor update event.\n");
5225       return;
5226     }
5228   if (type == NSApplicationDefined)
5229     {
5230       /* Events posted by ns_send_appdefined interrupt the run loop here.
5231          But, if a modal window is up, an appdefined can still come through,
5232          (e.g., from a makeKeyWindow event) but stopping self also stops the
5233          modal loop. Just defer it until later. */
5234       if ([NSApp modalWindow] == nil)
5235         {
5236           last_appdefined_event_data = [theEvent data1];
5237           [self stop: self];
5238         }
5239       else
5240         {
5241           send_appdefined = YES;
5242         }
5243     }
5246 #ifdef NS_IMPL_COCOA
5247   /* If no dialog and none of our frames have focus and it is a move, skip it.
5248      It is a mouse move in an auxiliary menu, i.e. on the top right on macOS,
5249      such as Wifi, sound, date or similar.
5250      This prevents "spooky" highlighting in the frame under the menu.  */
5251   if (type == NSMouseMoved && [NSApp modalWindow] == nil)
5252     {
5253       struct ns_display_info *di;
5254       BOOL has_focus = NO;
5255       for (di = x_display_list; ! has_focus && di; di = di->next)
5256         has_focus = di->x_focus_frame != 0;
5257       if (! has_focus)
5258         return;
5259     }
5260 #endif
5262   NSTRACE_UNSILENCE();
5264   [super sendEvent: theEvent];
5268 - (void)showPreferencesWindow: (id)sender
5270   struct frame *emacsframe = SELECTED_FRAME ();
5271   NSEvent *theEvent = [NSApp currentEvent];
5273   if (!emacs_event)
5274     return;
5275   emacs_event->kind = NS_NONKEY_EVENT;
5276   emacs_event->code = KEY_NS_SHOW_PREFS;
5277   emacs_event->modifiers = 0;
5278   EV_TRAILER (theEvent);
5282 - (void)newFrame: (id)sender
5284   NSTRACE ("[EmacsApp newFrame:]");
5286   struct frame *emacsframe = SELECTED_FRAME ();
5287   NSEvent *theEvent = [NSApp currentEvent];
5289   if (!emacs_event)
5290     return;
5291   emacs_event->kind = NS_NONKEY_EVENT;
5292   emacs_event->code = KEY_NS_NEW_FRAME;
5293   emacs_event->modifiers = 0;
5294   EV_TRAILER (theEvent);
5298 /* Open a file (used by below, after going into queue read by ns_read_socket) */
5299 - (BOOL) openFile: (NSString *)fileName
5301   NSTRACE ("[EmacsApp openFile:]");
5303   struct frame *emacsframe = SELECTED_FRAME ();
5304   NSEvent *theEvent = [NSApp currentEvent];
5306   if (!emacs_event)
5307     return NO;
5309   emacs_event->kind = NS_NONKEY_EVENT;
5310   emacs_event->code = KEY_NS_OPEN_FILE_LINE;
5311   ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
5312   ns_input_line = Qnil; /* can be start or cons start,end */
5313   emacs_event->modifiers =0;
5314   EV_TRAILER (theEvent);
5316   return YES;
5320 /* **************************************************************************
5322       EmacsApp delegate implementation
5324    ************************************************************************** */
5326 - (void)applicationDidFinishLaunching: (NSNotification *)notification
5327 /* --------------------------------------------------------------------------
5328      When application is loaded, terminate event loop in ns_term_init
5329    -------------------------------------------------------------------------- */
5331   NSTRACE ("[EmacsApp applicationDidFinishLaunching:]");
5333 #ifdef NS_IMPL_GNUSTEP
5334   ((EmacsApp *)self)->applicationDidFinishLaunchingCalled = YES;
5335 #endif
5336   [NSApp setServicesProvider: NSApp];
5338   [self antialiasThresholdDidChange:nil];
5339 #ifdef NS_IMPL_COCOA
5340   [[NSNotificationCenter defaultCenter]
5341     addObserver:self
5342        selector:@selector(antialiasThresholdDidChange:)
5343            name:NSAntialiasThresholdChangedNotification
5344          object:nil];
5345 #endif
5347   ns_send_appdefined (-2);
5350 - (void)antialiasThresholdDidChange:(NSNotification *)notification
5352 #ifdef NS_IMPL_COCOA
5353   macfont_update_antialias_threshold ();
5354 #endif
5358 /* Termination sequences:
5359     C-x C-c:
5360     Cmd-Q:
5361     MenuBar | File | Exit:
5362     Select Quit from App menubar:
5363         -terminate
5364         KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5365         ns_term_shutdown()
5367     Select Quit from Dock menu:
5368     Logout attempt:
5369         -appShouldTerminate
5370           Cancel -> Nothing else
5371           Accept ->
5373           -terminate
5374           KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5375           ns_term_shutdown()
5379 - (void) terminate: (id)sender
5381   NSTRACE ("[EmacsApp terminate:]");
5383   struct frame *emacsframe = SELECTED_FRAME ();
5385   if (!emacs_event)
5386     return;
5388   emacs_event->kind = NS_NONKEY_EVENT;
5389   emacs_event->code = KEY_NS_POWER_OFF;
5390   emacs_event->arg = Qt; /* mark as non-key event */
5391   EV_TRAILER ((id)nil);
5394 static bool
5395 runAlertPanel(NSString *title,
5396               NSString *msgFormat,
5397               NSString *defaultButton,
5398               NSString *alternateButton)
5400 #if !defined (NS_IMPL_COCOA) || \
5401   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
5402   return NSRunAlertPanel(title, msgFormat, defaultButton, alternateButton, nil)
5403     == NSAlertDefaultReturn;
5404 #else
5405   NSAlert *alert = [[NSAlert alloc] init];
5406   [alert setAlertStyle: NSCriticalAlertStyle];
5407   [alert setMessageText: msgFormat];
5408   [alert addButtonWithTitle: defaultButton];
5409   [alert addButtonWithTitle: alternateButton];
5410   NSInteger ret = [alert runModal];
5411   [alert release];
5412   return ret == NSAlertFirstButtonReturn;
5413 #endif
5417 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
5419   NSTRACE ("[EmacsApp applicationShouldTerminate:]");
5421   bool ret;
5423   if (NILP (ns_confirm_quit)) //   || ns_shutdown_properly  --> TO DO
5424     return NSTerminateNow;
5426     ret = runAlertPanel(ns_app_name,
5427                         @"Exit requested.  Would you like to Save Buffers and Exit, or Cancel the request?",
5428                         @"Save Buffers and Exit", @"Cancel");
5430     if (ret)
5431         return NSTerminateNow;
5432     else
5433         return NSTerminateCancel;
5434     return NSTerminateNow;  /* just in case */
5437 static int
5438 not_in_argv (NSString *arg)
5440   int k;
5441   const char *a = [arg UTF8String];
5442   for (k = 1; k < initial_argc; ++k)
5443     if (strcmp (a, initial_argv[k]) == 0) return 0;
5444   return 1;
5447 /*   Notification from the Workspace to open a file */
5448 - (BOOL)application: sender openFile: (NSString *)file
5450   if (ns_do_open_file || not_in_argv (file))
5451     [ns_pending_files addObject: file];
5452   return YES;
5456 /*   Open a file as a temporary file */
5457 - (BOOL)application: sender openTempFile: (NSString *)file
5459   if (ns_do_open_file || not_in_argv (file))
5460     [ns_pending_files addObject: file];
5461   return YES;
5465 /*   Notification from the Workspace to open a file noninteractively (?) */
5466 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
5468   if (ns_do_open_file || not_in_argv (file))
5469     [ns_pending_files addObject: file];
5470   return YES;
5473 /*   Notification from the Workspace to open multiple files */
5474 - (void)application: sender openFiles: (NSArray *)fileList
5476   NSEnumerator *files = [fileList objectEnumerator];
5477   NSString *file;
5478   /* Don't open files from the command line unconditionally,
5479      Cocoa parses the command line wrong, --option value tries to open value
5480      if --option is the last option.  */
5481   while ((file = [files nextObject]) != nil)
5482     if (ns_do_open_file || not_in_argv (file))
5483       [ns_pending_files addObject: file];
5485   [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
5490 /* Handle dock menu requests.  */
5491 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
5493   return dockMenu;
5497 /* TODO: these may help w/IO switching btwn terminal and NSApp */
5498 - (void)applicationWillBecomeActive: (NSNotification *)notification
5500   NSTRACE ("[EmacsApp applicationWillBecomeActive:]");
5501   //ns_app_active=YES;
5504 - (void)applicationDidBecomeActive: (NSNotification *)notification
5506   NSTRACE ("[EmacsApp applicationDidBecomeActive:]");
5508 #ifdef NS_IMPL_GNUSTEP
5509   if (! applicationDidFinishLaunchingCalled)
5510     [self applicationDidFinishLaunching:notification];
5511 #endif
5512   //ns_app_active=YES;
5514   ns_update_auto_hide_menu_bar ();
5515   // No constraining takes place when the application is not active.
5516   ns_constrain_all_frames ();
5518 - (void)applicationDidResignActive: (NSNotification *)notification
5520   NSTRACE ("[EmacsApp applicationDidResignActive:]");
5522   //ns_app_active=NO;
5523   ns_send_appdefined (-1);
5528 /* ==========================================================================
5530     EmacsApp aux handlers for managing event loop
5532    ========================================================================== */
5535 - (void)timeout_handler: (NSTimer *)timedEntry
5536 /* --------------------------------------------------------------------------
5537      The timeout specified to ns_select has passed.
5538    -------------------------------------------------------------------------- */
5540   /*NSTRACE ("timeout_handler"); */
5541   ns_send_appdefined (-2);
5544 - (void)sendFromMainThread:(id)unused
5546   ns_send_appdefined (nextappdefined);
5549 - (void)fd_handler:(id)unused
5550 /* --------------------------------------------------------------------------
5551      Check data waiting on file descriptors and terminate if so
5552    -------------------------------------------------------------------------- */
5554   int result;
5555   int waiting = 1, nfds;
5556   char c;
5558   fd_set readfds, writefds, *wfds;
5559   struct timespec timeout, *tmo;
5560   NSAutoreleasePool *pool = nil;
5562   /* NSTRACE ("fd_handler"); */
5564   for (;;)
5565     {
5566       [pool release];
5567       pool = [[NSAutoreleasePool alloc] init];
5569       if (waiting)
5570         {
5571           fd_set fds;
5572           FD_ZERO (&fds);
5573           FD_SET (selfds[0], &fds);
5574           result = select (selfds[0]+1, &fds, NULL, NULL, NULL);
5575           if (result > 0 && read (selfds[0], &c, 1) == 1 && c == 'g')
5576             waiting = 0;
5577         }
5578       else
5579         {
5580           pthread_mutex_lock (&select_mutex);
5581           nfds = select_nfds;
5583           if (select_valid & SELECT_HAVE_READ)
5584             readfds = select_readfds;
5585           else
5586             FD_ZERO (&readfds);
5588           if (select_valid & SELECT_HAVE_WRITE)
5589             {
5590               writefds = select_writefds;
5591               wfds = &writefds;
5592             }
5593           else
5594             wfds = NULL;
5595           if (select_valid & SELECT_HAVE_TMO)
5596             {
5597               timeout = select_timeout;
5598               tmo = &timeout;
5599             }
5600           else
5601             tmo = NULL;
5603           pthread_mutex_unlock (&select_mutex);
5605           FD_SET (selfds[0], &readfds);
5606           if (selfds[0] >= nfds) nfds = selfds[0]+1;
5608           result = pselect (nfds, &readfds, wfds, NULL, tmo, NULL);
5610           if (result == 0)
5611             ns_send_appdefined (-2);
5612           else if (result > 0)
5613             {
5614               if (FD_ISSET (selfds[0], &readfds))
5615                 {
5616                   if (read (selfds[0], &c, 1) == 1 && c == 's')
5617                     waiting = 1;
5618                 }
5619               else
5620                 {
5621                   pthread_mutex_lock (&select_mutex);
5622                   if (select_valid & SELECT_HAVE_READ)
5623                     select_readfds = readfds;
5624                   if (select_valid & SELECT_HAVE_WRITE)
5625                     select_writefds = writefds;
5626                   if (select_valid & SELECT_HAVE_TMO)
5627                     select_timeout = timeout;
5628                   pthread_mutex_unlock (&select_mutex);
5630                   ns_send_appdefined (result);
5631                 }
5632             }
5633           waiting = 1;
5634         }
5635     }
5640 /* ==========================================================================
5642     Service provision
5644    ========================================================================== */
5646 /* called from system: queue for next pass through event loop */
5647 - (void)requestService: (NSPasteboard *)pboard
5648               userData: (NSString *)userData
5649                  error: (NSString **)error
5651   [ns_pending_service_names addObject: userData];
5652   [ns_pending_service_args addObject: [NSString stringWithUTF8String:
5653       SSDATA (ns_string_from_pasteboard (pboard))]];
5657 /* called from ns_read_socket to clear queue */
5658 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
5660   struct frame *emacsframe = SELECTED_FRAME ();
5661   NSEvent *theEvent = [NSApp currentEvent];
5663   NSTRACE ("[EmacsApp fulfillService:withArg:]");
5665   if (!emacs_event)
5666     return NO;
5668   emacs_event->kind = NS_NONKEY_EVENT;
5669   emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
5670   ns_input_spi_name = build_string ([name UTF8String]);
5671   ns_input_spi_arg = build_string ([arg UTF8String]);
5672   emacs_event->modifiers = EV_MODIFIERS (theEvent);
5673   EV_TRAILER (theEvent);
5675   return YES;
5679 @end  /* EmacsApp */
5683 /* ==========================================================================
5685     EmacsView implementation
5687    ========================================================================== */
5690 @implementation EmacsView
5692 /* needed to inform when window closed from LISP */
5693 - (void) setWindowClosing: (BOOL)closing
5695   NSTRACE ("[EmacsView setWindowClosing:%d]", closing);
5697   windowClosing = closing;
5701 - (void)dealloc
5703   NSTRACE ("[EmacsView dealloc]");
5704   [toolbar release];
5705   if (fs_state == FULLSCREEN_BOTH)
5706     [nonfs_window release];
5707   [super dealloc];
5711 /* called on font panel selection */
5712 - (void)changeFont: (id)sender
5714   NSEvent *e = [[self window] currentEvent];
5715   struct face *face = FRAME_DEFAULT_FACE (emacsframe);
5716   struct font *font = face->font;
5717   id newFont;
5718   CGFloat size;
5719   NSFont *nsfont;
5721   NSTRACE ("[EmacsView changeFont:]");
5723   if (!emacs_event)
5724     return;
5726 #ifdef NS_IMPL_GNUSTEP
5727   nsfont = ((struct nsfont_info *)font)->nsfont;
5728 #endif
5729 #ifdef NS_IMPL_COCOA
5730   nsfont = (NSFont *) macfont_get_nsctfont (font);
5731 #endif
5733   if ((newFont = [sender convertFont: nsfont]))
5734     {
5735       SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
5737       emacs_event->kind = NS_NONKEY_EVENT;
5738       emacs_event->modifiers = 0;
5739       emacs_event->code = KEY_NS_CHANGE_FONT;
5741       size = [newFont pointSize];
5742       ns_input_fontsize = make_number (lrint (size));
5743       ns_input_font = build_string ([[newFont familyName] UTF8String]);
5744       EV_TRAILER (e);
5745     }
5749 - (BOOL)acceptsFirstResponder
5751   NSTRACE ("[EmacsView acceptsFirstResponder]");
5752   return YES;
5756 - (void)resetCursorRects
5758   NSRect visible = [self visibleRect];
5759   NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
5760   NSTRACE ("[EmacsView resetCursorRects]");
5762   if (currentCursor == nil)
5763     currentCursor = [NSCursor arrowCursor];
5765   if (!NSIsEmptyRect (visible))
5766     [self addCursorRect: visible cursor: currentCursor];
5767   [currentCursor setOnMouseEntered: YES];
5772 /*****************************************************************************/
5773 /* Keyboard handling. */
5774 #define NS_KEYLOG 0
5776 - (void)keyDown: (NSEvent *)theEvent
5778   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5779   int code;
5780   unsigned fnKeysym = 0;
5781   static NSMutableArray *nsEvArray;
5782   int left_is_none;
5783   unsigned int flags = [theEvent modifierFlags];
5785   NSTRACE ("[EmacsView keyDown:]");
5787   /* Rhapsody and macOS give up and down events for the arrow keys */
5788   if (ns_fake_keydown == YES)
5789     ns_fake_keydown = NO;
5790   else if ([theEvent type] != NSKeyDown)
5791     return;
5793   if (!emacs_event)
5794     return;
5796  if (![[self window] isKeyWindow]
5797      && [[theEvent window] isKindOfClass: [EmacsWindow class]]
5798      /* we must avoid an infinite loop here. */
5799      && (EmacsView *)[[theEvent window] delegate] != self)
5800    {
5801      /* XXX: There is an occasional condition in which, when Emacs display
5802          updates a different frame from the current one, and temporarily
5803          selects it, then processes some interrupt-driven input
5804          (dispnew.c:3878), OS will send the event to the correct NSWindow, but
5805          for some reason that window has its first responder set to the NSView
5806          most recently updated (I guess), which is not the correct one. */
5807      [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
5808      return;
5809    }
5811   if (nsEvArray == nil)
5812     nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
5814   [NSCursor setHiddenUntilMouseMoves: YES];
5816   if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
5817     {
5818       clear_mouse_face (hlinfo);
5819       hlinfo->mouse_face_hidden = 1;
5820     }
5822   if (!processingCompose)
5823     {
5824       /* When using screen sharing, no left or right information is sent,
5825          so use Left key in those cases.  */
5826       int is_left_key, is_right_key;
5828       code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
5829         0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
5831       /* (Carbon way: [theEvent keyCode]) */
5833       /* is it a "function key"? */
5834       /* Note: Sometimes a plain key will have the NSNumericPadKeyMask
5835          flag set (this is probably a bug in the OS).
5836       */
5837       if (code < 0x00ff && (flags&NSNumericPadKeyMask))
5838         {
5839           fnKeysym = ns_convert_key ([theEvent keyCode] | NSNumericPadKeyMask);
5840         }
5841       if (fnKeysym == 0)
5842         {
5843           fnKeysym = ns_convert_key (code);
5844         }
5846       if (fnKeysym)
5847         {
5848           /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
5849              because Emacs treats Delete and KP-Delete same (in simple.el). */
5850           if ((fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
5851 #ifdef NS_IMPL_GNUSTEP
5852               /*  GNUstep uses incompatible keycodes, even for those that are
5853                   supposed to be hardware independent.  Just check for delete.
5854                   Keypad delete does not have keysym 0xFFFF.
5855                   See http://savannah.gnu.org/bugs/?25395
5856               */
5857               || (fnKeysym == 0xFFFF && code == 127)
5858 #endif
5859             )
5860             code = 0xFF08; /* backspace */
5861           else
5862             code = fnKeysym;
5863         }
5865       /* are there modifiers? */
5866       emacs_event->modifiers = 0;
5868       if (flags & NSHelpKeyMask)
5869           emacs_event->modifiers |= hyper_modifier;
5871       if (flags & NSShiftKeyMask)
5872         emacs_event->modifiers |= shift_modifier;
5874       is_right_key = (flags & NSRightCommandKeyMask) == NSRightCommandKeyMask;
5875       is_left_key = (flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask
5876         || (! is_right_key && (flags & NSCommandKeyMask) == NSCommandKeyMask);
5878       if (is_right_key)
5879         emacs_event->modifiers |= parse_solitary_modifier
5880           (EQ (ns_right_command_modifier, Qleft)
5881            ? ns_command_modifier
5882            : ns_right_command_modifier);
5884       if (is_left_key)
5885         {
5886           emacs_event->modifiers |= parse_solitary_modifier
5887             (ns_command_modifier);
5889           /* if super (default), take input manager's word so things like
5890              dvorak / qwerty layout work */
5891           if (EQ (ns_command_modifier, Qsuper)
5892               && !fnKeysym
5893               && [[theEvent characters] length] != 0)
5894             {
5895               /* XXX: the code we get will be unshifted, so if we have
5896                  a shift modifier, must convert ourselves */
5897               if (!(flags & NSShiftKeyMask))
5898                 code = [[theEvent characters] characterAtIndex: 0];
5899 #if 0
5900               /* this is ugly and also requires linking w/Carbon framework
5901                  (for LMGetKbdType) so for now leave this rare (?) case
5902                  undealt with.. in future look into CGEvent methods */
5903               else
5904                 {
5905                   long smv = GetScriptManagerVariable (smKeyScript);
5906                   Handle uchrHandle = GetResource
5907                     ('uchr', GetScriptVariable (smv, smScriptKeys));
5908                   UInt32 dummy = 0;
5909                   UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
5910                                  [[theEvent characters] characterAtIndex: 0],
5911                                  kUCKeyActionDisplay,
5912                                  (flags & ~NSCommandKeyMask) >> 8,
5913                                  LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
5914                                  &dummy, 1, &dummy, &code);
5915                   code &= 0xFF;
5916                 }
5917 #endif
5918             }
5919         }
5921       is_right_key = (flags & NSRightControlKeyMask) == NSRightControlKeyMask;
5922       is_left_key = (flags & NSLeftControlKeyMask) == NSLeftControlKeyMask
5923         || (! is_right_key && (flags & NSControlKeyMask) == NSControlKeyMask);
5925       if (is_right_key)
5926           emacs_event->modifiers |= parse_solitary_modifier
5927               (EQ (ns_right_control_modifier, Qleft)
5928                ? ns_control_modifier
5929                : ns_right_control_modifier);
5931       if (is_left_key)
5932         emacs_event->modifiers |= parse_solitary_modifier
5933           (ns_control_modifier);
5935       if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
5936           emacs_event->modifiers |=
5937             parse_solitary_modifier (ns_function_modifier);
5939       left_is_none = NILP (ns_alternate_modifier)
5940         || EQ (ns_alternate_modifier, Qnone);
5942       is_right_key = (flags & NSRightAlternateKeyMask)
5943         == NSRightAlternateKeyMask;
5944       is_left_key = (flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask
5945         || (! is_right_key
5946             && (flags & NSAlternateKeyMask) == NSAlternateKeyMask);
5948       if (is_right_key)
5949         {
5950           if ((NILP (ns_right_alternate_modifier)
5951                || EQ (ns_right_alternate_modifier, Qnone)
5952                || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
5953               && !fnKeysym)
5954             {   /* accept pre-interp alt comb */
5955               if ([[theEvent characters] length] > 0)
5956                 code = [[theEvent characters] characterAtIndex: 0];
5957               /*HACK: clear lone shift modifier to stop next if from firing */
5958               if (emacs_event->modifiers == shift_modifier)
5959                 emacs_event->modifiers = 0;
5960             }
5961           else
5962             emacs_event->modifiers |= parse_solitary_modifier
5963               (EQ (ns_right_alternate_modifier, Qleft)
5964                ? ns_alternate_modifier
5965                : ns_right_alternate_modifier);
5966         }
5968       if (is_left_key) /* default = meta */
5969         {
5970           if (left_is_none && !fnKeysym)
5971             {   /* accept pre-interp alt comb */
5972               if ([[theEvent characters] length] > 0)
5973                 code = [[theEvent characters] characterAtIndex: 0];
5974               /*HACK: clear lone shift modifier to stop next if from firing */
5975               if (emacs_event->modifiers == shift_modifier)
5976                 emacs_event->modifiers = 0;
5977             }
5978           else
5979               emacs_event->modifiers |=
5980                 parse_solitary_modifier (ns_alternate_modifier);
5981         }
5983   if (NS_KEYLOG)
5984     fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
5985              code, fnKeysym, flags, emacs_event->modifiers);
5987       /* if it was a function key or had modifiers, pass it directly to emacs */
5988       if (fnKeysym || (emacs_event->modifiers
5989                        && (emacs_event->modifiers != shift_modifier)
5990                        && [[theEvent charactersIgnoringModifiers] length] > 0))
5991 /*[[theEvent characters] length] */
5992         {
5993           emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5994           if (code < 0x20)
5995             code |= (1<<28)|(3<<16);
5996           else if (code == 0x7f)
5997             code |= (1<<28)|(3<<16);
5998           else if (!fnKeysym)
5999             emacs_event->kind = code > 0xFF
6000               ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
6002           emacs_event->code = code;
6003           EV_TRAILER (theEvent);
6004           processingCompose = NO;
6005           return;
6006         }
6007     }
6010   if (NS_KEYLOG && !processingCompose)
6011     fprintf (stderr, "keyDown: Begin compose sequence.\n");
6013   processingCompose = YES;
6014   [nsEvArray addObject: theEvent];
6015   [self interpretKeyEvents: nsEvArray];
6016   [nsEvArray removeObject: theEvent];
6020 #ifdef NS_IMPL_COCOA
6021 /* Needed to pick up Ctrl-tab and possibly other events that Mac OS X
6022    decided not to send key-down for.
6023    See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
6024    This only applies on Tiger and earlier.
6025    If it matches one of these, send it on to keyDown. */
6026 -(void)keyUp: (NSEvent *)theEvent
6028   int flags = [theEvent modifierFlags];
6029   int code = [theEvent keyCode];
6031   NSTRACE ("[EmacsView keyUp:]");
6033   if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
6034       code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
6035     {
6036       if (NS_KEYLOG)
6037         fprintf (stderr, "keyUp: passed test");
6038       ns_fake_keydown = YES;
6039       [self keyDown: theEvent];
6040     }
6042 #endif
6045 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
6048 /* <NSTextInput>: called when done composing;
6049    NOTE: also called when we delete over working text, followed immed.
6050          by doCommandBySelector: deleteBackward: */
6051 - (void)insertText: (id)aString
6053   int code;
6054   int len = [(NSString *)aString length];
6055   int i;
6057   NSTRACE ("[EmacsView insertText:]");
6059   if (NS_KEYLOG)
6060     NSLog (@"insertText '%@'\tlen = %d", aString, len);
6061   processingCompose = NO;
6063   if (!emacs_event)
6064     return;
6066   /* first, clear any working text */
6067   if (workingText != nil)
6068     [self deleteWorkingText];
6070   /* now insert the string as keystrokes */
6071   for (i =0; i<len; i++)
6072     {
6073       code = [aString characterAtIndex: i];
6074       /* TODO: still need this? */
6075       if (code == 0x2DC)
6076         code = '~'; /* 0x7E */
6077       if (code != 32) /* Space */
6078         emacs_event->modifiers = 0;
6079       emacs_event->kind
6080         = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
6081       emacs_event->code = code;
6082       EV_TRAILER ((id)nil);
6083     }
6087 /* <NSTextInput>: inserts display of composing characters */
6088 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
6090   NSString *str = [aString respondsToSelector: @selector (string)] ?
6091     [aString string] : aString;
6093   NSTRACE ("[EmacsView setMarkedText:selectedRange:]");
6095   if (NS_KEYLOG)
6096     NSLog (@"setMarkedText '%@' len =%lu range %lu from %lu",
6097            str, (unsigned long)[str length],
6098            (unsigned long)selRange.length,
6099            (unsigned long)selRange.location);
6101   if (workingText != nil)
6102     [self deleteWorkingText];
6103   if ([str length] == 0)
6104     return;
6106   if (!emacs_event)
6107     return;
6109   processingCompose = YES;
6110   workingText = [str copy];
6111   ns_working_text = build_string ([workingText UTF8String]);
6113   emacs_event->kind = NS_TEXT_EVENT;
6114   emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
6115   EV_TRAILER ((id)nil);
6119 /* delete display of composing characters [not in <NSTextInput>] */
6120 - (void)deleteWorkingText
6122   NSTRACE ("[EmacsView deleteWorkingText]");
6124   if (workingText == nil)
6125     return;
6126   if (NS_KEYLOG)
6127     NSLog(@"deleteWorkingText len =%lu\n", (unsigned long)[workingText length]);
6128   [workingText release];
6129   workingText = nil;
6130   processingCompose = NO;
6132   if (!emacs_event)
6133     return;
6135   emacs_event->kind = NS_TEXT_EVENT;
6136   emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
6137   EV_TRAILER ((id)nil);
6141 - (BOOL)hasMarkedText
6143   NSTRACE ("[EmacsView hasMarkedText]");
6145   return workingText != nil;
6149 - (NSRange)markedRange
6151   NSTRACE ("[EmacsView markedRange]");
6153   NSRange rng = workingText != nil
6154     ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
6155   if (NS_KEYLOG)
6156     NSLog (@"markedRange request");
6157   return rng;
6161 - (void)unmarkText
6163   NSTRACE ("[EmacsView unmarkText]");
6165   if (NS_KEYLOG)
6166     NSLog (@"unmark (accept) text");
6167   [self deleteWorkingText];
6168   processingCompose = NO;
6172 /* used to position char selection windows, etc. */
6173 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
6175   NSRect rect;
6176   NSPoint pt;
6177   struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
6179   NSTRACE ("[EmacsView firstRectForCharacterRange:]");
6181   if (NS_KEYLOG)
6182     NSLog (@"firstRectForCharRange request");
6184   rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
6185   rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
6186   pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
6187   pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
6188                                        +FRAME_LINE_HEIGHT (emacsframe));
6190   pt = [self convertPoint: pt toView: nil];
6191   pt = [[self window] convertBaseToScreen: pt];
6192   rect.origin = pt;
6193   return rect;
6197 - (NSInteger)conversationIdentifier
6199   return (NSInteger)self;
6203 - (void)doCommandBySelector: (SEL)aSelector
6205   NSTRACE ("[EmacsView doCommandBySelector:]");
6207   if (NS_KEYLOG)
6208     NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
6210   processingCompose = NO;
6211   if (aSelector == @selector (deleteBackward:))
6212     {
6213       /* happens when user backspaces over an ongoing composition:
6214          throw a 'delete' into the event queue */
6215       if (!emacs_event)
6216         return;
6217       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
6218       emacs_event->code = 0xFF08;
6219       EV_TRAILER ((id)nil);
6220     }
6223 - (NSArray *)validAttributesForMarkedText
6225   static NSArray *arr = nil;
6226   if (arr == nil) arr = [NSArray new];
6227  /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
6228   return arr;
6231 - (NSRange)selectedRange
6233   if (NS_KEYLOG)
6234     NSLog (@"selectedRange request");
6235   return NSMakeRange (NSNotFound, 0);
6238 #if defined (NS_IMPL_COCOA) || GNUSTEP_GUI_MAJOR_VERSION > 0 || \
6239     GNUSTEP_GUI_MINOR_VERSION > 22
6240 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
6241 #else
6242 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
6243 #endif
6245   if (NS_KEYLOG)
6246     NSLog (@"characterIndexForPoint request");
6247   return 0;
6250 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
6252   static NSAttributedString *str = nil;
6253   if (str == nil) str = [NSAttributedString new];
6254   if (NS_KEYLOG)
6255     NSLog (@"attributedSubstringFromRange request");
6256   return str;
6259 /* End <NSTextInput> impl. */
6260 /*****************************************************************************/
6263 /* This is what happens when the user presses a mouse button.  */
6264 - (void)mouseDown: (NSEvent *)theEvent
6266   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6267   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
6269   NSTRACE ("[EmacsView mouseDown:]");
6271   [self deleteWorkingText];
6273   if (!emacs_event)
6274     return;
6276   dpyinfo->last_mouse_frame = emacsframe;
6277   /* appears to be needed to prevent spurious movement events generated on
6278      button clicks */
6279   emacsframe->mouse_moved = 0;
6281   if ([theEvent type] == NSScrollWheel)
6282     {
6283       CGFloat delta = [theEvent deltaY];
6284       /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
6285       if (delta == 0)
6286         {
6287           delta = [theEvent deltaX];
6288           if (delta == 0)
6289             {
6290               NSTRACE_MSG ("deltaIsZero");
6291               return;
6292             }
6293           emacs_event->kind = HORIZ_WHEEL_EVENT;
6294         }
6295       else
6296         emacs_event->kind = WHEEL_EVENT;
6298       emacs_event->code = 0;
6299       emacs_event->modifiers = EV_MODIFIERS (theEvent) |
6300         ((delta > 0) ? up_modifier : down_modifier);
6301     }
6302   else
6303     {
6304       emacs_event->kind = MOUSE_CLICK_EVENT;
6305       emacs_event->code = EV_BUTTON (theEvent);
6306       emacs_event->modifiers = EV_MODIFIERS (theEvent)
6307                              | EV_UDMODIFIERS (theEvent);
6308     }
6309   XSETINT (emacs_event->x, lrint (p.x));
6310   XSETINT (emacs_event->y, lrint (p.y));
6311   EV_TRAILER (theEvent);
6315 - (void)rightMouseDown: (NSEvent *)theEvent
6317   NSTRACE ("[EmacsView rightMouseDown:]");
6318   [self mouseDown: theEvent];
6322 - (void)otherMouseDown: (NSEvent *)theEvent
6324   NSTRACE ("[EmacsView otherMouseDown:]");
6325   [self mouseDown: theEvent];
6329 - (void)mouseUp: (NSEvent *)theEvent
6331   NSTRACE ("[EmacsView mouseUp:]");
6332   [self mouseDown: theEvent];
6336 - (void)rightMouseUp: (NSEvent *)theEvent
6338   NSTRACE ("[EmacsView rightMouseUp:]");
6339   [self mouseDown: theEvent];
6343 - (void)otherMouseUp: (NSEvent *)theEvent
6345   NSTRACE ("[EmacsView otherMouseUp:]");
6346   [self mouseDown: theEvent];
6350 - (void) scrollWheel: (NSEvent *)theEvent
6352   NSTRACE ("[EmacsView scrollWheel:]");
6353   [self mouseDown: theEvent];
6357 /* Tell emacs the mouse has moved. */
6358 - (void)mouseMoved: (NSEvent *)e
6360   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
6361   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6362   Lisp_Object frame;
6363   NSPoint pt;
6365   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "[EmacsView mouseMoved:]");
6367   dpyinfo->last_mouse_movement_time = EV_TIMESTAMP (e);
6368   pt = [self convertPoint: [e locationInWindow] fromView: nil];
6369   dpyinfo->last_mouse_motion_x = pt.x;
6370   dpyinfo->last_mouse_motion_y = pt.y;
6372   /* update any mouse face */
6373   if (hlinfo->mouse_face_hidden)
6374     {
6375       hlinfo->mouse_face_hidden = 0;
6376       clear_mouse_face (hlinfo);
6377     }
6379   /* tooltip handling */
6380   previous_help_echo_string = help_echo_string;
6381   help_echo_string = Qnil;
6383   if (!NILP (Vmouse_autoselect_window))
6384     {
6385       NSTRACE_MSG ("mouse_autoselect_window");
6386       static Lisp_Object last_mouse_window;
6387       Lisp_Object window
6388         = window_from_coordinates (emacsframe, pt.x, pt.y, 0, 0);
6390       if (WINDOWP (window)
6391           && !EQ (window, last_mouse_window)
6392           && !EQ (window, selected_window)
6393           && (focus_follows_mouse
6394               || (EQ (XWINDOW (window)->frame,
6395                       XWINDOW (selected_window)->frame))))
6396         {
6397           NSTRACE_MSG ("in_window");
6398           emacs_event->kind = SELECT_WINDOW_EVENT;
6399           emacs_event->frame_or_window = window;
6400           EV_TRAILER2 (e);
6401         }
6402       /* Remember the last window where we saw the mouse.  */
6403       last_mouse_window = window;
6404     }
6406   if (!note_mouse_movement (emacsframe, pt.x, pt.y))
6407     help_echo_string = previous_help_echo_string;
6409   XSETFRAME (frame, emacsframe);
6410   if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
6411     {
6412       /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
6413          (note_mouse_highlight), which is called through the
6414          note_mouse_movement () call above */
6415       any_help_event_p = YES;
6416       gen_help_event (help_echo_string, frame, help_echo_window,
6417                       help_echo_object, help_echo_pos);
6418     }
6420   if (emacsframe->mouse_moved && send_appdefined)
6421     ns_send_appdefined (-1);
6425 - (void)mouseDragged: (NSEvent *)e
6427   NSTRACE ("[EmacsView mouseDragged:]");
6428   [self mouseMoved: e];
6432 - (void)rightMouseDragged: (NSEvent *)e
6434   NSTRACE ("[EmacsView rightMouseDragged:]");
6435   [self mouseMoved: e];
6439 - (void)otherMouseDragged: (NSEvent *)e
6441   NSTRACE ("[EmacsView otherMouseDragged:]");
6442   [self mouseMoved: e];
6446 - (BOOL)windowShouldClose: (id)sender
6448   NSEvent *e =[[self window] currentEvent];
6450   NSTRACE ("[EmacsView windowShouldClose:]");
6451   windowClosing = YES;
6452   if (!emacs_event)
6453     return NO;
6454   emacs_event->kind = DELETE_WINDOW_EVENT;
6455   emacs_event->modifiers = 0;
6456   emacs_event->code = 0;
6457   EV_TRAILER (e);
6458   /* Don't close this window, let this be done from lisp code.  */
6459   return NO;
6462 - (void) updateFrameSize: (BOOL) delay;
6464   NSWindow *window = [self window];
6465   NSRect wr = [window frame];
6466   int extra = 0;
6467   int oldc = cols, oldr = rows;
6468   int oldw = FRAME_PIXEL_WIDTH (emacsframe);
6469   int oldh = FRAME_PIXEL_HEIGHT (emacsframe);
6470   int neww, newh;
6472   NSTRACE ("[EmacsView updateFrameSize:]");
6473   NSTRACE_SIZE ("Original size", NSMakeSize (oldw, oldh));
6474   NSTRACE_RECT ("Original frame", wr);
6475   NSTRACE_MSG  ("Original columns: %d", cols);
6476   NSTRACE_MSG  ("Original rows: %d", rows);
6478   if (! [self isFullscreen])
6479     {
6480 #ifdef NS_IMPL_GNUSTEP
6481       // GNUstep does not always update the tool bar height.  Force it.
6482       if (toolbar && [toolbar isVisible])
6483           update_frame_tool_bar (emacsframe);
6484 #endif
6486       extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6487         + FRAME_TOOLBAR_HEIGHT (emacsframe);
6488     }
6490   if (wait_for_tool_bar)
6491     {
6492       if (FRAME_TOOLBAR_HEIGHT (emacsframe) == 0)
6493         {
6494           NSTRACE_MSG ("Waiting for toolbar");
6495           return;
6496         }
6497       wait_for_tool_bar = NO;
6498     }
6500   neww = (int)wr.size.width - emacsframe->border_width;
6501   newh = (int)wr.size.height - extra;
6503   NSTRACE_SIZE ("New size", NSMakeSize (neww, newh));
6504   NSTRACE_MSG ("tool_bar_height: %d", emacsframe->tool_bar_height);
6506   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, neww);
6507   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, newh);
6509   if (cols < MINWIDTH)
6510     cols = MINWIDTH;
6512   if (rows < MINHEIGHT)
6513     rows = MINHEIGHT;
6515   NSTRACE_MSG ("New columns: %d", cols);
6516   NSTRACE_MSG ("New rows: %d", rows);
6518   if (oldr != rows || oldc != cols || neww != oldw || newh != oldh)
6519     {
6520       NSView *view = FRAME_NS_VIEW (emacsframe);
6522       change_frame_size (emacsframe,
6523                          FRAME_PIXEL_TO_TEXT_WIDTH (emacsframe, neww),
6524                          FRAME_PIXEL_TO_TEXT_HEIGHT (emacsframe, newh),
6525                          0, delay, 0, 1);
6526       SET_FRAME_GARBAGED (emacsframe);
6527       cancel_mouse_face (emacsframe);
6529       wr = NSMakeRect (0, 0, neww, newh);
6531       [view setFrame: wr];
6533       // to do: consider using [NSNotificationCenter postNotificationName:].
6534       [self windowDidMove: // Update top/left.
6535               [NSNotification notificationWithName:NSWindowDidMoveNotification
6536                                             object:[view window]]];
6537     }
6538   else
6539     {
6540       NSTRACE_MSG ("No change");
6541     }
6544 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
6545 /* normalize frame to gridded text size */
6547   int extra = 0;
6549   NSTRACE ("[EmacsView windowWillResize:toSize: " NSTRACE_FMT_SIZE "]",
6550            NSTRACE_ARG_SIZE (frameSize));
6551   NSTRACE_RECT   ("[sender frame]", [sender frame]);
6552   NSTRACE_FSTYPE ("fs_state", fs_state);
6554   if (fs_state == FULLSCREEN_MAXIMIZED
6555       && (maximized_width != (int)frameSize.width
6556           || maximized_height != (int)frameSize.height))
6557     [self setFSValue: FULLSCREEN_NONE];
6558   else if (fs_state == FULLSCREEN_WIDTH
6559            && maximized_width != (int)frameSize.width)
6560     [self setFSValue: FULLSCREEN_NONE];
6561   else if (fs_state == FULLSCREEN_HEIGHT
6562            && maximized_height != (int)frameSize.height)
6563     [self setFSValue: FULLSCREEN_NONE];
6565   if (fs_state == FULLSCREEN_NONE)
6566     maximized_width = maximized_height = -1;
6568   if (! [self isFullscreen])
6569     {
6570       extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6571         + FRAME_TOOLBAR_HEIGHT (emacsframe);
6572     }
6574   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, frameSize.width);
6575   if (cols < MINWIDTH)
6576     cols = MINWIDTH;
6578   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe,
6579                                            frameSize.height - extra);
6580   if (rows < MINHEIGHT)
6581     rows = MINHEIGHT;
6582 #ifdef NS_IMPL_COCOA
6583   {
6584     /* this sets window title to have size in it; the wm does this under GS */
6585     NSRect r = [[self window] frame];
6586     if (r.size.height == frameSize.height && r.size.width == frameSize.width)
6587       {
6588         if (old_title != 0)
6589           {
6590             xfree (old_title);
6591             old_title = 0;
6592           }
6593       }
6594     else if (fs_state == FULLSCREEN_NONE && ! maximizing_resize)
6595       {
6596         char *size_title;
6597         NSWindow *window = [self window];
6598         if (old_title == 0)
6599           {
6600             char *t = strdup ([[[self window] title] UTF8String]);
6601             char *pos = strstr (t, "  â€”  ");
6602             if (pos)
6603               *pos = '\0';
6604             old_title = t;
6605           }
6606         size_title = xmalloc (strlen (old_title) + 40);
6607         esprintf (size_title, "%s  â€”  (%d x %d)", old_title, cols, rows);
6608         [window setTitle: [NSString stringWithUTF8String: size_title]];
6609         [window display];
6610         xfree (size_title);
6611       }
6612   }
6613 #endif /* NS_IMPL_COCOA */
6615   NSTRACE_MSG ("cols: %d  rows: %d", cols, rows);
6617   /* Restrict the new size to the text gird.
6619      Don't restrict the width if the user only adjusted the height, and
6620      vice versa.  (Without this, the frame would shrink, and move
6621      slightly, if the window was resized by dragging one of its
6622      borders.) */
6623   if (!frame_resize_pixelwise)
6624     {
6625       NSRect r = [[self window] frame];
6627       if (r.size.width != frameSize.width)
6628         {
6629           frameSize.width =
6630             FRAME_TEXT_COLS_TO_PIXEL_WIDTH  (emacsframe, cols);
6631         }
6633       if (r.size.height != frameSize.height)
6634         {
6635           frameSize.height =
6636             FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows) + extra;
6637         }
6638     }
6640   NSTRACE_RETURN_SIZE (frameSize);
6642   return frameSize;
6646 - (void)windowDidResize: (NSNotification *)notification
6648   NSTRACE ("[EmacsView windowDidResize:]");
6649   if (!FRAME_LIVE_P (emacsframe))
6650     {
6651       NSTRACE_MSG ("Ignored (frame dead)");
6652       return;
6653     }
6654   if (emacsframe->output_data.ns->in_animation)
6655     {
6656       NSTRACE_MSG ("Ignored (in animation)");
6657       return;
6658     }
6660   if (! [self fsIsNative])
6661     {
6662       NSWindow *theWindow = [notification object];
6663       /* We can get notification on the non-FS window when in
6664          fullscreen mode.  */
6665       if ([self window] != theWindow) return;
6666     }
6668   NSTRACE_RECT ("frame", [[notification object] frame]);
6670 #ifdef NS_IMPL_GNUSTEP
6671   NSWindow *theWindow = [notification object];
6673    /* In GNUstep, at least currently, it's possible to get a didResize
6674       without getting a willResize.. therefore we need to act as if we got
6675       the willResize now */
6676   NSSize sz = [theWindow frame].size;
6677   sz = [self windowWillResize: theWindow toSize: sz];
6678 #endif /* NS_IMPL_GNUSTEP */
6680   if (cols > 0 && rows > 0)
6681     {
6682       [self updateFrameSize: YES];
6683     }
6685   ns_send_appdefined (-1);
6688 #ifdef NS_IMPL_COCOA
6689 - (void)viewDidEndLiveResize
6691   NSTRACE ("[EmacsView viewDidEndLiveResize]");
6693   [super viewDidEndLiveResize];
6694   if (old_title != 0)
6695     {
6696       [[self window] setTitle: [NSString stringWithUTF8String: old_title]];
6697       xfree (old_title);
6698       old_title = 0;
6699     }
6700   maximizing_resize = NO;
6702 #endif /* NS_IMPL_COCOA */
6705 - (void)windowDidBecomeKey: (NSNotification *)notification
6706 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6708   [self windowDidBecomeKey];
6712 - (void)windowDidBecomeKey      /* for direct calls */
6714   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6715   struct frame *old_focus = dpyinfo->x_focus_frame;
6717   NSTRACE ("[EmacsView windowDidBecomeKey]");
6719   if (emacsframe != old_focus)
6720     dpyinfo->x_focus_frame = emacsframe;
6722   ns_frame_rehighlight (emacsframe);
6724   if (emacs_event)
6725     {
6726       emacs_event->kind = FOCUS_IN_EVENT;
6727       EV_TRAILER ((id)nil);
6728     }
6732 - (void)windowDidResignKey: (NSNotification *)notification
6733 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6735   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6736   BOOL is_focus_frame = dpyinfo->x_focus_frame == emacsframe;
6737   NSTRACE ("[EmacsView windowDidResignKey:]");
6739   if (is_focus_frame)
6740     dpyinfo->x_focus_frame = 0;
6742   emacsframe->mouse_moved = 0;
6743   ns_frame_rehighlight (emacsframe);
6745   /* FIXME: for some reason needed on second and subsequent clicks away
6746             from sole-frame Emacs to get hollow box to show */
6747   if (!windowClosing && [[self window] isVisible] == YES)
6748     {
6749       x_update_cursor (emacsframe, 1);
6750       x_set_frame_alpha (emacsframe);
6751     }
6753   if (any_help_event_p)
6754     {
6755       Lisp_Object frame;
6756       XSETFRAME (frame, emacsframe);
6757       help_echo_string = Qnil;
6758       gen_help_event (Qnil, frame, Qnil, Qnil, 0);
6759     }
6761   if (emacs_event && is_focus_frame)
6762     {
6763       [self deleteWorkingText];
6764       emacs_event->kind = FOCUS_OUT_EVENT;
6765       EV_TRAILER ((id)nil);
6766     }
6770 - (void)windowWillMiniaturize: sender
6772   NSTRACE ("[EmacsView windowWillMiniaturize:]");
6776 - (void)setFrame:(NSRect)frameRect;
6778   NSTRACE ("[EmacsView setFrame:" NSTRACE_FMT_RECT "]",
6779            NSTRACE_ARG_RECT (frameRect));
6781   [super setFrame:(NSRect)frameRect];
6785 - (BOOL)isFlipped
6787   return YES;
6791 - (BOOL)isOpaque
6793   return NO;
6797 - initFrameFromEmacs: (struct frame *)f
6799   NSRect r, wr;
6800   Lisp_Object tem;
6801   NSWindow *win;
6802   NSColor *col;
6803   NSString *name;
6805   NSTRACE ("[EmacsView initFrameFromEmacs:]");
6806   NSTRACE_MSG ("cols:%d lines:%d", f->text_cols, f->text_lines);
6808   windowClosing = NO;
6809   processingCompose = NO;
6810   scrollbarsNeedingUpdate = 0;
6811   fs_state = FULLSCREEN_NONE;
6812   fs_before_fs = next_maximized = -1;
6813 #ifdef HAVE_NATIVE_FS
6814   fs_is_native = ns_use_native_fullscreen;
6815 #else
6816   fs_is_native = NO;
6817 #endif
6818   maximized_width = maximized_height = -1;
6819   nonfs_window = nil;
6821   ns_userRect = NSMakeRect (0, 0, 0, 0);
6822   r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
6823                  FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
6824   [self initWithFrame: r];
6825   [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
6827   FRAME_NS_VIEW (f) = self;
6828   emacsframe = f;
6829 #ifdef NS_IMPL_COCOA
6830   old_title = 0;
6831   maximizing_resize = NO;
6832 #endif
6834   win = [[EmacsWindow alloc]
6835             initWithContentRect: r
6836                       styleMask: (NSResizableWindowMask |
6837 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6838                                   NSTitledWindowMask |
6839 #endif
6840                                   NSMiniaturizableWindowMask |
6841                                   NSClosableWindowMask)
6842                         backing: NSBackingStoreBuffered
6843                           defer: YES];
6845 #ifdef HAVE_NATIVE_FS
6846     [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
6847 #endif
6849   wr = [win frame];
6850   bwidth = f->border_width = wr.size.width - r.size.width;
6851   tibar_height = FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
6853   [win setAcceptsMouseMovedEvents: YES];
6854   [win setDelegate: self];
6855 #if !defined (NS_IMPL_COCOA) || \
6856   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6857   [win useOptimizedDrawing: YES];
6858 #endif
6860   [[win contentView] addSubview: self];
6862   if (ns_drag_types)
6863     [self registerForDraggedTypes: ns_drag_types];
6865   tem = f->name;
6866   name = [NSString stringWithUTF8String:
6867                    NILP (tem) ? "Emacs" : SSDATA (tem)];
6868   [win setTitle: name];
6870   /* toolbar support */
6871   toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
6872                          [NSString stringWithFormat: @"Emacs Frame %d",
6873                                    ns_window_num]];
6874   [win setToolbar: toolbar];
6875   [toolbar setVisible: NO];
6877   /* Don't set frame garbaged until tool bar is up to date?
6878      This avoids an extra clear and redraw (flicker) at frame creation.  */
6879   if (FRAME_EXTERNAL_TOOL_BAR (f)) wait_for_tool_bar = YES;
6880   else wait_for_tool_bar = NO;
6883 #ifdef NS_IMPL_COCOA
6884   {
6885     NSButton *toggleButton;
6886   toggleButton = [win standardWindowButton: NSWindowToolbarButton];
6887   [toggleButton setTarget: self];
6888   [toggleButton setAction: @selector (toggleToolbar: )];
6889   }
6890 #endif
6891   FRAME_TOOLBAR_HEIGHT (f) = 0;
6893   tem = f->icon_name;
6894   if (!NILP (tem))
6895     [win setMiniwindowTitle:
6896            [NSString stringWithUTF8String: SSDATA (tem)]];
6898   {
6899     NSScreen *screen = [win screen];
6901     if (screen != 0)
6902       {
6903         NSPoint pt = NSMakePoint
6904           (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
6905            IN_BOUND (-SCREENMAX,
6906                      [screen frame].size.height - NS_TOP_POS (f), SCREENMAX));
6908         [win setFrameTopLeftPoint: pt];
6910         NSTRACE_RECT ("new frame", [win frame]);
6911       }
6912   }
6914   [win makeFirstResponder: self];
6916   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6917                                   (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
6918   [win setBackgroundColor: col];
6919   if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6920     [win setOpaque: NO];
6922 #if !defined (NS_IMPL_COCOA) || \
6923   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6924   [self allocateGState];
6925 #endif
6926   [NSApp registerServicesMenuSendTypes: ns_send_types
6927                            returnTypes: nil];
6929   ns_window_num++;
6930   return self;
6934 - (void)windowDidMove: sender
6936   NSWindow *win = [self window];
6937   NSRect r = [win frame];
6938   NSArray *screens = [NSScreen screens];
6939   NSScreen *screen = [screens objectAtIndex: 0];
6941   NSTRACE ("[EmacsView windowDidMove:]");
6943   if (!emacsframe->output_data.ns)
6944     return;
6945   if (screen != nil)
6946     {
6947       emacsframe->left_pos = r.origin.x;
6948       emacsframe->top_pos =
6949         [screen frame].size.height - (r.origin.y + r.size.height);
6950     }
6954 /* Called AFTER method below, but before our windowWillResize call there leads
6955    to windowDidResize -> x_set_window_size.  Update emacs' notion of frame
6956    location so set_window_size moves the frame. */
6957 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
6959   NSTRACE (("[EmacsView windowShouldZoom:toFrame:" NSTRACE_FMT_RECT "]"
6960             NSTRACE_FMT_RETURN "YES"),
6961            NSTRACE_ARG_RECT (newFrame));
6963   emacsframe->output_data.ns->zooming = 1;
6964   return YES;
6968 /* Override to do something slightly nonstandard, but nice.  First click on
6969    zoom button will zoom vertically.  Second will zoom completely.  Third
6970    returns to original. */
6971 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
6972                         defaultFrame:(NSRect)defaultFrame
6974   // TODO: Rename to "currentFrame" and assign "result" properly in
6975   // all paths.
6976   NSRect result = [sender frame];
6978   NSTRACE (("[EmacsView windowWillUseStandardFrame:defaultFrame:"
6979             NSTRACE_FMT_RECT "]"),
6980            NSTRACE_ARG_RECT (defaultFrame));
6981   NSTRACE_FSTYPE ("fs_state", fs_state);
6982   NSTRACE_FSTYPE ("fs_before_fs", fs_before_fs);
6983   NSTRACE_FSTYPE ("next_maximized", next_maximized);
6984   NSTRACE_RECT   ("ns_userRect", ns_userRect);
6985   NSTRACE_RECT   ("[sender frame]", [sender frame]);
6987   if (fs_before_fs != -1) /* Entering fullscreen */
6988     {
6989       NSTRACE_MSG ("Entering fullscreen");
6990       result = defaultFrame;
6991     }
6992   else
6993     {
6994       // Save the window size and position (frame) before the resize.
6995       if (fs_state != FULLSCREEN_MAXIMIZED
6996           && fs_state != FULLSCREEN_WIDTH)
6997         {
6998           ns_userRect.size.width = result.size.width;
6999           ns_userRect.origin.x   = result.origin.x;
7000         }
7002       if (fs_state != FULLSCREEN_MAXIMIZED
7003           && fs_state != FULLSCREEN_HEIGHT)
7004         {
7005           ns_userRect.size.height = result.size.height;
7006           ns_userRect.origin.y    = result.origin.y;
7007         }
7009       NSTRACE_RECT ("ns_userRect (2)", ns_userRect);
7011       if (next_maximized == FULLSCREEN_HEIGHT
7012           || (next_maximized == -1
7013               && abs ((int)(defaultFrame.size.height - result.size.height))
7014               > FRAME_LINE_HEIGHT (emacsframe)))
7015         {
7016           /* first click */
7017           NSTRACE_MSG ("FULLSCREEN_HEIGHT");
7018           maximized_height = result.size.height = defaultFrame.size.height;
7019           maximized_width = -1;
7020           result.origin.y = defaultFrame.origin.y;
7021           if (ns_userRect.size.height != 0)
7022             {
7023               result.origin.x = ns_userRect.origin.x;
7024               result.size.width = ns_userRect.size.width;
7025             }
7026           [self setFSValue: FULLSCREEN_HEIGHT];
7027 #ifdef NS_IMPL_COCOA
7028           maximizing_resize = YES;
7029 #endif
7030         }
7031       else if (next_maximized == FULLSCREEN_WIDTH)
7032         {
7033           NSTRACE_MSG ("FULLSCREEN_WIDTH");
7034           maximized_width = result.size.width = defaultFrame.size.width;
7035           maximized_height = -1;
7036           result.origin.x = defaultFrame.origin.x;
7037           if (ns_userRect.size.width != 0)
7038             {
7039               result.origin.y = ns_userRect.origin.y;
7040               result.size.height = ns_userRect.size.height;
7041             }
7042           [self setFSValue: FULLSCREEN_WIDTH];
7043         }
7044       else if (next_maximized == FULLSCREEN_MAXIMIZED
7045                || (next_maximized == -1
7046                    && abs ((int)(defaultFrame.size.width - result.size.width))
7047                    > FRAME_COLUMN_WIDTH (emacsframe)))
7048         {
7049           NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
7051           result = defaultFrame;  /* second click */
7052           maximized_width = result.size.width;
7053           maximized_height = result.size.height;
7054           [self setFSValue: FULLSCREEN_MAXIMIZED];
7055 #ifdef NS_IMPL_COCOA
7056           maximizing_resize = YES;
7057 #endif
7058         }
7059       else
7060         {
7061           /* restore */
7062           NSTRACE_MSG ("Restore");
7063           result = ns_userRect.size.height ? ns_userRect : result;
7064           NSTRACE_RECT ("restore (2)", result);
7065           ns_userRect = NSMakeRect (0, 0, 0, 0);
7066 #ifdef NS_IMPL_COCOA
7067           maximizing_resize = fs_state != FULLSCREEN_NONE;
7068 #endif
7069           [self setFSValue: FULLSCREEN_NONE];
7070           maximized_width = maximized_height = -1;
7071         }
7072     }
7074   if (fs_before_fs == -1) next_maximized = -1;
7076   NSTRACE_RECT   ("Final ns_userRect", ns_userRect);
7077   NSTRACE_MSG    ("Final maximized_width: %d", maximized_width);
7078   NSTRACE_MSG    ("Final maximized_height: %d", maximized_height);
7079   NSTRACE_FSTYPE ("Final next_maximized", next_maximized);
7081   [self windowWillResize: sender toSize: result.size];
7083   NSTRACE_RETURN_RECT (result);
7085   return result;
7089 - (void)windowDidDeminiaturize: sender
7091   NSTRACE ("[EmacsView windowDidDeminiaturize:]");
7092   if (!emacsframe->output_data.ns)
7093     return;
7095   SET_FRAME_ICONIFIED (emacsframe, 0);
7096   SET_FRAME_VISIBLE (emacsframe, 1);
7097   windows_or_buffers_changed = 63;
7099   if (emacs_event)
7100     {
7101       emacs_event->kind = DEICONIFY_EVENT;
7102       EV_TRAILER ((id)nil);
7103     }
7107 - (void)windowDidExpose: sender
7109   NSTRACE ("[EmacsView windowDidExpose:]");
7110   if (!emacsframe->output_data.ns)
7111     return;
7113   SET_FRAME_VISIBLE (emacsframe, 1);
7114   SET_FRAME_GARBAGED (emacsframe);
7116   if (send_appdefined)
7117     ns_send_appdefined (-1);
7121 - (void)windowDidMiniaturize: sender
7123   NSTRACE ("[EmacsView windowDidMiniaturize:]");
7124   if (!emacsframe->output_data.ns)
7125     return;
7127   SET_FRAME_ICONIFIED (emacsframe, 1);
7128   SET_FRAME_VISIBLE (emacsframe, 0);
7130   if (emacs_event)
7131     {
7132       emacs_event->kind = ICONIFY_EVENT;
7133       EV_TRAILER ((id)nil);
7134     }
7137 #ifdef HAVE_NATIVE_FS
7138 - (NSApplicationPresentationOptions)window:(NSWindow *)window
7139       willUseFullScreenPresentationOptions:
7140   (NSApplicationPresentationOptions)proposedOptions
7142   return proposedOptions|NSApplicationPresentationAutoHideToolbar;
7144 #endif
7146 - (void)windowWillEnterFullScreen:(NSNotification *)notification
7148   NSTRACE ("[EmacsView windowWillEnterFullScreen:]");
7149   [self windowWillEnterFullScreen];
7151 - (void)windowWillEnterFullScreen /* provided for direct calls */
7153   NSTRACE ("[EmacsView windowWillEnterFullScreen]");
7154   fs_before_fs = fs_state;
7157 - (void)windowDidEnterFullScreen:(NSNotification *)notification
7159   NSTRACE ("[EmacsView windowDidEnterFullScreen:]");
7160   [self windowDidEnterFullScreen];
7163 - (void)windowDidEnterFullScreen /* provided for direct calls */
7165   NSTRACE ("[EmacsView windowDidEnterFullScreen]");
7166   [self setFSValue: FULLSCREEN_BOTH];
7167   if (! [self fsIsNative])
7168     {
7169       [self windowDidBecomeKey];
7170       [nonfs_window orderOut:self];
7171     }
7172   else
7173     {
7174       BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (emacsframe) ? YES : NO;
7175 #ifdef NS_IMPL_COCOA
7176 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
7177       unsigned val = (unsigned)[NSApp presentationOptions];
7179       // Mac OS X 10.7 bug fix, the menu won't appear without this.
7180       // val is non-zero on other macOS versions.
7181       if (val == 0)
7182         {
7183           NSApplicationPresentationOptions options
7184             = NSApplicationPresentationAutoHideDock
7185             | NSApplicationPresentationAutoHideMenuBar
7186             | NSApplicationPresentationFullScreen
7187             | NSApplicationPresentationAutoHideToolbar;
7189           [NSApp setPresentationOptions: options];
7190         }
7191 #endif
7192 #endif
7193       [toolbar setVisible:tbar_visible];
7194     }
7197 - (void)windowWillExitFullScreen:(NSNotification *)notification
7199   NSTRACE ("[EmacsView windowWillExitFullScreen:]");
7200   [self windowWillExitFullScreen];
7203 - (void)windowWillExitFullScreen /* provided for direct calls */
7205   NSTRACE ("[EmacsView windowWillExitFullScreen]");
7206   if (!FRAME_LIVE_P (emacsframe))
7207     {
7208       NSTRACE_MSG ("Ignored (frame dead)");
7209       return;
7210     }
7211   if (next_maximized != -1)
7212     fs_before_fs = next_maximized;
7215 - (void)windowDidExitFullScreen:(NSNotification *)notification
7217   NSTRACE ("[EmacsView windowDidExitFullScreen:]");
7218   [self windowDidExitFullScreen];
7221 - (void)windowDidExitFullScreen /* provided for direct calls */
7223   NSTRACE ("[EmacsView windowDidExitFullScreen]");
7224   if (!FRAME_LIVE_P (emacsframe))
7225     {
7226       NSTRACE_MSG ("Ignored (frame dead)");
7227       return;
7228     }
7229   [self setFSValue: fs_before_fs];
7230   fs_before_fs = -1;
7231 #ifdef HAVE_NATIVE_FS
7232   [self updateCollectionBehavior];
7233 #endif
7234   if (FRAME_EXTERNAL_TOOL_BAR (emacsframe))
7235     {
7236       [toolbar setVisible:YES];
7237       update_frame_tool_bar (emacsframe);
7238       [self updateFrameSize:YES];
7239       [[self window] display];
7240     }
7241   else
7242     [toolbar setVisible:NO];
7244   if (next_maximized != -1)
7245     [[self window] performZoom:self];
7248 - (BOOL)fsIsNative
7250   return fs_is_native;
7253 - (BOOL)isFullscreen
7255   BOOL res;
7257   if (! fs_is_native)
7258     {
7259       res = (nonfs_window != nil);
7260     }
7261   else
7262     {
7263 #ifdef HAVE_NATIVE_FS
7264       res = (([[self window] styleMask] & NSFullScreenWindowMask) != 0);
7265 #else
7266       res = NO;
7267 #endif
7268     }
7270   NSTRACE ("[EmacsView isFullscreen] " NSTRACE_FMT_RETURN " %d",
7271            (int) res);
7273   return res;
7276 #ifdef HAVE_NATIVE_FS
7277 - (void)updateCollectionBehavior
7279   NSTRACE ("[EmacsView updateCollectionBehavior]");
7281   if (! [self isFullscreen])
7282     {
7283       NSWindow *win = [self window];
7284       NSWindowCollectionBehavior b = [win collectionBehavior];
7285       if (ns_use_native_fullscreen)
7286         b |= NSWindowCollectionBehaviorFullScreenPrimary;
7287       else
7288         b &= ~NSWindowCollectionBehaviorFullScreenPrimary;
7290       [win setCollectionBehavior: b];
7291       fs_is_native = ns_use_native_fullscreen;
7292     }
7294 #endif
7296 - (void)toggleFullScreen: (id)sender
7298   NSWindow *w, *fw;
7299   BOOL onFirstScreen;
7300   struct frame *f;
7301   NSRect r, wr;
7302   NSColor *col;
7304   NSTRACE ("[EmacsView toggleFullScreen:]");
7306   if (fs_is_native)
7307     {
7308 #ifdef HAVE_NATIVE_FS
7309       [[self window] toggleFullScreen:sender];
7310 #endif
7311       return;
7312     }
7314   w = [self window];
7315   onFirstScreen = [[w screen] isEqual:[[NSScreen screens] objectAtIndex:0]];
7316   f = emacsframe;
7317   wr = [w frame];
7318   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
7319                                  (FRAME_DEFAULT_FACE (f)),
7320                                  f);
7322   if (fs_state != FULLSCREEN_BOTH)
7323     {
7324       NSScreen *screen = [w screen];
7326 #if defined (NS_IMPL_COCOA) && \
7327   MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7328       /* Hide ghost menu bar on secondary monitor? */
7329       if (! onFirstScreen)
7330         onFirstScreen = [NSScreen screensHaveSeparateSpaces];
7331 #endif
7332       /* Hide dock and menubar if we are on the primary screen.  */
7333       if (onFirstScreen)
7334         {
7335 #ifdef NS_IMPL_COCOA
7336           NSApplicationPresentationOptions options
7337             = NSApplicationPresentationAutoHideDock
7338             | NSApplicationPresentationAutoHideMenuBar;
7340           [NSApp setPresentationOptions: options];
7341 #else
7342           [NSMenu setMenuBarVisible:NO];
7343 #endif
7344         }
7346       fw = [[EmacsFSWindow alloc]
7347                        initWithContentRect:[w contentRectForFrameRect:wr]
7348                                  styleMask:NSBorderlessWindowMask
7349                                    backing:NSBackingStoreBuffered
7350                                      defer:YES
7351                                     screen:screen];
7353       [fw setContentView:[w contentView]];
7354       [fw setTitle:[w title]];
7355       [fw setDelegate:self];
7356       [fw setAcceptsMouseMovedEvents: YES];
7357 #if !defined (NS_IMPL_COCOA) || \
7358   MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
7359       [fw useOptimizedDrawing: YES];
7360 #endif
7361       [fw setBackgroundColor: col];
7362       if ([col alphaComponent] != (EmacsCGFloat) 1.0)
7363         [fw setOpaque: NO];
7365       f->border_width = 0;
7366       FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
7367       tobar_height = FRAME_TOOLBAR_HEIGHT (f);
7368       FRAME_TOOLBAR_HEIGHT (f) = 0;
7370       nonfs_window = w;
7372       [self windowWillEnterFullScreen];
7373       [fw makeKeyAndOrderFront:NSApp];
7374       [fw makeFirstResponder:self];
7375       [w orderOut:self];
7376       r = [fw frameRectForContentRect:[screen frame]];
7377       [fw setFrame: r display:YES animate:ns_use_fullscreen_animation];
7378       [self windowDidEnterFullScreen];
7379       [fw display];
7380     }
7381   else
7382     {
7383       fw = w;
7384       w = nonfs_window;
7385       nonfs_window = nil;
7387       if (onFirstScreen)
7388         {
7389 #ifdef NS_IMPL_COCOA
7390           [NSApp setPresentationOptions: NSApplicationPresentationDefault];
7391 #else
7392           [NSMenu setMenuBarVisible:YES];
7393 #endif
7394         }
7396       [w setContentView:[fw contentView]];
7397       [w setBackgroundColor: col];
7398       if ([col alphaComponent] != (EmacsCGFloat) 1.0)
7399         [w setOpaque: NO];
7401       f->border_width = bwidth;
7402       FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
7403       if (FRAME_EXTERNAL_TOOL_BAR (f))
7404         FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
7406       // to do: consider using [NSNotificationCenter postNotificationName:] to send notifications.
7408       [self windowWillExitFullScreen];
7409       [fw setFrame: [w frame] display:YES animate:ns_use_fullscreen_animation];
7410       [fw close];
7411       [w makeKeyAndOrderFront:NSApp];
7412       [self windowDidExitFullScreen];
7413       [self updateFrameSize:YES];
7414     }
7417 - (void)handleFS
7419   NSTRACE ("[EmacsView handleFS]");
7421   if (fs_state != emacsframe->want_fullscreen)
7422     {
7423       if (fs_state == FULLSCREEN_BOTH)
7424         {
7425           NSTRACE_MSG ("fs_state == FULLSCREEN_BOTH");
7426           [self toggleFullScreen:self];
7427         }
7429       switch (emacsframe->want_fullscreen)
7430         {
7431         case FULLSCREEN_BOTH:
7432           NSTRACE_MSG ("FULLSCREEN_BOTH");
7433           [self toggleFullScreen:self];
7434           break;
7435         case FULLSCREEN_WIDTH:
7436           NSTRACE_MSG ("FULLSCREEN_WIDTH");
7437           next_maximized = FULLSCREEN_WIDTH;
7438           if (fs_state != FULLSCREEN_BOTH)
7439             [[self window] performZoom:self];
7440           break;
7441         case FULLSCREEN_HEIGHT:
7442           NSTRACE_MSG ("FULLSCREEN_HEIGHT");
7443           next_maximized = FULLSCREEN_HEIGHT;
7444           if (fs_state != FULLSCREEN_BOTH)
7445             [[self window] performZoom:self];
7446           break;
7447         case FULLSCREEN_MAXIMIZED:
7448           NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
7449           next_maximized = FULLSCREEN_MAXIMIZED;
7450           if (fs_state != FULLSCREEN_BOTH)
7451             [[self window] performZoom:self];
7452           break;
7453         case FULLSCREEN_NONE:
7454           NSTRACE_MSG ("FULLSCREEN_NONE");
7455           if (fs_state != FULLSCREEN_BOTH)
7456             {
7457               next_maximized = FULLSCREEN_NONE;
7458               [[self window] performZoom:self];
7459             }
7460           break;
7461         }
7463       emacsframe->want_fullscreen = FULLSCREEN_NONE;
7464     }
7468 - (void) setFSValue: (int)value
7470   NSTRACE ("[EmacsView setFSValue:" NSTRACE_FMT_FSTYPE "]",
7471            NSTRACE_ARG_FSTYPE(value));
7473   Lisp_Object lval = Qnil;
7474   switch (value)
7475     {
7476     case FULLSCREEN_BOTH:
7477       lval = Qfullboth;
7478       break;
7479     case FULLSCREEN_WIDTH:
7480       lval = Qfullwidth;
7481       break;
7482     case FULLSCREEN_HEIGHT:
7483       lval = Qfullheight;
7484       break;
7485     case FULLSCREEN_MAXIMIZED:
7486       lval = Qmaximized;
7487       break;
7488     }
7489   store_frame_param (emacsframe, Qfullscreen, lval);
7490   fs_state = value;
7493 - (void)mouseEntered: (NSEvent *)theEvent
7495   NSTRACE ("[EmacsView mouseEntered:]");
7496   if (emacsframe)
7497     FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7498       = EV_TIMESTAMP (theEvent);
7502 - (void)mouseExited: (NSEvent *)theEvent
7504   Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
7506   NSTRACE ("[EmacsView mouseExited:]");
7508   if (!hlinfo)
7509     return;
7511   FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7512     = EV_TIMESTAMP (theEvent);
7514   if (emacsframe == hlinfo->mouse_face_mouse_frame)
7515     {
7516       clear_mouse_face (hlinfo);
7517       hlinfo->mouse_face_mouse_frame = 0;
7518     }
7522 - menuDown: sender
7524   NSTRACE ("[EmacsView menuDown:]");
7525   if (context_menu_value == -1)
7526     context_menu_value = [sender tag];
7527   else
7528     {
7529       NSInteger tag = [sender tag];
7530       find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
7531                                     emacsframe->menu_bar_vector,
7532                                     (void *)tag);
7533     }
7535   ns_send_appdefined (-1);
7536   return self;
7540 - (EmacsToolbar *)toolbar
7542   return toolbar;
7546 /* this gets called on toolbar button click */
7547 - toolbarClicked: (id)item
7549   NSEvent *theEvent;
7550   int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
7552   NSTRACE ("[EmacsView toolbarClicked:]");
7554   if (!emacs_event)
7555     return self;
7557   /* send first event (for some reason two needed) */
7558   theEvent = [[self window] currentEvent];
7559   emacs_event->kind = TOOL_BAR_EVENT;
7560   XSETFRAME (emacs_event->arg, emacsframe);
7561   EV_TRAILER (theEvent);
7563   emacs_event->kind = TOOL_BAR_EVENT;
7564 /*   XSETINT (emacs_event->code, 0); */
7565   emacs_event->arg = AREF (emacsframe->tool_bar_items,
7566                            idx + TOOL_BAR_ITEM_KEY);
7567   emacs_event->modifiers = EV_MODIFIERS (theEvent);
7568   EV_TRAILER (theEvent);
7569   return self;
7573 - toggleToolbar: (id)sender
7575   NSTRACE ("[EmacsView toggleToolbar:]");
7577   if (!emacs_event)
7578     return self;
7580   emacs_event->kind = NS_NONKEY_EVENT;
7581   emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
7582   EV_TRAILER ((id)nil);
7583   return self;
7587 - (void)drawRect: (NSRect)rect
7589   int x = NSMinX (rect), y = NSMinY (rect);
7590   int width = NSWidth (rect), height = NSHeight (rect);
7592   NSTRACE ("[EmacsView drawRect:" NSTRACE_FMT_RECT "]",
7593            NSTRACE_ARG_RECT(rect));
7595   if (!emacsframe || !emacsframe->output_data.ns)
7596     return;
7598   ns_clear_frame_area (emacsframe, x, y, width, height);
7599   block_input ();
7600   expose_frame (emacsframe, x, y, width, height);
7601   unblock_input ();
7603   /*
7604     drawRect: may be called (at least in Mac OS X 10.5) for invisible
7605     views as well for some reason.  Thus, do not infer visibility
7606     here.
7608     emacsframe->async_visible = 1;
7609     emacsframe->async_iconified = 0;
7610   */
7614 /* NSDraggingDestination protocol methods.  Actually this is not really a
7615    protocol, but a category of Object.  O well...  */
7617 -(NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
7619   NSTRACE ("[EmacsView draggingEntered:]");
7620   return NSDragOperationGeneric;
7624 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
7626   return YES;
7630 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
7632   id pb;
7633   int x, y;
7634   NSString *type;
7635   NSEvent *theEvent = [[self window] currentEvent];
7636   NSPoint position;
7637   NSDragOperation op = [sender draggingSourceOperationMask];
7638   int modifiers = 0;
7640   NSTRACE ("[EmacsView performDragOperation:]");
7642   if (!emacs_event)
7643     return NO;
7645   position = [self convertPoint: [sender draggingLocation] fromView: nil];
7646   x = lrint (position.x);  y = lrint (position.y);
7648   pb = [sender draggingPasteboard];
7649   type = [pb availableTypeFromArray: ns_drag_types];
7651   if (! (op & (NSDragOperationMove|NSDragOperationDelete)) &&
7652       // URL drags contain all operations (0xf), don't allow all to be set.
7653       (op & 0xf) != 0xf)
7654     {
7655       if (op & NSDragOperationLink)
7656         modifiers |= NSControlKeyMask;
7657       if (op & NSDragOperationCopy)
7658         modifiers |= NSAlternateKeyMask;
7659       if (op & NSDragOperationGeneric)
7660         modifiers |= NSCommandKeyMask;
7661     }
7663   modifiers = EV_MODIFIERS2 (modifiers);
7664   if (type == 0)
7665     {
7666       return NO;
7667     }
7668   else if ([type isEqualToString: NSFilenamesPboardType])
7669     {
7670       NSArray *files;
7671       NSEnumerator *fenum;
7672       NSString *file;
7674       if (!(files = [pb propertyListForType: type]))
7675         return NO;
7677       fenum = [files objectEnumerator];
7678       while ( (file = [fenum nextObject]) )
7679         {
7680           emacs_event->kind = DRAG_N_DROP_EVENT;
7681           XSETINT (emacs_event->x, x);
7682           XSETINT (emacs_event->y, y);
7683           ns_input_file = append2 (ns_input_file,
7684                                    build_string ([file UTF8String]));
7685           emacs_event->modifiers = modifiers;
7686           emacs_event->arg =  list2 (Qfile, build_string ([file UTF8String]));
7687           EV_TRAILER (theEvent);
7688         }
7689       return YES;
7690     }
7691   else if ([type isEqualToString: NSURLPboardType])
7692     {
7693       NSURL *url = [NSURL URLFromPasteboard: pb];
7694       if (url == nil) return NO;
7696       emacs_event->kind = DRAG_N_DROP_EVENT;
7697       XSETINT (emacs_event->x, x);
7698       XSETINT (emacs_event->y, y);
7699       emacs_event->modifiers = modifiers;
7700       emacs_event->arg =  list2 (Qurl,
7701                                  build_string ([[url absoluteString]
7702                                                  UTF8String]));
7703       EV_TRAILER (theEvent);
7705       if ([url isFileURL] != NO)
7706         {
7707           NSString *file = [url path];
7708           ns_input_file = append2 (ns_input_file,
7709                                    build_string ([file UTF8String]));
7710         }
7711       return YES;
7712     }
7713   else if ([type isEqualToString: NSStringPboardType]
7714            || [type isEqualToString: NSTabularTextPboardType])
7715     {
7716       NSString *data;
7718       if (! (data = [pb stringForType: type]))
7719         return NO;
7721       emacs_event->kind = DRAG_N_DROP_EVENT;
7722       XSETINT (emacs_event->x, x);
7723       XSETINT (emacs_event->y, y);
7724       emacs_event->modifiers = modifiers;
7725       emacs_event->arg =  list2 (Qnil, build_string ([data UTF8String]));
7726       EV_TRAILER (theEvent);
7727       return YES;
7728     }
7729   else
7730     {
7731       fprintf (stderr, "Invalid data type in dragging pasteboard");
7732       return NO;
7733     }
7737 - (id) validRequestorForSendType: (NSString *)typeSent
7738                       returnType: (NSString *)typeReturned
7740   NSTRACE ("[EmacsView validRequestorForSendType:returnType:]");
7741   if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
7742       && typeReturned == nil)
7743     {
7744       if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
7745         return self;
7746     }
7748   return [super validRequestorForSendType: typeSent
7749                                returnType: typeReturned];
7753 /* The next two methods are part of NSServicesRequests informal protocol,
7754    supposedly called when a services menu item is chosen from this app.
7755    But this should not happen because we override the services menu with our
7756    own entries which call ns-perform-service.
7757    Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
7758    So let's at least stub them out until further investigation can be done. */
7760 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
7762   /* we could call ns_string_from_pasteboard(pboard) here but then it should
7763      be written into the buffer in place of the existing selection..
7764      ordinary service calls go through functions defined in ns-win.el */
7765   return NO;
7768 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
7770   NSArray *typesDeclared;
7771   Lisp_Object val;
7773   NSTRACE ("[EmacsView writeSelectionToPasteboard:types:]");
7775   /* We only support NSStringPboardType */
7776   if ([types containsObject:NSStringPboardType] == NO) {
7777     return NO;
7778   }
7780   val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7781   if (CONSP (val) && SYMBOLP (XCAR (val)))
7782     {
7783       val = XCDR (val);
7784       if (CONSP (val) && NILP (XCDR (val)))
7785         val = XCAR (val);
7786     }
7787   if (! STRINGP (val))
7788     return NO;
7790   typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
7791   [pb declareTypes:typesDeclared owner:nil];
7792   ns_string_to_pasteboard (pb, val);
7793   return YES;
7797 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
7798    (gives a miniaturized version of the window); currently we use the latter for
7799    frames whose active buffer doesn't correspond to any file
7800    (e.g., '*scratch*') */
7801 - setMiniwindowImage: (BOOL) setMini
7803   id image = [[self window] miniwindowImage];
7804   NSTRACE ("[EmacsView setMiniwindowImage:%d]", setMini);
7806   /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
7807      about "AppleDockIconEnabled" notwithstanding, however the set message
7808      below has its effect nonetheless. */
7809   if (image != emacsframe->output_data.ns->miniimage)
7810     {
7811       if (image && [image isKindOfClass: [EmacsImage class]])
7812         [image release];
7813       [[self window] setMiniwindowImage:
7814                        setMini ? emacsframe->output_data.ns->miniimage : nil];
7815     }
7817   return self;
7821 - (void) setRows: (int) r andColumns: (int) c
7823   NSTRACE ("[EmacsView setRows:%d andColumns:%d]", r, c);
7824   rows = r;
7825   cols = c;
7828 - (int) fullscreenState
7830   return fs_state;
7833 @end  /* EmacsView */
7837 /* ==========================================================================
7839     EmacsWindow implementation
7841    ========================================================================== */
7843 @implementation EmacsWindow
7845 #ifdef NS_IMPL_COCOA
7846 - (id)accessibilityAttributeValue:(NSString *)attribute
7848   Lisp_Object str = Qnil;
7849   struct frame *f = SELECTED_FRAME ();
7850   struct buffer *curbuf = XBUFFER (XWINDOW (f->selected_window)->contents);
7852   NSTRACE ("[EmacsWindow accessibilityAttributeValue:]");
7854   if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
7855     return NSAccessibilityTextFieldRole;
7857   if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]
7858       && curbuf && ! NILP (BVAR (curbuf, mark_active)))
7859     {
7860       str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7861     }
7862   else if (curbuf && [attribute isEqualToString:NSAccessibilityValueAttribute])
7863     {
7864       if (! NILP (BVAR (curbuf, mark_active)))
7865           str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7867       if (NILP (str))
7868         {
7869           ptrdiff_t start_byte = BUF_BEGV_BYTE (curbuf);
7870           ptrdiff_t byte_range = BUF_ZV_BYTE (curbuf) - start_byte;
7871           ptrdiff_t range = BUF_ZV (curbuf) - BUF_BEGV (curbuf);
7873           if (! NILP (BVAR (curbuf, enable_multibyte_characters)))
7874             str = make_uninit_multibyte_string (range, byte_range);
7875           else
7876             str = make_uninit_string (range);
7877           /* To check: This returns emacs-utf-8, which is a superset of utf-8.
7878              Is this a problem?  */
7879           memcpy (SDATA (str), BYTE_POS_ADDR (start_byte), byte_range);
7880         }
7881     }
7884   if (! NILP (str))
7885     {
7886       if (CONSP (str) && SYMBOLP (XCAR (str)))
7887         {
7888           str = XCDR (str);
7889           if (CONSP (str) && NILP (XCDR (str)))
7890             str = XCAR (str);
7891         }
7892       if (STRINGP (str))
7893         {
7894           const char *utfStr = SSDATA (str);
7895           NSString *nsStr = [NSString stringWithUTF8String: utfStr];
7896           return nsStr;
7897         }
7898     }
7900   return [super accessibilityAttributeValue:attribute];
7902 #endif /* NS_IMPL_COCOA */
7904 /* Constrain size and placement of a frame.
7906    By returning the original "frameRect", the frame is not
7907    constrained. This can lead to unwanted situations where, for
7908    example, the menu bar covers the frame.
7910    The default implementation (accessed using "super") constrains the
7911    frame to the visible area of SCREEN, minus the menu bar (if
7912    present) and the Dock.  Note that default implementation also calls
7913    windowWillResize, with the frame it thinks should have.  (This can
7914    make the frame exit maximized mode.)
7916    Note that this should work in situations where multiple monitors
7917    are present.  Common configurations are side-by-side monitors and a
7918    monitor on top of another (e.g. when a laptop is placed under a
7919    large screen). */
7920 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
7922   NSTRACE ("[EmacsWindow constrainFrameRect:" NSTRACE_FMT_RECT " toScreen:]",
7923              NSTRACE_ARG_RECT (frameRect));
7925 #ifdef NS_IMPL_COCOA
7926 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7927   // If separate spaces is on, it is like each screen is independent.  There is
7928   // no spanning of frames across screens.
7929   if ([NSScreen screensHaveSeparateSpaces])
7930     {
7931       NSTRACE_MSG ("Screens have separate spaces");
7932       frameRect = [super constrainFrameRect:frameRect toScreen:screen];
7933       NSTRACE_RETURN_RECT (frameRect);
7934       return frameRect;
7935     }
7936 #endif
7937 #endif
7939   return constrain_frame_rect(frameRect,
7940                               [(EmacsView *)[self delegate] isFullscreen]);
7944 - (void)performZoom:(id)sender
7946   NSTRACE ("[EmacsWindow performZoom:]");
7948   return [super performZoom:sender];
7951 - (void)zoom:(id)sender
7953   NSTRACE ("[EmacsWindow zoom:]");
7955   ns_update_auto_hide_menu_bar();
7957   // Below are three zoom implementations.  In the final commit, the
7958   // idea is that the last should be included.
7960 #if 0
7961   // Native zoom done using the standard zoom animation.  Size of the
7962   // resulting frame reduced to accommodate the Dock and, if present,
7963   // the menu-bar.
7964   [super zoom:sender];
7966 #elif 0
7967   // Native zoom done using the standard zoom animation, plus an
7968   // explicit resize to cover the full screen, except the menu-bar and
7969   // dock, if present.
7970   [super zoom:sender];
7972   // After the native zoom, resize the resulting frame to fill the
7973   // entire screen, except the menu-bar.
7974   //
7975   // This works for all practical purposes.  (The only minor oddity is
7976   // when transiting from full-height frame to a maximized, the
7977   // animation reduces the height of the frame slightly (to the 4
7978   // pixels needed to accommodate the Doc) before it snaps back into
7979   // full height.  The user would need a very trained eye to spot
7980   // this.)
7981   NSScreen * screen = [self screen];
7982   if (screen != nil)
7983     {
7984       int fs_state = [(EmacsView *)[self delegate] fullscreenState];
7986       NSTRACE_FSTYPE ("fullscreenState", fs_state);
7988       NSRect sr = [screen frame];
7989       struct EmacsMargins margins
7990         = ns_screen_margins_ignoring_hidden_dock(screen);
7992       NSRect wr = [self frame];
7993       NSTRACE_RECT ("Rect after zoom", wr);
7995       NSRect newWr = wr;
7997       if (fs_state == FULLSCREEN_MAXIMIZED
7998           || fs_state == FULLSCREEN_HEIGHT)
7999         {
8000           newWr.origin.y = sr.origin.y + margins.bottom;
8001           newWr.size.height = sr.size.height - margins.top - margins.bottom;
8002         }
8004       if (fs_state == FULLSCREEN_MAXIMIZED
8005           || fs_state == FULLSCREEN_WIDTH)
8006         {
8007           newWr.origin.x = sr.origin.x + margins.left;
8008           newWr.size.width = sr.size.width - margins.right - margins.left;
8009         }
8011       if (newWr.size.width     != wr.size.width
8012           || newWr.size.height != wr.size.height
8013           || newWr.origin.x    != wr.origin.x
8014           || newWr.origin.y    != wr.origin.y)
8015         {
8016           NSTRACE_MSG ("New frame different");
8017           [self setFrame: newWr display: NO];
8018         }
8019     }
8020 #else
8021   // Non-native zoom which is done instantaneously.  The resulting
8022   // frame covers the entire screen, except the menu-bar and dock, if
8023   // present.
8024   NSScreen * screen = [self screen];
8025   if (screen != nil)
8026     {
8027       NSRect sr = [screen frame];
8028       struct EmacsMargins margins
8029         = ns_screen_margins_ignoring_hidden_dock(screen);
8031       sr.size.height -= (margins.top + margins.bottom);
8032       sr.size.width  -= (margins.left + margins.right);
8033       sr.origin.x += margins.left;
8034       sr.origin.y += margins.bottom;
8036       sr = [[self delegate] windowWillUseStandardFrame:self
8037                                           defaultFrame:sr];
8038       [self setFrame: sr display: NO];
8039     }
8040 #endif
8043 - (void)setFrame:(NSRect)windowFrame
8044          display:(BOOL)displayViews
8046   NSTRACE ("[EmacsWindow setFrame:" NSTRACE_FMT_RECT " display:%d]",
8047            NSTRACE_ARG_RECT (windowFrame), displayViews);
8049   [super setFrame:windowFrame display:displayViews];
8052 - (void)setFrame:(NSRect)windowFrame
8053          display:(BOOL)displayViews
8054          animate:(BOOL)performAnimation
8056   NSTRACE ("[EmacsWindow setFrame:" NSTRACE_FMT_RECT
8057            " display:%d performAnimation:%d]",
8058            NSTRACE_ARG_RECT (windowFrame), displayViews, performAnimation);
8060   [super setFrame:windowFrame display:displayViews animate:performAnimation];
8063 - (void)setFrameTopLeftPoint:(NSPoint)point
8065   NSTRACE ("[EmacsWindow setFrameTopLeftPoint:" NSTRACE_FMT_POINT "]",
8066            NSTRACE_ARG_POINT (point));
8068   [super setFrameTopLeftPoint:point];
8070 @end /* EmacsWindow */
8073 @implementation EmacsFSWindow
8075 - (BOOL)canBecomeKeyWindow
8077   return YES;
8080 - (BOOL)canBecomeMainWindow
8082   return YES;
8085 @end
8087 /* ==========================================================================
8089     EmacsScroller implementation
8091    ========================================================================== */
8094 @implementation EmacsScroller
8096 /* for repeat button push */
8097 #define SCROLL_BAR_FIRST_DELAY 0.5
8098 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
8100 + (CGFloat) scrollerWidth
8102   /* TODO: if we want to allow variable widths, this is the place to do it,
8103            however neither GNUstep nor Cocoa support it very well */
8104   CGFloat r;
8105 #if !defined (NS_IMPL_COCOA) || \
8106   MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
8107   r = [NSScroller scrollerWidth];
8108 #else
8109   r = [NSScroller scrollerWidthForControlSize: NSRegularControlSize
8110                                 scrollerStyle: NSScrollerStyleLegacy];
8111 #endif
8112   return r;
8116 - initFrame: (NSRect )r window: (Lisp_Object)nwin
8118   NSTRACE ("[EmacsScroller initFrame: window:]");
8120   r.size.width = [EmacsScroller scrollerWidth];
8121   [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
8122   [self setContinuous: YES];
8123   [self setEnabled: YES];
8125   /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
8126      locked against the top and bottom edges, and right edge on macOS, where
8127      scrollers are on right. */
8128 #ifdef NS_IMPL_GNUSTEP
8129   [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
8130 #else
8131   [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
8132 #endif
8134   window = XWINDOW (nwin);
8135   condemned = NO;
8136   pixel_height = NSHeight (r);
8137   if (pixel_height == 0) pixel_height = 1;
8138   min_portion = 20 / pixel_height;
8140   frame = XFRAME (window->frame);
8141   if (FRAME_LIVE_P (frame))
8142     {
8143       int i;
8144       EmacsView *view = FRAME_NS_VIEW (frame);
8145       NSView *sview = [[view window] contentView];
8146       NSArray *subs = [sview subviews];
8148       /* disable optimization stopping redraw of other scrollbars */
8149       view->scrollbarsNeedingUpdate = 0;
8150       for (i =[subs count]-1; i >= 0; i--)
8151         if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
8152           view->scrollbarsNeedingUpdate++;
8153       [sview addSubview: self];
8154     }
8156 /*  [self setFrame: r]; */
8158   return self;
8162 - (void)setFrame: (NSRect)newRect
8164   NSTRACE ("[EmacsScroller setFrame:]");
8166 /*  block_input (); */
8167   pixel_height = NSHeight (newRect);
8168   if (pixel_height == 0) pixel_height = 1;
8169   min_portion = 20 / pixel_height;
8170   [super setFrame: newRect];
8171 /*  unblock_input (); */
8175 - (void)dealloc
8177   NSTRACE ("[EmacsScroller dealloc]");
8178   if (window)
8179     wset_vertical_scroll_bar (window, Qnil);
8180   window = 0;
8181   [super dealloc];
8185 - condemn
8187   NSTRACE ("[EmacsScroller condemn]");
8188   condemned =YES;
8189   return self;
8193 - reprieve
8195   NSTRACE ("[EmacsScroller reprieve]");
8196   condemned =NO;
8197   return self;
8201 -(bool)judge
8203   NSTRACE ("[EmacsScroller judge]");
8204   bool ret = condemned;
8205   if (condemned)
8206     {
8207       EmacsView *view;
8208       block_input ();
8209       /* ensure other scrollbar updates after deletion */
8210       view = (EmacsView *)FRAME_NS_VIEW (frame);
8211       if (view != nil)
8212         view->scrollbarsNeedingUpdate++;
8213       if (window)
8214         wset_vertical_scroll_bar (window, Qnil);
8215       window = 0;
8216       [self removeFromSuperview];
8217       [self release];
8218       unblock_input ();
8219     }
8220   return ret;
8224 - (void)resetCursorRects
8226   NSRect visible = [self visibleRect];
8227   NSTRACE ("[EmacsScroller resetCursorRects]");
8229   if (!NSIsEmptyRect (visible))
8230     [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
8231   [[NSCursor arrowCursor] setOnMouseEntered: YES];
8235 - (int) checkSamePosition: (int) position portion: (int) portion
8236                     whole: (int) whole
8238   return em_position ==position && em_portion ==portion && em_whole ==whole
8239     && portion != whole; /* needed for resize empty buf */
8243 - setPosition: (int)position portion: (int)portion whole: (int)whole
8245   NSTRACE ("[EmacsScroller setPosition:portion:whole:]");
8247   em_position = position;
8248   em_portion = portion;
8249   em_whole = whole;
8251   if (portion >= whole)
8252     {
8253 #ifdef NS_IMPL_COCOA
8254       [self setKnobProportion: 1.0];
8255       [self setDoubleValue: 1.0];
8256 #else
8257       [self setFloatValue: 0.0 knobProportion: 1.0];
8258 #endif
8259     }
8260   else
8261     {
8262       float pos;
8263       CGFloat por;
8264       portion = max ((float)whole*min_portion/pixel_height, portion);
8265       pos = (float)position / (whole - portion);
8266       por = (CGFloat)portion/whole;
8267 #ifdef NS_IMPL_COCOA
8268       [self setKnobProportion: por];
8269       [self setDoubleValue: pos];
8270 #else
8271       [self setFloatValue: pos knobProportion: por];
8272 #endif
8273     }
8275   return self;
8278 /* set up emacs_event */
8279 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
8281   Lisp_Object win;
8283   NSTRACE ("[EmacsScroller sendScrollEventAtLoc:fromEvent:]");
8285   if (!emacs_event)
8286     return;
8288   emacs_event->part = last_hit_part;
8289   emacs_event->code = 0;
8290   emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
8291   XSETWINDOW (win, window);
8292   emacs_event->frame_or_window = win;
8293   emacs_event->timestamp = EV_TIMESTAMP (e);
8294   emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
8295   emacs_event->arg = Qnil;
8296   XSETINT (emacs_event->x, loc * pixel_height);
8297   XSETINT (emacs_event->y, pixel_height-20);
8299   if (q_event_ptr)
8300     {
8301       n_emacs_events_pending++;
8302       kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
8303     }
8304   else
8305     hold_event (emacs_event);
8306   EVENT_INIT (*emacs_event);
8307   ns_send_appdefined (-1);
8311 /* called manually thru timer to implement repeated button action w/hold-down */
8312 - repeatScroll: (NSTimer *)scrollEntry
8314   NSEvent *e = [[self window] currentEvent];
8315   NSPoint p =  [[self window] mouseLocationOutsideOfEventStream];
8316   BOOL inKnob = [self testPart: p] == NSScrollerKnob;
8318   NSTRACE ("[EmacsScroller repeatScroll:]");
8320   /* clear timer if need be */
8321   if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
8322     {
8323         [scroll_repeat_entry invalidate];
8324         [scroll_repeat_entry release];
8325         scroll_repeat_entry = nil;
8327         if (inKnob)
8328           return self;
8330         scroll_repeat_entry
8331           = [[NSTimer scheduledTimerWithTimeInterval:
8332                         SCROLL_BAR_CONTINUOUS_DELAY
8333                                             target: self
8334                                           selector: @selector (repeatScroll:)
8335                                           userInfo: 0
8336                                            repeats: YES]
8337               retain];
8338     }
8340   [self sendScrollEventAtLoc: 0 fromEvent: e];
8341   return self;
8345 /* Asynchronous mouse tracking for scroller.  This allows us to dispatch
8346    mouseDragged events without going into a modal loop. */
8347 - (void)mouseDown: (NSEvent *)e
8349   NSRect sr, kr;
8350   /* hitPart is only updated AFTER event is passed on */
8351   NSScrollerPart part = [self testPart: [e locationInWindow]];
8352   CGFloat inc = 0.0, loc, kloc, pos;
8353   int edge = 0;
8355   NSTRACE ("[EmacsScroller mouseDown:]");
8357   switch (part)
8358     {
8359     case NSScrollerDecrementPage:
8360         last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
8361     case NSScrollerIncrementPage:
8362         last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
8363     case NSScrollerDecrementLine:
8364       last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
8365     case NSScrollerIncrementLine:
8366       last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
8367     case NSScrollerKnob:
8368       last_hit_part = scroll_bar_handle; break;
8369     case NSScrollerKnobSlot:  /* GNUstep-only */
8370       last_hit_part = scroll_bar_move_ratio; break;
8371     default:  /* NSScrollerNoPart? */
8372       fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
8373                (long) part);
8374       return;
8375     }
8377   if (inc != 0.0)
8378     {
8379       pos = 0;      /* ignored */
8381       /* set a timer to repeat, as we can't let superclass do this modally */
8382       scroll_repeat_entry
8383         = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
8384                                             target: self
8385                                           selector: @selector (repeatScroll:)
8386                                           userInfo: 0
8387                                            repeats: YES]
8388             retain];
8389     }
8390   else
8391     {
8392       /* handle, or on GNUstep possibly slot */
8393       NSEvent *fake_event;
8395       /* compute float loc in slot and mouse offset on knob */
8396       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
8397                       toView: nil];
8398       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
8399       if (loc <= 0.0)
8400         {
8401           loc = 0.0;
8402           edge = -1;
8403         }
8404       else if (loc >= NSHeight (sr))
8405         {
8406           loc = NSHeight (sr);
8407           edge = 1;
8408         }
8410       if (edge)
8411         kloc = 0.5 * edge;
8412       else
8413         {
8414           kr = [self convertRect: [self rectForPart: NSScrollerKnob]
8415                           toView: nil];
8416           kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
8417         }
8418       last_mouse_offset = kloc;
8420       /* if knob, tell emacs a location offset by knob pos
8421          (to indicate top of handle) */
8422       if (part == NSScrollerKnob)
8423           pos = (loc - last_mouse_offset) / NSHeight (sr);
8424       else
8425         /* else this is a slot click on GNUstep: go straight there */
8426         pos = loc / NSHeight (sr);
8428       /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
8429       fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
8430                                       location: [e locationInWindow]
8431                                  modifierFlags: [e modifierFlags]
8432                                      timestamp: [e timestamp]
8433                                   windowNumber: [e windowNumber]
8434                                        context: [e context]
8435                                    eventNumber: [e eventNumber]
8436                                     clickCount: [e clickCount]
8437                                       pressure: [e pressure]];
8438       [super mouseUp: fake_event];
8439     }
8441   if (part != NSScrollerKnob)
8442     [self sendScrollEventAtLoc: pos fromEvent: e];
8446 /* Called as we manually track scroller drags, rather than superclass. */
8447 - (void)mouseDragged: (NSEvent *)e
8449     NSRect sr;
8450     double loc, pos;
8452     NSTRACE ("[EmacsScroller mouseDragged:]");
8454       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
8455                       toView: nil];
8456       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
8458       if (loc <= 0.0)
8459         {
8460           loc = 0.0;
8461         }
8462       else if (loc >= NSHeight (sr) + last_mouse_offset)
8463         {
8464           loc = NSHeight (sr) + last_mouse_offset;
8465         }
8467       pos = (loc - last_mouse_offset) / NSHeight (sr);
8468       [self sendScrollEventAtLoc: pos fromEvent: e];
8472 - (void)mouseUp: (NSEvent *)e
8474   NSTRACE ("[EmacsScroller mouseUp:]");
8476   if (scroll_repeat_entry)
8477     {
8478       [scroll_repeat_entry invalidate];
8479       [scroll_repeat_entry release];
8480       scroll_repeat_entry = nil;
8481     }
8482   last_hit_part = scroll_bar_above_handle;
8486 /* treat scrollwheel events in the bar as though they were in the main window */
8487 - (void) scrollWheel: (NSEvent *)theEvent
8489   NSTRACE ("[EmacsScroller scrollWheel:]");
8491   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
8492   [view mouseDown: theEvent];
8495 @end  /* EmacsScroller */
8498 #ifdef NS_IMPL_GNUSTEP
8499 /* Dummy class to get rid of startup warnings.  */
8500 @implementation EmacsDocument
8502 @end
8503 #endif
8506 /* ==========================================================================
8508    Font-related functions; these used to be in nsfaces.m
8510    ========================================================================== */
8513 Lisp_Object
8514 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
8516   struct font *font = XFONT_OBJECT (font_object);
8517   EmacsView *view = FRAME_NS_VIEW (f);
8518   int font_ascent, font_descent;
8520   if (fontset < 0)
8521     fontset = fontset_from_font (font_object);
8522   FRAME_FONTSET (f) = fontset;
8524   if (FRAME_FONT (f) == font)
8525     /* This font is already set in frame F.  There's nothing more to
8526        do.  */
8527     return font_object;
8529   FRAME_FONT (f) = font;
8531   FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
8532   FRAME_COLUMN_WIDTH (f) = font->average_width;
8533   get_font_ascent_descent (font, &font_ascent, &font_descent);
8534   FRAME_LINE_HEIGHT (f) = font_ascent + font_descent;
8536   /* Compute the scroll bar width in character columns.  */
8537   if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
8538     {
8539       int wid = FRAME_COLUMN_WIDTH (f);
8540       FRAME_CONFIG_SCROLL_BAR_COLS (f)
8541         = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
8542     }
8543   else
8544     {
8545       int wid = FRAME_COLUMN_WIDTH (f);
8546       FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
8547     }
8549   /* Compute the scroll bar height in character lines.  */
8550   if (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) > 0)
8551     {
8552       int height = FRAME_LINE_HEIGHT (f);
8553       FRAME_CONFIG_SCROLL_BAR_LINES (f)
8554         = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + height - 1) / height;
8555     }
8556   else
8557     {
8558       int height = FRAME_LINE_HEIGHT (f);
8559       FRAME_CONFIG_SCROLL_BAR_LINES (f) = (14 + height - 1) / height;
8560     }
8562   /* Now make the frame display the given font.  */
8563   if (FRAME_NS_WINDOW (f) != 0 && ! [view isFullscreen])
8564     adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
8565                        FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 3,
8566                        false, Qfont);
8568   return font_object;
8572 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
8573 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
8574          in 1.43. */
8576 const char *
8577 ns_xlfd_to_fontname (const char *xlfd)
8578 /* --------------------------------------------------------------------------
8579     Convert an X font name (XLFD) to an NS font name.
8580     Only family is used.
8581     The string returned is temporarily allocated.
8582    -------------------------------------------------------------------------- */
8584   char *name = xmalloc (180);
8585   int i, len;
8586   const char *ret;
8588   if (!strncmp (xlfd, "--", 2))
8589     sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
8590   else
8591     sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
8593   /* stopgap for malformed XLFD input */
8594   if (strlen (name) == 0)
8595     strcpy (name, "Monaco");
8597   /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
8598      also uppercase after '-' or ' ' */
8599   name[0] = c_toupper (name[0]);
8600   for (len =strlen (name), i =0; i<len; i++)
8601     {
8602       if (name[i] == '$')
8603         {
8604           name[i] = '-';
8605           if (i+1<len)
8606             name[i+1] = c_toupper (name[i+1]);
8607         }
8608       else if (name[i] == '_')
8609         {
8610           name[i] = ' ';
8611           if (i+1<len)
8612             name[i+1] = c_toupper (name[i+1]);
8613         }
8614     }
8615 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name);  */
8616   ret = [[NSString stringWithUTF8String: name] UTF8String];
8617   xfree (name);
8618   return ret;
8622 void
8623 syms_of_nsterm (void)
8625   NSTRACE ("syms_of_nsterm");
8627   ns_antialias_threshold = 10.0;
8629   /* from 23+ we need to tell emacs what modifiers there are.. */
8630   DEFSYM (Qmodifier_value, "modifier-value");
8631   DEFSYM (Qalt, "alt");
8632   DEFSYM (Qhyper, "hyper");
8633   DEFSYM (Qmeta, "meta");
8634   DEFSYM (Qsuper, "super");
8635   DEFSYM (Qcontrol, "control");
8636   DEFSYM (QUTF8_STRING, "UTF8_STRING");
8638   DEFSYM (Qfile, "file");
8639   DEFSYM (Qurl, "url");
8641   Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
8642   Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
8643   Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
8644   Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
8645   Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
8647   DEFVAR_LISP ("ns-input-file", ns_input_file,
8648               "The file specified in the last NS event.");
8649   ns_input_file =Qnil;
8651   DEFVAR_LISP ("ns-working-text", ns_working_text,
8652               "String for visualizing working composition sequence.");
8653   ns_working_text =Qnil;
8655   DEFVAR_LISP ("ns-input-font", ns_input_font,
8656               "The font specified in the last NS event.");
8657   ns_input_font =Qnil;
8659   DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
8660               "The fontsize specified in the last NS event.");
8661   ns_input_fontsize =Qnil;
8663   DEFVAR_LISP ("ns-input-line", ns_input_line,
8664                "The line specified in the last NS event.");
8665   ns_input_line =Qnil;
8667   DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
8668                "The service name specified in the last NS event.");
8669   ns_input_spi_name =Qnil;
8671   DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
8672                "The service argument specified in the last NS event.");
8673   ns_input_spi_arg =Qnil;
8675   DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
8676                "This variable describes the behavior of the alternate or option key.\n\
8677 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8678 Set to none means that the alternate / option key is not interpreted by Emacs\n\
8679 at all, allowing it to be used at a lower level for accented character entry.");
8680   ns_alternate_modifier = Qmeta;
8682   DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
8683                "This variable describes the behavior of the right alternate or option key.\n\
8684 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8685 Set to left means be the same key as `ns-alternate-modifier'.\n\
8686 Set to none means that the alternate / option key is not interpreted by Emacs\n\
8687 at all, allowing it to be used at a lower level for accented character entry.");
8688   ns_right_alternate_modifier = Qleft;
8690   DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
8691                "This variable describes the behavior of the command key.\n\
8692 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
8693   ns_command_modifier = Qsuper;
8695   DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
8696                "This variable describes the behavior of the right command key.\n\
8697 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8698 Set to left means be the same key as `ns-command-modifier'.\n\
8699 Set to none means that the command / option key is not interpreted by Emacs\n\
8700 at all, allowing it to be used at a lower level for accented character entry.");
8701   ns_right_command_modifier = Qleft;
8703   DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
8704                "This variable describes the behavior of the control key.\n\
8705 Set to control, meta, alt, super, or hyper means it is taken to be 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 control, meta, alt, super, or hyper means it is taken to be that key.\n\
8711 Set to left means be the same key as `ns-control-modifier'.\n\
8712 Set to none means that the control / option key is not interpreted by Emacs\n\
8713 at all, allowing it to be used at a lower level for accented character entry.");
8714   ns_right_control_modifier = Qleft;
8716   DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
8717                "This variable describes the behavior of the function key (on laptops).\n\
8718 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8719 Set to none means that the function key is not interpreted by Emacs at all,\n\
8720 allowing it to be used at a lower level for accented character entry.");
8721   ns_function_modifier = Qnone;
8723   DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
8724                "Non-nil (the default) means to render text antialiased.");
8725   ns_antialias_text = Qt;
8727   DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
8728                "Whether to confirm application quit using dialog.");
8729   ns_confirm_quit = Qnil;
8731   DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
8732                doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
8733 Only works on Mac OS X 10.6 or later.  */);
8734   ns_auto_hide_menu_bar = Qnil;
8736   DEFVAR_BOOL ("ns-use-native-fullscreen", ns_use_native_fullscreen,
8737      doc: /*Non-nil means to use native fullscreen on Mac OS X 10.7 and later.
8738 Nil means use fullscreen the old (< 10.7) way.  The old way works better with
8739 multiple monitors, but lacks tool bar.  This variable is ignored on
8740 Mac OS X < 10.7.  Default is t for 10.7 and later, nil otherwise.  */);
8741 #ifdef HAVE_NATIVE_FS
8742   ns_use_native_fullscreen = YES;
8743 #else
8744   ns_use_native_fullscreen = NO;
8745 #endif
8746   ns_last_use_native_fullscreen = ns_use_native_fullscreen;
8748   DEFVAR_BOOL ("ns-use-fullscreen-animation", ns_use_fullscreen_animation,
8749      doc: /*Non-nil means use animation on non-native fullscreen.
8750 For native fullscreen, this does nothing.
8751 Default is nil.  */);
8752   ns_use_fullscreen_animation = NO;
8754   DEFVAR_BOOL ("ns-use-srgb-colorspace", ns_use_srgb_colorspace,
8755      doc: /*Non-nil means to use sRGB colorspace on Mac OS X 10.7 and later.
8756 Note that this does not apply to images.
8757 This variable is ignored on Mac OS X < 10.7 and GNUstep.  */);
8758   ns_use_srgb_colorspace = YES;
8760   /* TODO: move to common code */
8761   DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
8762                doc: /* Which toolkit scroll bars Emacs uses, if any.
8763 A value of nil means Emacs doesn't use toolkit scroll bars.
8764 With the X Window system, the value is a symbol describing the
8765 X toolkit.  Possible values are: gtk, motif, xaw, or xaw3d.
8766 With MS Windows or Nextstep, the value is t.  */);
8767   Vx_toolkit_scroll_bars = Qt;
8769   DEFVAR_BOOL ("x-use-underline-position-properties",
8770                x_use_underline_position_properties,
8771      doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
8772 A value of nil means ignore them.  If you encounter fonts with bogus
8773 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
8774 to 4.1, set this to nil. */);
8775   x_use_underline_position_properties = 0;
8777   DEFVAR_BOOL ("x-underline-at-descent-line",
8778                x_underline_at_descent_line,
8779      doc: /* Non-nil means to draw the underline at the same place as the descent line.
8780 A value of nil means to draw the underline according to the value of the
8781 variable `x-use-underline-position-properties', which is usually at the
8782 baseline level.  The default value is nil.  */);
8783   x_underline_at_descent_line = 0;
8785   /* Tell Emacs about this window system.  */
8786   Fprovide (Qns, Qnil);
8788   DEFSYM (Qcocoa, "cocoa");
8789   DEFSYM (Qgnustep, "gnustep");
8791 #ifdef NS_IMPL_COCOA
8792   Fprovide (Qcocoa, Qnil);
8793   syms_of_macfont ();
8794 #else
8795   Fprovide (Qgnustep, Qnil);
8796   syms_of_nsfont ();
8797 #endif