Do not use pure Xism x_wm_set_icon_position in non-X ports.
[emacs/old-mirror.git] / src / nsterm.m
blob7126ef56c5ee6fd9cba0fa6fde12da293833a788
1 /* NeXT/Open/GNUstep / MacOSX communication module.
3 Copyright (C) 1989, 1993-1994, 2005-2006, 2008-2013 Free Software
4 Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.  */
22 Originally by Carl Edman
23 Updated by Christian Limpach (chris@nice.ch)
24 OpenStep/Rhapsody port by Scott Bender (sbender@harmony-ds.com)
25 MacOSX/Aqua port by Christophe de Dinechin (descubes@earthlink.net)
26 GNUstep port and post-20 update by Adrian Robert (arobert@cogsci.ucsd.edu)
29 /* This should be the first include, as it may set up #defines affecting
30    interpretation of even the system includes. */
31 #include <config.h>
33 #include <fcntl.h>
34 #include <math.h>
35 #include <pthread.h>
36 #include <sys/types.h>
37 #include <time.h>
38 #include <signal.h>
39 #include <unistd.h>
41 #include <c-ctype.h>
42 #include <c-strcase.h>
43 #include <ftoastr.h>
45 #include "lisp.h"
46 #include "blockinput.h"
47 #include "sysselect.h"
48 #include "nsterm.h"
49 #include "systime.h"
50 #include "character.h"
51 #include "fontset.h"
52 #include "composite.h"
53 #include "ccl.h"
55 #include "termhooks.h"
56 #include "termchar.h"
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 /* call tracing */
68 #if 0
69 int term_trace_num = 0;
70 #define NSTRACE(x)        fprintf (stderr, "%s:%d: [%d] " #x "\n",         \
71                                 __FILE__, __LINE__, ++term_trace_num)
72 #else
73 #define NSTRACE(x)
74 #endif
76 extern NSString *NSMenuDidBeginTrackingNotification;
78 /* ==========================================================================
80     Local declarations
82    ========================================================================== */
84 /* Convert a symbol indexed with an NSxxx value to a value as defined
85    in keyboard.c (lispy_function_key). I hope this is a correct way
86    of doing things... */
87 static unsigned convert_ns_to_X_keysym[] =
89   NSHomeFunctionKey,            0x50,
90   NSLeftArrowFunctionKey,       0x51,
91   NSUpArrowFunctionKey,         0x52,
92   NSRightArrowFunctionKey,      0x53,
93   NSDownArrowFunctionKey,       0x54,
94   NSPageUpFunctionKey,          0x55,
95   NSPageDownFunctionKey,        0x56,
96   NSEndFunctionKey,             0x57,
97   NSBeginFunctionKey,           0x58,
98   NSSelectFunctionKey,          0x60,
99   NSPrintFunctionKey,           0x61,
100   NSClearLineFunctionKey,       0x0B,
101   NSExecuteFunctionKey,         0x62,
102   NSInsertFunctionKey,          0x63,
103   NSUndoFunctionKey,            0x65,
104   NSRedoFunctionKey,            0x66,
105   NSMenuFunctionKey,            0x67,
106   NSFindFunctionKey,            0x68,
107   NSHelpFunctionKey,            0x6A,
108   NSBreakFunctionKey,           0x6B,
110   NSF1FunctionKey,              0xBE,
111   NSF2FunctionKey,              0xBF,
112   NSF3FunctionKey,              0xC0,
113   NSF4FunctionKey,              0xC1,
114   NSF5FunctionKey,              0xC2,
115   NSF6FunctionKey,              0xC3,
116   NSF7FunctionKey,              0xC4,
117   NSF8FunctionKey,              0xC5,
118   NSF9FunctionKey,              0xC6,
119   NSF10FunctionKey,             0xC7,
120   NSF11FunctionKey,             0xC8,
121   NSF12FunctionKey,             0xC9,
122   NSF13FunctionKey,             0xCA,
123   NSF14FunctionKey,             0xCB,
124   NSF15FunctionKey,             0xCC,
125   NSF16FunctionKey,             0xCD,
126   NSF17FunctionKey,             0xCE,
127   NSF18FunctionKey,             0xCF,
128   NSF19FunctionKey,             0xD0,
129   NSF20FunctionKey,             0xD1,
130   NSF21FunctionKey,             0xD2,
131   NSF22FunctionKey,             0xD3,
132   NSF23FunctionKey,             0xD4,
133   NSF24FunctionKey,             0xD5,
135   NSBackspaceCharacter,         0x08,  /* 8: Not on some KBs. */
136   NSDeleteCharacter,            0xFF,  /* 127: Big 'delete' key upper right. */
137   NSDeleteFunctionKey,          0x9F,  /* 63272: Del forw key off main array. */
139   NSTabCharacter,               0x09,
140   0x19,                         0x09,  /* left tab->regular since pass shift */
141   NSCarriageReturnCharacter,    0x0D,
142   NSNewlineCharacter,           0x0D,
143   NSEnterCharacter,             0x8D,
145   0x41|NSNumericPadKeyMask,     0xAE,  /* KP_Decimal */
146   0x43|NSNumericPadKeyMask,     0xAA,  /* KP_Multiply */
147   0x45|NSNumericPadKeyMask,     0xAB,  /* KP_Add */
148   0x4B|NSNumericPadKeyMask,     0xAF,  /* KP_Divide */
149   0x4E|NSNumericPadKeyMask,     0xAD,  /* KP_Subtract */
150   0x51|NSNumericPadKeyMask,     0xBD,  /* KP_Equal */
151   0x52|NSNumericPadKeyMask,     0xB0,  /* KP_0 */
152   0x53|NSNumericPadKeyMask,     0xB1,  /* KP_1 */
153   0x54|NSNumericPadKeyMask,     0xB2,  /* KP_2 */
154   0x55|NSNumericPadKeyMask,     0xB3,  /* KP_3 */
155   0x56|NSNumericPadKeyMask,     0xB4,  /* KP_4 */
156   0x57|NSNumericPadKeyMask,     0xB5,  /* KP_5 */
157   0x58|NSNumericPadKeyMask,     0xB6,  /* KP_6 */
158   0x59|NSNumericPadKeyMask,     0xB7,  /* KP_7 */
159   0x5B|NSNumericPadKeyMask,     0xB8,  /* KP_8 */
160   0x5C|NSNumericPadKeyMask,     0xB9,  /* KP_9 */
162   0x1B,                         0x1B   /* escape */
165 static Lisp_Object Qmodifier_value;
166 Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper;
167 extern Lisp_Object Qcursor_color, Qcursor_type, Qns, Qleft;
169 static Lisp_Object QUTF8_STRING;
171 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
172    the maximum font size to NOT antialias.  On GNUstep there is currently
173    no way to control this behavior. */
174 float ns_antialias_threshold;
176 /* Used to pick up AppleHighlightColor on OS X */
177 NSString *ns_selection_color;
179 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
180 NSString *ns_app_name = @"Emacs";  /* default changed later */
182 /* Display variables */
183 struct ns_display_info *x_display_list; /* Chain of existing displays */
184 Lisp_Object ns_display_name_list;
185 long context_menu_value = 0;
187 /* display update */
188 NSPoint last_mouse_motion_position;
189 static NSRect last_mouse_glyph;
190 static Time last_mouse_movement_time = 0;
191 static Lisp_Object last_mouse_motion_frame;
192 static EmacsScroller *last_mouse_scroll_bar = nil;
193 static struct frame *ns_updating_frame;
194 static NSView *focus_view = NULL;
195 static int ns_window_num = 0;
196 #ifdef NS_IMPL_GNUSTEP
197 static NSRect uRect;
198 #endif
199 static BOOL gsaved = NO;
200 static BOOL ns_fake_keydown = NO;
201 int ns_tmp_flags; /* FIXME */
202 struct nsfont_info *ns_tmp_font; /* FIXME */
203 #ifdef NS_IMPL_COCOA
204 static BOOL ns_menu_bar_is_hidden = NO;
205 #endif
206 /*static int debug_lock = 0; */
208 /* event loop */
209 static BOOL send_appdefined = YES;
210 #define NO_APPDEFINED_DATA (-8)
211 static int last_appdefined_event_data = NO_APPDEFINED_DATA;
212 static NSTimer *timed_entry = 0;
213 static NSTimer *scroll_repeat_entry = nil;
214 static fd_set select_readfds, select_writefds;
215 enum { SELECT_HAVE_READ = 1, SELECT_HAVE_WRITE = 2, SELECT_HAVE_TMO = 4 };
216 static int select_nfds = 0, select_valid = 0;
217 static EMACS_TIME select_timeout = { 0, 0 };
218 static int selfds[2] = { -1, -1 };
219 static pthread_mutex_t select_mutex;
220 static int apploopnr = 0;
221 static NSAutoreleasePool *outerpool;
222 static struct input_event *emacs_event = NULL;
223 static struct input_event *q_event_ptr = NULL;
224 static int n_emacs_events_pending = 0;
225 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
226   *ns_pending_service_args;
227 static BOOL ns_do_open_file = NO;
228 static BOOL ns_last_use_native_fullscreen;
230 static struct {
231   struct input_event *q;
232   int nr, cap;
233 } hold_event_q = {
234   NULL, 0, 0
237 #ifdef NS_IMPL_COCOA
239  * State for pending menu activation:
240  * MENU_NONE     Normal state
241  * MENU_PENDING  A menu has been clicked on, but has been canceled so we can
242  *               run lisp to update the menu.
243  * MENU_OPENING  Menu is up to date, and the click event is redone so the menu
244  *               will open.
245  */
246 #define MENU_NONE 0
247 #define MENU_PENDING 1
248 #define MENU_OPENING 2
249 static int menu_will_open_state = MENU_NONE;
251 /* Saved position for menu click.  */
252 static CGPoint menu_mouse_point;
254 /* Title for the menu to open.  */
255 static char *menu_pending_title = 0;
256 #endif
258 /* Convert modifiers in a NeXTstep event to emacs style modifiers.  */
259 #define NS_FUNCTION_KEY_MASK 0x800000
260 #define NSLeftControlKeyMask    (0x000001 | NSControlKeyMask)
261 #define NSRightControlKeyMask   (0x002000 | NSControlKeyMask)
262 #define NSLeftCommandKeyMask    (0x000008 | NSCommandKeyMask)
263 #define NSRightCommandKeyMask   (0x000010 | NSCommandKeyMask)
264 #define NSLeftAlternateKeyMask  (0x000020 | NSAlternateKeyMask)
265 #define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
266 #define EV_MODIFIERS(e)                               \
267     ((([e modifierFlags] & NSHelpKeyMask) ?           \
268            hyper_modifier : 0)                        \
269      | (!EQ (ns_right_alternate_modifier, Qleft) && \
270         (([e modifierFlags] & NSRightAlternateKeyMask) \
271          == NSRightAlternateKeyMask) ? \
272            parse_solitary_modifier (ns_right_alternate_modifier) : 0) \
273      | (([e modifierFlags] & NSAlternateKeyMask) ?                 \
274            parse_solitary_modifier (ns_alternate_modifier) : 0)   \
275      | (([e modifierFlags] & NSShiftKeyMask) ?     \
276            shift_modifier : 0)                        \
277      | (!EQ (ns_right_control_modifier, Qleft) && \
278         (([e modifierFlags] & NSRightControlKeyMask) \
279          == NSRightControlKeyMask) ? \
280            parse_solitary_modifier (ns_right_control_modifier) : 0) \
281      | (([e modifierFlags] & NSControlKeyMask) ?      \
282            parse_solitary_modifier (ns_control_modifier) : 0)     \
283      | (([e modifierFlags] & NS_FUNCTION_KEY_MASK) ?  \
284            parse_solitary_modifier (ns_function_modifier) : 0)    \
285      | (!EQ (ns_right_command_modifier, Qleft) && \
286         (([e modifierFlags] & NSRightCommandKeyMask) \
287          == NSRightCommandKeyMask) ? \
288            parse_solitary_modifier (ns_right_command_modifier) : 0) \
289      | (([e modifierFlags] & NSCommandKeyMask) ?      \
290            parse_solitary_modifier (ns_command_modifier):0))
292 #define EV_UDMODIFIERS(e)                                      \
293     ((([e type] == NSLeftMouseDown) ? down_modifier : 0)       \
294      | (([e type] == NSRightMouseDown) ? down_modifier : 0)    \
295      | (([e type] == NSOtherMouseDown) ? down_modifier : 0)    \
296      | (([e type] == NSLeftMouseDragged) ? down_modifier : 0)  \
297      | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
298      | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
299      | (([e type] == NSLeftMouseUp)   ? up_modifier   : 0)     \
300      | (([e type] == NSRightMouseUp)   ? up_modifier   : 0)    \
301      | (([e type] == NSOtherMouseUp)   ? up_modifier   : 0))
303 #define EV_BUTTON(e)                                                         \
304     ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 :    \
305       (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
306      [e buttonNumber] - 1)
308 /* Convert the time field to a timestamp in milliseconds. */
309 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
311 /* This is a piece of code which is common to all the event handling
312    methods.  Maybe it should even be a function.  */
313 #define EV_TRAILER(e)                                                   \
314     {                                                                   \
315       XSETFRAME (emacs_event->frame_or_window, emacsframe);             \
316       if (e) emacs_event->timestamp = EV_TIMESTAMP (e);                 \
317       if (q_event_ptr)                                                  \
318         {                                                               \
319           n_emacs_events_pending++;                                     \
320           kbd_buffer_store_event_hold (emacs_event, q_event_ptr);       \
321         }                                                               \
322       else                                                              \
323         hold_event (emacs_event);                                       \
324       EVENT_INIT (*emacs_event);                                        \
325       ns_send_appdefined (-1);                                          \
326     }
328 /* TODO: get rid of need for these forward declarations */
329 static void ns_condemn_scroll_bars (struct frame *f);
330 static void ns_judge_scroll_bars (struct frame *f);
331 void x_set_frame_alpha (struct frame *f);
334 /* ==========================================================================
336     Utilities
338    ========================================================================== */
340 static void
341 hold_event (struct input_event *event)
343   if (hold_event_q.nr == hold_event_q.cap)
344     {
345       if (hold_event_q.cap == 0) hold_event_q.cap = 10;
346       else hold_event_q.cap *= 2;
347       hold_event_q.q = (struct input_event *)
348         xrealloc (hold_event_q.q, hold_event_q.cap * sizeof (*hold_event_q.q));
349     }
351   hold_event_q.q[hold_event_q.nr++] = *event;
352   /* Make sure ns_read_socket is called, i.e. we have input.  */
353   raise (SIGIO);
354   send_appdefined = YES;
357 static Lisp_Object
358 append2 (Lisp_Object list, Lisp_Object item)
359 /* --------------------------------------------------------------------------
360    Utility to append to a list
361    -------------------------------------------------------------------------- */
363   Lisp_Object array[2];
364   array[0] = list;
365   array[1] = list1 (item);
366   return Fnconc (2, &array[0]);
370 const char *
371 ns_etc_directory (void)
372 /* If running as a self-contained app bundle, return as a string the
373    filename of the etc directory, if present; else nil.  */
375   NSBundle *bundle = [NSBundle mainBundle];
376   NSString *resourceDir = [bundle resourcePath];
377   NSString *resourcePath;
378   NSFileManager *fileManager = [NSFileManager defaultManager];
379   BOOL isDir;
381   resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
382   if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
383     {
384       if (isDir) return [resourcePath UTF8String];
385     }
386   return NULL;
390 const char *
391 ns_exec_path (void)
392 /* If running as a self-contained app bundle, return as a path string
393    the filenames of the libexec and bin directories, ie libexec:bin.
394    Otherwise, return nil.
395    Normally, Emacs does not add its own bin/ directory to the PATH.
396    However, a self-contained NS build has a different layout, with
397    bin/ and libexec/ subdirectories in the directory that contains
398    Emacs.app itself.
399    We put libexec first, because init_callproc_1 uses the first
400    element to initialize exec-directory.  An alternative would be
401    for init_callproc to check for invocation-directory/libexec.
404   NSBundle *bundle = [NSBundle mainBundle];
405   NSString *resourceDir = [bundle resourcePath];
406   NSString *binDir = [bundle bundlePath];
407   NSString *resourcePath, *resourcePaths;
408   NSRange range;
409   NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
410   NSFileManager *fileManager = [NSFileManager defaultManager];
411   NSArray *paths;
412   NSEnumerator *pathEnum;
413   BOOL isDir;
415   range = [resourceDir rangeOfString: @"Contents"];
416   if (range.location != NSNotFound)
417     {
418       binDir = [binDir stringByAppendingPathComponent: @"Contents"];
419 #ifdef NS_IMPL_COCOA
420       binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
421 #endif
422     }
424   paths = [binDir stringsByAppendingPaths:
425                 [NSArray arrayWithObjects: @"libexec", @"bin", nil]];
426   pathEnum = [paths objectEnumerator];
427   resourcePaths = @"";
429   while ((resourcePath = [pathEnum nextObject]))
430     {
431       if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
432         if (isDir)
433           {
434             if ([resourcePaths length] > 0)
435               resourcePaths
436                 = [resourcePaths stringByAppendingString: pathSeparator];
437             resourcePaths
438               = [resourcePaths stringByAppendingString: resourcePath];
439           }
440     }
441   if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
443   return NULL;
447 const char *
448 ns_load_path (void)
449 /* If running as a self-contained app bundle, return as a path string
450    the filenames of the site-lisp, lisp and leim directories.
451    Ie, site-lisp:lisp:leim.  Otherwise, return nil.  */
453   NSBundle *bundle = [NSBundle mainBundle];
454   NSString *resourceDir = [bundle resourcePath];
455   NSString *resourcePath, *resourcePaths;
456   NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
457   NSFileManager *fileManager = [NSFileManager defaultManager];
458   BOOL isDir;
459   NSArray *paths = [resourceDir stringsByAppendingPaths:
460                               [NSArray arrayWithObjects:
461                                          @"site-lisp", @"lisp", @"leim", nil]];
462   NSEnumerator *pathEnum = [paths objectEnumerator];
463   resourcePaths = @"";
465   /* Hack to skip site-lisp.  */
466   if (no_site_lisp) resourcePath = [pathEnum nextObject];
468   while ((resourcePath = [pathEnum nextObject]))
469     {
470       if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
471         if (isDir)
472           {
473             if ([resourcePaths length] > 0)
474               resourcePaths
475                 = [resourcePaths stringByAppendingString: pathSeparator];
476             resourcePaths
477               = [resourcePaths stringByAppendingString: resourcePath];
478           }
479     }
480   if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
482   return NULL;
485 static void
486 ns_timeout (int usecs)
487 /* --------------------------------------------------------------------------
488      Blocking timer utility used by ns_ring_bell
489    -------------------------------------------------------------------------- */
491   EMACS_TIME wakeup = add_emacs_time (current_emacs_time (),
492                                       make_emacs_time (0, usecs * 1000));
494   /* Keep waiting until past the time wakeup.  */
495   while (1)
496     {
497       EMACS_TIME timeout, now = current_emacs_time ();
498       if (EMACS_TIME_LE (wakeup, now))
499         break;
500       timeout = sub_emacs_time (wakeup, now);
502       /* Try to wait that long--but we might wake up sooner.  */
503       pselect (0, NULL, NULL, NULL, &timeout, NULL);
504     }
508 void
509 ns_release_object (void *obj)
510 /* --------------------------------------------------------------------------
511     Release an object (callable from C)
512    -------------------------------------------------------------------------- */
514     [(id)obj release];
518 void
519 ns_retain_object (void *obj)
520 /* --------------------------------------------------------------------------
521     Retain an object (callable from C)
522    -------------------------------------------------------------------------- */
524     [(id)obj retain];
528 void *
529 ns_alloc_autorelease_pool (void)
530 /* --------------------------------------------------------------------------
531      Allocate a pool for temporary objects (callable from C)
532    -------------------------------------------------------------------------- */
534   return [[NSAutoreleasePool alloc] init];
538 void
539 ns_release_autorelease_pool (void *pool)
540 /* --------------------------------------------------------------------------
541      Free a pool and temporary objects it refers to (callable from C)
542    -------------------------------------------------------------------------- */
544   ns_release_object (pool);
549 /* ==========================================================================
551     Focus (clipping) and screen update
553    ========================================================================== */
556 // Window constraining
557 // -------------------
559 // To ensure that the windows are not placed under the menu bar, they
560 // are typically moved by the call-back constrainFrameRect. However,
561 // by overriding it, it's possible to inhibit this, leaving the window
562 // in it's original position.
564 // It's possible to hide the menu bar. However, technically, it's only
565 // possible to hide it when the application is active. To ensure that
566 // this work properly, the menu bar and window constraining are
567 // deferred until the application becomes active.
569 // Even though it's not possible to manually move a window above the
570 // top of the screen, it is allowed if it's done programmatically,
571 // when the menu is hidden. This allows the editable area to cover the
572 // full screen height.
574 // Test cases
575 // ----------
577 // Use the following extra files:
579 //    init.el:
580 //       ;; Hide menu and place frame slightly above the top of the screen.
581 //       (setq ns-auto-hide-menu-bar t)
582 //       (set-frame-position (selected-frame) 0 -20)
584 // Test 1:
586 //    emacs -Q -l init.el
588 //    Result: No menu bar, and the title bar should be above the screen.
590 // Test 2:
592 //    emacs -Q
594 //    Result: Menu bar visible, frame placed immediately below the menu.
597 static void
598 ns_constrain_all_frames (void)
600   Lisp_Object tail, frame;
602   FOR_EACH_FRAME (tail, frame)
603     {
604       struct frame *f = XFRAME (frame);
605       if (FRAME_NS_P (f))
606         {
607           NSView *view = FRAME_NS_VIEW (f);
608           /* This no-op will trigger the default window placing
609            * constraint system. */
610           f->output_data.ns->dont_constrain = 0;
611           [[view window] setFrameOrigin:[[view window] frame].origin];
612         }
613     }
617 /* True, if the menu bar should be hidden.  */
619 static BOOL
620 ns_menu_bar_should_be_hidden (void)
622   return !NILP (ns_auto_hide_menu_bar)
623     && [NSApp respondsToSelector:@selector(setPresentationOptions:)];
627 /* Show or hide the menu bar, based on user setting.  */
629 static void
630 ns_update_auto_hide_menu_bar (void)
632 #ifdef NS_IMPL_COCOA
633 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
634   block_input ();
636   NSTRACE (ns_update_auto_hide_menu_bar);
638   if (NSApp != nil
639       && [NSApp isActive]
640       && [NSApp respondsToSelector:@selector(setPresentationOptions:)])
641     {
642       // Note, "setPresentationOptions" triggers an error unless the
643       // application is active.
644       BOOL menu_bar_should_be_hidden = ns_menu_bar_should_be_hidden ();
646       if (menu_bar_should_be_hidden != ns_menu_bar_is_hidden)
647         {
648           NSApplicationPresentationOptions options
649             = NSApplicationPresentationAutoHideDock;
651           if (menu_bar_should_be_hidden)
652             options |= NSApplicationPresentationAutoHideMenuBar;
654           [NSApp setPresentationOptions: options];
656           ns_menu_bar_is_hidden = menu_bar_should_be_hidden;
658           if (!ns_menu_bar_is_hidden)
659             {
660               ns_constrain_all_frames ();
661             }
662         }
663     }
665   unblock_input ();
666 #endif
667 #endif
671 static void
672 ns_update_begin (struct frame *f)
673 /* --------------------------------------------------------------------------
674    Prepare for a grouped sequence of drawing calls
675    external (RIF) call; whole frame, called before update_window_begin
676    -------------------------------------------------------------------------- */
678   NSView *view = FRAME_NS_VIEW (f);
679   NSTRACE (ns_update_begin);
681   ns_update_auto_hide_menu_bar ();
683   ns_updating_frame = f;
684   [view lockFocus];
686   /* drawRect may have been called for say the minibuffer, and then clip path
687      is for the minibuffer.  But the display engine may draw more because
688      we have set the frame as garbaged.  So reset clip path to the whole
689      view.  */
690 #ifdef NS_IMPL_COCOA
691   {
692     NSBezierPath *bp;
693     NSRect r = [view frame];
694   bp = [[NSBezierPath bezierPathWithRect: r] retain];
695   [bp setClip];
696   [bp release];
697   }
698 #endif
700 #ifdef NS_IMPL_GNUSTEP
701   uRect = NSMakeRect (0, 0, 0, 0);
702 #endif
706 static void
707 ns_update_window_begin (struct window *w)
708 /* --------------------------------------------------------------------------
709    Prepare for a grouped sequence of drawing calls
710    external (RIF) call; for one window, called after update_begin
711    -------------------------------------------------------------------------- */
713   struct frame *f = XFRAME (WINDOW_FRAME (w));
714  Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
715   NSTRACE (ns_update_window_begin);
716   updated_window = w;
717   set_output_cursor (&w->cursor);
719   block_input ();
721   if (f == hlinfo->mouse_face_mouse_frame)
722     {
723       /* Don't do highlighting for mouse motion during the update.  */
724       hlinfo->mouse_face_defer = 1;
726         /* If the frame needs to be redrawn,
727            simply forget about any prior mouse highlighting.  */
728       if (FRAME_GARBAGED_P (f))
729         hlinfo->mouse_face_window = Qnil;
731       /* (further code for mouse faces ifdef'd out in other terms elided) */
732     }
734   unblock_input ();
738 static void
739 ns_update_window_end (struct window *w, int cursor_on_p,
740                       int mouse_face_overwritten_p)
741 /* --------------------------------------------------------------------------
742    Finished a grouped sequence of drawing calls
743    external (RIF) call; for one window called before update_end
744    -------------------------------------------------------------------------- */
746   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (XFRAME (w->frame));
748   /* note: this fn is nearly identical in all terms */
749   if (!w->pseudo_window_p)
750     {
751       block_input ();
753       if (cursor_on_p)
754         display_and_set_cursor (w, 1,
755                                 output_cursor.hpos, output_cursor.vpos,
756                                 output_cursor.x, output_cursor.y);
758       if (draw_window_fringes (w, 1))
759         x_draw_vertical_border (w);
761       unblock_input ();
762     }
764   /* If a row with mouse-face was overwritten, arrange for
765      frame_up_to_date to redisplay the mouse highlight.  */
766   if (mouse_face_overwritten_p)
767     {
768       hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
769       hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
770       hlinfo->mouse_face_window = Qnil;
771     }
773   updated_window = NULL;
774   NSTRACE (update_window_end);
778 static void
779 ns_update_end (struct frame *f)
780 /* --------------------------------------------------------------------------
781    Finished a grouped sequence of drawing calls
782    external (RIF) call; for whole frame, called after update_window_end
783    -------------------------------------------------------------------------- */
785   EmacsView *view = FRAME_NS_VIEW (f);
787 /*   if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
788     MOUSE_HL_INFO (f)->mouse_face_defer = 0;
790     block_input ();
792   [view unlockFocus];
793   [[view window] flushWindow];
795   unblock_input ();
796   ns_updating_frame = NULL;
797   NSTRACE (ns_update_end);
801 static void
802 ns_flush (struct frame *f)
803 /* --------------------------------------------------------------------------
804    external (RIF) call
805    NS impl is no-op since currently we flush in ns_update_end and elsewhere
806    -------------------------------------------------------------------------- */
808     NSTRACE (ns_flush);
812 static void
813 ns_focus (struct frame *f, NSRect *r, int n)
814 /* --------------------------------------------------------------------------
815    Internal: Focus on given frame.  During small local updates this is used to
816      draw, however during large updates, ns_update_begin and ns_update_end are
817      called to wrap the whole thing, in which case these calls are stubbed out.
818      Except, on GNUstep, we accumulate the rectangle being drawn into, because
819      the back end won't do this automatically, and will just end up flushing
820      the entire window.
821    -------------------------------------------------------------------------- */
823 //  NSTRACE (ns_focus);
824 /* static int c =0;
825    fprintf (stderr, "focus: %d", c++);
826    if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
827    fprintf (stderr, "\n"); */
829   if (f != ns_updating_frame)
830     {
831       NSView *view = FRAME_NS_VIEW (f);
832       if (view != focus_view)
833         {
834           if (focus_view != NULL)
835             {
836               [focus_view unlockFocus];
837               [[focus_view window] flushWindow];
838 /*debug_lock--; */
839             }
841           if (view)
842             [view lockFocus];
843           focus_view = view;
844 /*if (view) debug_lock++; */
845         }
846     }
848   /* clipping */
849   if (r)
850     {
851       [[NSGraphicsContext currentContext] saveGraphicsState];
852       if (n == 2)
853         NSRectClipList (r, 2);
854       else
855         NSRectClip (*r);
856       gsaved = YES;
857     }
861 static void
862 ns_unfocus (struct frame *f)
863 /* --------------------------------------------------------------------------
864      Internal: Remove focus on given frame
865    -------------------------------------------------------------------------- */
867 //  NSTRACE (ns_unfocus);
869   if (gsaved)
870     {
871       [[NSGraphicsContext currentContext] restoreGraphicsState];
872       gsaved = NO;
873     }
875   if (f != ns_updating_frame)
876     {
877       if (focus_view != NULL)
878         {
879           [focus_view unlockFocus];
880           [[focus_view window] flushWindow];
881           focus_view = NULL;
882 /*debug_lock--; */
883         }
884     }
888 static void
889 ns_clip_to_row (struct window *w, struct glyph_row *row, int area, BOOL gc)
890 /* --------------------------------------------------------------------------
891      Internal (but parallels other terms): Focus drawing on given row
892    -------------------------------------------------------------------------- */
894   struct frame *f = XFRAME (WINDOW_FRAME (w));
895   NSRect clip_rect;
896   int window_x, window_y, window_width;
898   window_box (w, area, &window_x, &window_y, &window_width, 0);
900   clip_rect.origin.x = window_x;
901   clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
902   clip_rect.origin.y = max (clip_rect.origin.y, window_y);
903   clip_rect.size.width = window_width;
904   clip_rect.size.height = row->visible_height;
906   ns_focus (f, &clip_rect, 1);
910 static void
911 ns_ring_bell (struct frame *f)
912 /* --------------------------------------------------------------------------
913      "Beep" routine
914    -------------------------------------------------------------------------- */
916   NSTRACE (ns_ring_bell);
917   if (visible_bell)
918     {
919       NSAutoreleasePool *pool;
920       struct frame *frame = SELECTED_FRAME ();
921       NSView *view;
923       block_input ();
924       pool = [[NSAutoreleasePool alloc] init];
926       view = FRAME_NS_VIEW (frame);
927       if (view != nil)
928         {
929           NSRect r, surr;
930           NSPoint dim = NSMakePoint (128, 128);
932           r = [view bounds];
933           r.origin.x += (r.size.width - dim.x) / 2;
934           r.origin.y += (r.size.height - dim.y) / 2;
935           r.size.width = dim.x;
936           r.size.height = dim.y;
937           surr = NSInsetRect (r, -2, -2);
938           ns_focus (frame, &surr, 1);
939           [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
940           [ns_lookup_indexed_color (NS_FACE_FOREGROUND
941                                       (FRAME_DEFAULT_FACE (frame)), frame) set];
942           NSRectFill (r);
943           [[view window] flushWindow];
944           ns_timeout (150000);
945           [[view window] restoreCachedImage];
946           [[view window] flushWindow];
947           ns_unfocus (frame);
948         }
949       [pool release];
950       unblock_input ();
951     }
952   else
953     {
954       NSBeep ();
955     }
959 static void
960 ns_reset_terminal_modes (struct terminal *terminal)
961 /*  Externally called as hook */
963   NSTRACE (ns_reset_terminal_modes);
967 static void
968 ns_set_terminal_modes (struct terminal *terminal)
969 /*  Externally called as hook */
971   NSTRACE (ns_set_terminal_modes);
976 /* ==========================================================================
978     Frame / window manager related functions
980    ========================================================================== */
983 static void
984 ns_raise_frame (struct frame *f)
985 /* --------------------------------------------------------------------------
986      Bring window to foreground and make it active
987    -------------------------------------------------------------------------- */
989   NSView *view;
990   check_window_system (f);
991   view = FRAME_NS_VIEW (f);
992   block_input ();
993   if (FRAME_VISIBLE_P (f))
994     [[view window] makeKeyAndOrderFront: NSApp];
995   unblock_input ();
999 static void
1000 ns_lower_frame (struct frame *f)
1001 /* --------------------------------------------------------------------------
1002      Send window to back
1003    -------------------------------------------------------------------------- */
1005   NSView *view;
1006   check_window_system (f);
1007   view = FRAME_NS_VIEW (f);
1008   block_input ();
1009   [[view window] orderBack: NSApp];
1010   unblock_input ();
1014 static void
1015 ns_frame_raise_lower (struct frame *f, int raise)
1016 /* --------------------------------------------------------------------------
1017      External (hook)
1018    -------------------------------------------------------------------------- */
1020   NSTRACE (ns_frame_raise_lower);
1022   if (raise)
1023     ns_raise_frame (f);
1024   else
1025     ns_lower_frame (f);
1029 static void
1030 ns_frame_rehighlight (struct frame *frame)
1031 /* --------------------------------------------------------------------------
1032      External (hook): called on things like window switching within frame
1033    -------------------------------------------------------------------------- */
1035   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
1036   struct frame *old_highlight = dpyinfo->x_highlight_frame;
1038   NSTRACE (ns_frame_rehighlight);
1039   if (dpyinfo->x_focus_frame)
1040     {
1041       dpyinfo->x_highlight_frame
1042         = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1043            ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1044            : dpyinfo->x_focus_frame);
1045       if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
1046         {
1047           fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
1048           dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
1049         }
1050     }
1051   else
1052       dpyinfo->x_highlight_frame = 0;
1054   if (dpyinfo->x_highlight_frame &&
1055          dpyinfo->x_highlight_frame != old_highlight)
1056     {
1057       if (old_highlight)
1058         {
1059           x_update_cursor (old_highlight, 1);
1060           x_set_frame_alpha (old_highlight);
1061         }
1062       if (dpyinfo->x_highlight_frame)
1063         {
1064           x_update_cursor (dpyinfo->x_highlight_frame, 1);
1065           x_set_frame_alpha (dpyinfo->x_highlight_frame);
1066         }
1067     }
1071 void
1072 x_make_frame_visible (struct frame *f)
1073 /* --------------------------------------------------------------------------
1074      External: Show the window (X11 semantics)
1075    -------------------------------------------------------------------------- */
1077   NSTRACE (x_make_frame_visible);
1078   /* XXX: at some points in past this was not needed, as the only place that
1079      called this (frame.c:Fraise_frame ()) also called raise_lower;
1080      if this ends up the case again, comment this out again. */
1081   if (!FRAME_VISIBLE_P (f))
1082     {
1083       EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1085       SET_FRAME_VISIBLE (f, 1);
1086       ns_raise_frame (f);
1088       /* Making a new frame from a fullscreen frame will make the new frame
1089          fullscreen also.  So skip handleFS as this will print an error.  */
1090       if ([view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH
1091           && [view isFullscreen])
1092         return;
1094       if (f->want_fullscreen != FULLSCREEN_NONE)
1095         {
1096           block_input ();
1097           [view handleFS];
1098           unblock_input ();
1099         }
1100     }
1104 void
1105 x_make_frame_invisible (struct frame *f)
1106 /* --------------------------------------------------------------------------
1107      External: Hide the window (X11 semantics)
1108    -------------------------------------------------------------------------- */
1110   NSView *view;
1111   NSTRACE (x_make_frame_invisible);
1112   check_window_system (f);
1113   view = FRAME_NS_VIEW (f);
1114   [[view window] orderOut: NSApp];
1115   SET_FRAME_VISIBLE (f, 0);
1116   SET_FRAME_ICONIFIED (f, 0);
1120 void
1121 x_iconify_frame (struct frame *f)
1122 /* --------------------------------------------------------------------------
1123      External: Iconify window
1124    -------------------------------------------------------------------------- */
1126   NSView *view;
1127   struct ns_display_info *dpyinfo;
1129   NSTRACE (x_iconify_frame);
1130   check_window_system (f);
1131   view = FRAME_NS_VIEW (f);
1132   dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1134   if (dpyinfo->x_highlight_frame == f)
1135     dpyinfo->x_highlight_frame = 0;
1137   if ([[view window] windowNumber] <= 0)
1138     {
1139       /* the window is still deferred.  Make it very small, bring it
1140          on screen and order it out. */
1141       NSRect s = { { 100, 100}, {0, 0} };
1142       NSRect t;
1143       t = [[view window] frame];
1144       [[view window] setFrame: s display: NO];
1145       [[view window] orderBack: NSApp];
1146       [[view window] orderOut: NSApp];
1147       [[view window] setFrame: t display: NO];
1148     }
1149   [[view window] miniaturize: NSApp];
1152 /* Free X resources of frame F.  */
1154 void
1155 x_free_frame_resources (struct frame *f)
1157   NSView *view;
1158   struct ns_display_info *dpyinfo;
1159   Mouse_HLInfo *hlinfo;
1161   NSTRACE (x_free_frame_resources);
1162   check_window_system (f);
1163   view = FRAME_NS_VIEW (f);
1164   dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1165   hlinfo = MOUSE_HL_INFO (f);
1167   [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1169   block_input ();
1171   free_frame_menubar (f);
1173   if (FRAME_FACE_CACHE (f))
1174     free_frame_faces (f);
1176   if (f == dpyinfo->x_focus_frame)
1177     dpyinfo->x_focus_frame = 0;
1178   if (f == dpyinfo->x_highlight_frame)
1179     dpyinfo->x_highlight_frame = 0;
1180   if (f == hlinfo->mouse_face_mouse_frame)
1181     {
1182       hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
1183       hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
1184       hlinfo->mouse_face_window = Qnil;
1185       hlinfo->mouse_face_mouse_frame = 0;
1186     }
1188   if (f->output_data.ns->miniimage != nil)
1189     [f->output_data.ns->miniimage release];
1191   [[view window] close];
1192   [view release];
1194   xfree (f->output_data.ns);
1196   unblock_input ();
1199 void
1200 x_destroy_window (struct frame *f)
1201 /* --------------------------------------------------------------------------
1202      External: Delete the window
1203    -------------------------------------------------------------------------- */
1205   NSTRACE (x_destroy_window);
1206   check_window_system (f);
1207   x_free_frame_resources (f);
1208   ns_window_num--;
1212 void
1213 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1214 /* --------------------------------------------------------------------------
1215      External: Position the window
1216    -------------------------------------------------------------------------- */
1218   NSView *view = FRAME_NS_VIEW (f);
1219   NSArray *screens = [NSScreen screens];
1220   NSScreen *fscreen = [screens objectAtIndex: 0];
1221   NSScreen *screen = [[view window] screen];
1223   NSTRACE (x_set_offset);
1225   block_input ();
1227   f->left_pos = xoff;
1228   f->top_pos = yoff;
1230   if (view != nil && screen && fscreen)
1231     {
1232       f->left_pos = f->size_hint_flags & XNegative
1233         ? [screen visibleFrame].size.width + f->left_pos - FRAME_PIXEL_WIDTH (f)
1234         : f->left_pos;
1235       /* We use visibleFrame here to take menu bar into account.
1236          Ideally we should also adjust left/top with visibleFrame.origin.  */
1238       f->top_pos = f->size_hint_flags & YNegative
1239         ? ([screen visibleFrame].size.height + f->top_pos
1240            - FRAME_PIXEL_HEIGHT (f) - FRAME_NS_TITLEBAR_HEIGHT (f)
1241            - FRAME_TOOLBAR_HEIGHT (f))
1242         : f->top_pos;
1243 #ifdef NS_IMPL_GNUSTEP
1244       if (f->left_pos < 100)
1245         f->left_pos = 100;  /* don't overlap menu */
1246 #endif
1247       /* Constrain the setFrameTopLeftPoint so we don't move behind the
1248          menu bar.  */
1249       f->output_data.ns->dont_constrain = 0;
1250       [[view window] setFrameTopLeftPoint:
1251                        NSMakePoint (SCREENMAXBOUND (f->left_pos),
1252                                     SCREENMAXBOUND ([fscreen frame].size.height
1253                                                     - NS_TOP_POS (f)))];
1254       f->size_hint_flags &= ~(XNegative|YNegative);
1255     }
1257   unblock_input ();
1261 void
1262 x_set_window_size (struct frame *f, int change_grav, int cols, int rows)
1263 /* --------------------------------------------------------------------------
1264      Adjust window pixel size based on given character grid size
1265      Impl is a bit more complex than other terms, need to do some
1266      internal clipping.
1267    -------------------------------------------------------------------------- */
1269   EmacsView *view = FRAME_NS_VIEW (f);
1270   NSWindow *window = [view window];
1271   NSRect wr = [window frame];
1272   int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1273   int pixelwidth, pixelheight;
1275   NSTRACE (x_set_window_size);
1277   if (view == nil)
1278     return;
1280 /*fprintf (stderr, "\tsetWindowSize: %d x %d, font size %d x %d\n", cols, rows, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f)); */
1282   block_input ();
1284   check_frame_size (f, &rows, &cols);
1286   f->scroll_bar_actual_width = NS_SCROLL_BAR_WIDTH (f);
1287   compute_fringe_widths (f, 0);
1289   pixelwidth =  FRAME_TEXT_COLS_TO_PIXEL_WIDTH   (f, cols);
1290   pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
1292   /* If we have a toolbar, take its height into account. */
1293   if (tb && ! [view isFullscreen])
1294     {
1295     /* NOTE: previously this would generate wrong result if toolbar not
1296              yet displayed and fixing toolbar_height=32 helped, but
1297              now (200903) seems no longer needed */
1298     FRAME_TOOLBAR_HEIGHT (f) =
1299       NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1300         - FRAME_NS_TITLEBAR_HEIGHT (f);
1301 #ifdef NS_IMPL_GNUSTEP
1302       FRAME_TOOLBAR_HEIGHT (f) -= 3;
1303 #endif
1304     }
1305   else
1306     FRAME_TOOLBAR_HEIGHT (f) = 0;
1308   wr.size.width = pixelwidth + f->border_width;
1309   wr.size.height = pixelheight;
1310   if (! [view isFullscreen])
1311     wr.size.height += FRAME_NS_TITLEBAR_HEIGHT (f)
1312       + FRAME_TOOLBAR_HEIGHT (f);
1314   /* Do not try to constrain to this screen.  We may have multiple
1315      screens, and want Emacs to span those.  Constraining to screen
1316      prevents that, and that is not nice to the user.  */
1317  if (f->output_data.ns->zooming)
1318    f->output_data.ns->zooming = 0;
1319  else
1320    wr.origin.y += FRAME_PIXEL_HEIGHT (f) - pixelheight;
1322   [view setRows: rows andColumns: cols];
1323   [window setFrame: wr display: YES];
1325 /*fprintf (stderr, "\tx_set_window_size %d, %d\t%d, %d\n", cols, rows, pixelwidth, pixelheight); */
1327   /* This is a trick to compensate for Emacs' managing the scrollbar area
1328      as a fixed number of standard character columns.  Instead of leaving
1329      blank space for the extra, we chopped it off above.  Now for
1330      left-hand scrollbars, we shift all rendering to the left by the
1331      difference between the real width and Emacs' imagined one.  For
1332      right-hand bars, don't worry about it since the extra is never used.
1333      (Obviously doesn't work for vertically split windows tho..) */
1334   {
1335     NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1336       ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1337                      - NS_SCROLL_BAR_WIDTH (f), 0)
1338       : NSMakePoint (0, 0);
1339     [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1340     [view setBoundsOrigin: origin];
1341   }
1343   change_frame_size (f, rows, cols, 0, 1, 0); /* pretend, delay, safe */
1344   FRAME_PIXEL_WIDTH (f) = pixelwidth;
1345   FRAME_PIXEL_HEIGHT (f) = pixelheight;
1346 /*  SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */
1348   mark_window_cursors_off (XWINDOW (f->root_window));
1349   cancel_mouse_face (f);
1351   unblock_input ();
1355 static void
1356 ns_fullscreen_hook (FRAME_PTR f)
1358   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1360   if (!FRAME_VISIBLE_P (f))
1361     return;
1363    if (! [view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH)
1364     {
1365       /* Old style fs don't initiate correctly if created from
1366          init/default-frame alist, so use a timer (not nice...).
1367       */
1368       [NSTimer scheduledTimerWithTimeInterval: 0.5 target: view
1369                                      selector: @selector (handleFS)
1370                                      userInfo: nil repeats: NO];
1371       return;
1372     }
1374   block_input ();
1375   [view handleFS];
1376   unblock_input ();
1379 /* ==========================================================================
1381     Color management
1383    ========================================================================== */
1386 NSColor *
1387 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1389   struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1390   if (idx < 1 || idx >= color_table->avail)
1391     return nil;
1392   return color_table->colors[idx];
1396 unsigned long
1397 ns_index_color (NSColor *color, struct frame *f)
1399   struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1400   ptrdiff_t idx;
1401   ptrdiff_t i;
1403   if (!color_table->colors)
1404     {
1405       color_table->size = NS_COLOR_CAPACITY;
1406       color_table->avail = 1; /* skip idx=0 as marker */
1407       color_table->colors = xmalloc (color_table->size * sizeof (NSColor *));
1408       color_table->colors[0] = nil;
1409       color_table->empty_indices = [[NSMutableSet alloc] init];
1410     }
1412   /* do we already have this color ? */
1413   for (i = 1; i < color_table->avail; i++)
1414     if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1415       return i;
1417   if ([color_table->empty_indices count] > 0)
1418     {
1419       NSNumber *index = [color_table->empty_indices anyObject];
1420       [color_table->empty_indices removeObject: index];
1421       idx = [index unsignedLongValue];
1422     }
1423   else
1424     {
1425       if (color_table->avail == color_table->size)
1426         color_table->colors =
1427           xpalloc (color_table->colors, &color_table->size, 1,
1428                    min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1429       idx = color_table->avail++;
1430     }
1432   color_table->colors[idx] = color;
1433   [color retain];
1434 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1435   return idx;
1439 void
1440 ns_free_indexed_color (unsigned long idx, struct frame *f)
1442   struct ns_color_table *color_table;
1443   NSColor *color;
1444   NSNumber *index;
1446   if (!f)
1447     return;
1449   color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1451   if (idx <= 0 || idx >= color_table->size) {
1452     message1 ("ns_free_indexed_color: Color index out of range.\n");
1453     return;
1454   }
1456   index = [NSNumber numberWithUnsignedInt: idx];
1457   if ([color_table->empty_indices containsObject: index]) {
1458     message1 ("ns_free_indexed_color: attempt to free already freed color.\n");
1459     return;
1460   }
1462   color = color_table->colors[idx];
1463   [color release];
1464   color_table->colors[idx] = nil;
1465   [color_table->empty_indices addObject: index];
1466 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1470 static int
1471 ns_get_color (const char *name, NSColor **col)
1472 /* --------------------------------------------------------------------------
1473      Parse a color name
1474    -------------------------------------------------------------------------- */
1475 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1476    X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1477    See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1479   NSColor *new = nil;
1480   static char hex[20];
1481   int scaling;
1482   float r = -1.0, g, b;
1483   NSString *nsname = [NSString stringWithUTF8String: name];
1485 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1486   block_input ();
1488   if ([nsname isEqualToString: @"ns_selection_color"])
1489     {
1490       nsname = ns_selection_color;
1491       name = [ns_selection_color UTF8String];
1492     }
1494   /* First, check for some sort of numeric specification. */
1495   hex[0] = '\0';
1497   if (name[0] == '0' || name[0] == '1' || name[0] == '.')  /* RGB decimal */
1498     {
1499       NSScanner *scanner = [NSScanner scannerWithString: nsname];
1500       [scanner scanFloat: &r];
1501       [scanner scanFloat: &g];
1502       [scanner scanFloat: &b];
1503     }
1504   else if (!strncmp(name, "rgb:", 4))  /* A newer X11 format -- rgb:r/g/b */
1505     scaling = (snprintf (hex, sizeof hex, "%s", name + 4) - 2) / 3;
1506   else if (name[0] == '#')        /* An old X11 format; convert to newer */
1507     {
1508       int len = (strlen(name) - 1);
1509       int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1510       int i;
1511       scaling = strlen(name+start) / 3;
1512       for (i = 0; i < 3; i++)
1513         sprintf (hex + i * (scaling + 1), "%.*s/", scaling,
1514                  name + start + i * scaling);
1515       hex[3 * (scaling + 1) - 1] = '\0';
1516     }
1518   if (hex[0])
1519     {
1520       int rr, gg, bb;
1521       float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1522       if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1523         {
1524           r = rr / fscale;
1525           g = gg / fscale;
1526           b = bb / fscale;
1527         }
1528     }
1530   if (r >= 0.0F)
1531     {
1532       *col = [NSColor colorWithCalibratedRed: r green: g blue: b alpha: 1.0];
1533       unblock_input ();
1534       return 0;
1535     }
1537   /* Otherwise, color is expected to be from a list */
1538   {
1539     NSEnumerator *lenum, *cenum;
1540     NSString *name;
1541     NSColorList *clist;
1543 #ifdef NS_IMPL_GNUSTEP
1544     /* XXX: who is wrong, the requestor or the implementation? */
1545     if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1546         == NSOrderedSame)
1547       nsname = @"highlightColor";
1548 #endif
1550     lenum = [[NSColorList availableColorLists] objectEnumerator];
1551     while ( (clist = [lenum nextObject]) && new == nil)
1552       {
1553         cenum = [[clist allKeys] objectEnumerator];
1554         while ( (name = [cenum nextObject]) && new == nil )
1555           {
1556             if ([name compare: nsname
1557                       options: NSCaseInsensitiveSearch] == NSOrderedSame )
1558               new = [clist colorWithKey: name];
1559           }
1560       }
1561   }
1563   if (new)
1564     *col = [new colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1565   unblock_input ();
1566   return new ? 0 : 1;
1571 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1572 /* --------------------------------------------------------------------------
1573      Convert a Lisp string object to a NS color
1574    -------------------------------------------------------------------------- */
1576   NSTRACE (ns_lisp_to_color);
1577   if (STRINGP (color))
1578     return ns_get_color (SSDATA (color), col);
1579   else if (SYMBOLP (color))
1580     return ns_get_color (SSDATA (SYMBOL_NAME (color)), col);
1581   return 1;
1585 Lisp_Object
1586 ns_color_to_lisp (NSColor *col)
1587 /* --------------------------------------------------------------------------
1588      Convert a color to a lisp string with the RGB equivalent
1589    -------------------------------------------------------------------------- */
1591   EmacsCGFloat red, green, blue, alpha, gray;
1592   char buf[1024];
1593   const char *str;
1594   NSTRACE (ns_color_to_lisp);
1596   block_input ();
1597   if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1599       if ((str =[[col colorNameComponent] UTF8String]))
1600         {
1601           unblock_input ();
1602           return build_string ((char *)str);
1603         }
1605     [[col colorUsingColorSpaceName: NSCalibratedRGBColorSpace]
1606         getRed: &red green: &green blue: &blue alpha: &alpha];
1607   if (red ==green && red ==blue)
1608     {
1609       [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1610             getWhite: &gray alpha: &alpha];
1611       snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1612                 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1613       unblock_input ();
1614       return build_string (buf);
1615     }
1617   snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1618             lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1620   unblock_input ();
1621   return build_string (buf);
1625 void
1626 ns_query_color(void *col, XColor *color_def, int setPixel)
1627 /* --------------------------------------------------------------------------
1628          Get ARGB values out of NSColor col and put them into color_def.
1629          If setPixel, set the pixel to a concatenated version.
1630          and set color_def pixel to the resulting index.
1631    -------------------------------------------------------------------------- */
1633   EmacsCGFloat r, g, b, a;
1635   [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1636   color_def->red   = r * 65535;
1637   color_def->green = g * 65535;
1638   color_def->blue  = b * 65535;
1640   if (setPixel == YES)
1641     color_def->pixel
1642       = ARGB_TO_ULONG((int)(a*255),
1643                       (int)(r*255), (int)(g*255), (int)(b*255));
1647 bool
1648 ns_defined_color (struct frame *f,
1649                   const char *name,
1650                   XColor *color_def,
1651                   bool alloc,
1652                   bool makeIndex)
1653 /* --------------------------------------------------------------------------
1654          Return true if named color found, and set color_def rgb accordingly.
1655          If makeIndex and alloc are nonzero put the color in the color_table,
1656          and set color_def pixel to the resulting index.
1657          If makeIndex is zero, set color_def pixel to ARGB.
1658          Return false if not found
1659    -------------------------------------------------------------------------- */
1661   NSColor *col;
1662   NSTRACE (ns_defined_color);
1664   block_input ();
1665   if (ns_get_color (name, &col) != 0) /* Color not found  */
1666     {
1667       unblock_input ();
1668       return 0;
1669     }
1670   if (makeIndex && alloc)
1671     color_def->pixel = ns_index_color (col, f);
1672   ns_query_color (col, color_def, !makeIndex);
1673   unblock_input ();
1674   return 1;
1678 void
1679 x_set_frame_alpha (struct frame *f)
1680 /* --------------------------------------------------------------------------
1681      change the entire-frame transparency
1682    -------------------------------------------------------------------------- */
1684   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1685   double alpha = 1.0;
1686   double alpha_min = 1.0;
1688   if (dpyinfo->x_highlight_frame == f)
1689     alpha = f->alpha[0];
1690   else
1691     alpha = f->alpha[1];
1693   if (FLOATP (Vframe_alpha_lower_limit))
1694     alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1695   else if (INTEGERP (Vframe_alpha_lower_limit))
1696     alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1698   if (alpha < 0.0)
1699     return;
1700   else if (1.0 < alpha)
1701     alpha = 1.0;
1702   else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1703     alpha = alpha_min;
1705 #ifdef NS_IMPL_COCOA
1706   {
1707     EmacsView *view = FRAME_NS_VIEW (f);
1708   [[view window] setAlphaValue: alpha];
1709   }
1710 #endif
1714 /* ==========================================================================
1716     Mouse handling
1718    ========================================================================== */
1721 void
1722 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1723 /* --------------------------------------------------------------------------
1724      Programmatically reposition mouse pointer in pixel coordinates
1725    -------------------------------------------------------------------------- */
1727   NSTRACE (x_set_mouse_pixel_position);
1728   ns_raise_frame (f);
1729 #if 0
1730   /* FIXME: this does not work, and what about GNUstep? */
1731 #ifdef NS_IMPL_COCOA
1732   [FRAME_NS_VIEW (f) lockFocus];
1733   PSsetmouse ((float)pix_x, (float)pix_y);
1734   [FRAME_NS_VIEW (f) unlockFocus];
1735 #endif
1736 #endif
1740 void
1741 x_set_mouse_position (struct frame *f, int h, int v)
1742 /* --------------------------------------------------------------------------
1743      Programmatically reposition mouse pointer in character coordinates
1744    -------------------------------------------------------------------------- */
1746   int pix_x, pix_y;
1748   pix_x = FRAME_COL_TO_PIXEL_X (f, h) + FRAME_COLUMN_WIDTH (f) / 2;
1749   pix_y = FRAME_LINE_TO_PIXEL_Y (f, v) + FRAME_LINE_HEIGHT (f) / 2;
1751   if (pix_x < 0) pix_x = 0;
1752   if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
1754   if (pix_y < 0) pix_y = 0;
1755   if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
1757   x_set_mouse_pixel_position (f, pix_x, pix_y);
1761 static int
1762 note_mouse_movement (struct frame *frame, CGFloat x, CGFloat y)
1763 /*   ------------------------------------------------------------------------
1764      Called by EmacsView on mouseMovement events.  Passes on
1765      to emacs mainstream code if we moved off of a rect of interest
1766      known as last_mouse_glyph.
1767      ------------------------------------------------------------------------ */
1769 //  NSTRACE (note_mouse_movement);
1771   XSETFRAME (last_mouse_motion_frame, frame);
1773   /* Note, this doesn't get called for enter/leave, since we don't have a
1774      position.  Those are taken care of in the corresponding NSView methods. */
1776   /* has movement gone beyond last rect we were tracking? */
1777   if (x < last_mouse_glyph.origin.x ||
1778       x >= (last_mouse_glyph.origin.x + last_mouse_glyph.size.width) ||
1779       y < last_mouse_glyph.origin.y ||
1780       y >= (last_mouse_glyph.origin.y + last_mouse_glyph.size.height))
1781     {
1782       ns_update_begin(frame);
1783       frame->mouse_moved = 1;
1784       note_mouse_highlight (frame, x, y);
1785       remember_mouse_glyph (frame, x, y, &last_mouse_glyph);
1786       ns_update_end(frame);
1787       return 1;
1788     }
1790   return 0;
1794 static void
1795 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1796                    enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1797                    Time *time)
1798 /* --------------------------------------------------------------------------
1799     External (hook): inform emacs about mouse position and hit parts.
1800     If a scrollbar is being dragged, set bar_window, part, x, y, time.
1801     x & y should be position in the scrollbar (the whole bar, not the handle)
1802     and length of scrollbar respectively
1803    -------------------------------------------------------------------------- */
1805   id view;
1806   NSPoint position;
1807   Lisp_Object frame, tail;
1808   struct frame *f;
1809   struct ns_display_info *dpyinfo;
1811   NSTRACE (ns_mouse_position);
1813   if (*fp == NULL)
1814     {
1815       fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1816       return;
1817     }
1819   dpyinfo = FRAME_NS_DISPLAY_INFO (*fp);
1821   block_input ();
1823   if (last_mouse_scroll_bar != nil && insist == 0)
1824     {
1825       /* TODO: we do not use this path at the moment because drag events will
1826            go directly to the EmacsScroller.  Leaving code in for now. */
1827       [last_mouse_scroll_bar getMouseMotionPart: (int *)part window: bar_window
1828                                               x: x y: y];
1829       if (time) *time = last_mouse_movement_time;
1830       last_mouse_scroll_bar = nil;
1831     }
1832   else
1833     {
1834       /* Clear the mouse-moved flag for every frame on this display.  */
1835       FOR_EACH_FRAME (tail, frame)
1836         if (FRAME_NS_P (XFRAME (frame))
1837             && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1838           XFRAME (frame)->mouse_moved = 0;
1840       last_mouse_scroll_bar = nil;
1841       if (last_mouse_frame && FRAME_LIVE_P (last_mouse_frame))
1842         f = last_mouse_frame;
1843       else
1844         f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame
1845                                     : SELECTED_FRAME ();
1847       if (f && FRAME_NS_P (f))
1848         {
1849           view = FRAME_NS_VIEW (*fp);
1851           position = [[view window] mouseLocationOutsideOfEventStream];
1852           position = [view convertPoint: position fromView: nil];
1853           remember_mouse_glyph (f, position.x, position.y, &last_mouse_glyph);
1854 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1856           if (bar_window) *bar_window = Qnil;
1857           if (part) *part = 0; /*scroll_bar_handle; */
1859           if (x) XSETINT (*x, lrint (position.x));
1860           if (y) XSETINT (*y, lrint (position.y));
1861           if (time) *time = last_mouse_movement_time;
1862           *fp = f;
1863         }
1864     }
1866   unblock_input ();
1870 static void
1871 ns_frame_up_to_date (struct frame *f)
1872 /* --------------------------------------------------------------------------
1873     External (hook): Fix up mouse highlighting right after a full update.
1874     Can't use FRAME_MOUSE_UPDATE due to ns_frame_begin and ns_frame_end calls.
1875    -------------------------------------------------------------------------- */
1877   NSTRACE (ns_frame_up_to_date);
1879   if (FRAME_NS_P (f))
1880     {
1881       Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1882       if (f == hlinfo->mouse_face_mouse_frame)
1883         {
1884           block_input ();
1885           ns_update_begin(f);
1886           if (hlinfo->mouse_face_mouse_frame)
1887             note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
1888                                   hlinfo->mouse_face_mouse_x,
1889                                   hlinfo->mouse_face_mouse_y);
1890           ns_update_end(f);
1891           unblock_input ();
1892         }
1893     }
1897 static void
1898 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1899 /* --------------------------------------------------------------------------
1900     External (RIF): set frame mouse pointer type.
1901    -------------------------------------------------------------------------- */
1903   NSTRACE (ns_define_frame_cursor);
1904   if (FRAME_POINTER_TYPE (f) != cursor)
1905     {
1906       EmacsView *view = FRAME_NS_VIEW (f);
1907       FRAME_POINTER_TYPE (f) = cursor;
1908       [[view window] invalidateCursorRectsForView: view];
1909       /* Redisplay assumes this function also draws the changed frame
1910          cursor, but this function doesn't, so do it explicitly.  */
1911       x_update_cursor (f, 1);
1912     }
1917 /* ==========================================================================
1919     Keyboard handling
1921    ========================================================================== */
1924 static unsigned
1925 ns_convert_key (unsigned code)
1926 /* --------------------------------------------------------------------------
1927     Internal call used by NSView-keyDown.
1928    -------------------------------------------------------------------------- */
1930   const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym)
1931                                 / sizeof (convert_ns_to_X_keysym[0]));
1932   unsigned keysym;
1933   /* An array would be faster, but less easy to read. */
1934   for (keysym = 0; keysym < last_keysym; keysym += 2)
1935     if (code == convert_ns_to_X_keysym[keysym])
1936       return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
1937   return 0;
1938 /* if decide to use keyCode and Carbon table, use this line:
1939      return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
1943 char *
1944 x_get_keysym_name (int keysym)
1945 /* --------------------------------------------------------------------------
1946     Called by keyboard.c.  Not sure if the return val is important, except
1947     that it be unique.
1948    -------------------------------------------------------------------------- */
1950   static char value[16];
1951   NSTRACE (x_get_keysym_name);
1952   sprintf (value, "%d", keysym);
1953   return value;
1958 /* ==========================================================================
1960     Block drawing operations
1962    ========================================================================== */
1965 static void
1966 ns_redraw_scroll_bars (struct frame *f)
1968   int i;
1969   id view;
1970   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
1971   NSTRACE (ns_redraw_scroll_bars);
1972   for (i =[subviews count]-1; i >= 0; i--)
1973     {
1974       view = [subviews objectAtIndex: i];
1975       if (![view isKindOfClass: [EmacsScroller class]]) continue;
1976       [view display];
1977     }
1981 void
1982 ns_clear_frame (struct frame *f)
1983 /* --------------------------------------------------------------------------
1984       External (hook): Erase the entire frame
1985    -------------------------------------------------------------------------- */
1987   NSView *view = FRAME_NS_VIEW (f);
1988   NSRect r;
1990   NSTRACE (ns_clear_frame);
1992  /* comes on initial frame because we have
1993     after-make-frame-functions = select-frame */
1994  if (!FRAME_DEFAULT_FACE (f))
1995    return;
1997   mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
1999   output_cursor.hpos = output_cursor.vpos = 0;
2000   output_cursor.x = -1;
2002   r = [view bounds];
2004   block_input ();
2005   ns_focus (f, &r, 1);
2006   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
2007   NSRectFill (r);
2008   ns_unfocus (f);
2010   /* as of 2006/11 or so this is now needed */
2011   ns_redraw_scroll_bars (f);
2012   unblock_input ();
2016 static void
2017 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2018 /* --------------------------------------------------------------------------
2019     External (RIF):  Clear section of frame
2020    -------------------------------------------------------------------------- */
2022   NSRect r = NSMakeRect (x, y, width, height);
2023   NSView *view = FRAME_NS_VIEW (f);
2024   struct face *face = FRAME_DEFAULT_FACE (f);
2026   if (!view || !face)
2027     return;
2029   NSTRACE (ns_clear_frame_area);
2031   r = NSIntersectionRect (r, [view frame]);
2032   ns_focus (f, &r, 1);
2033   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2035   NSRectFill (r);
2037   ns_unfocus (f);
2038   return;
2042 static void
2043 ns_scroll_run (struct window *w, struct run *run)
2044 /* --------------------------------------------------------------------------
2045     External (RIF):  Insert or delete n lines at line vpos
2046    -------------------------------------------------------------------------- */
2048   struct frame *f = XFRAME (w->frame);
2049   int x, y, width, height, from_y, to_y, bottom_y;
2051   NSTRACE (ns_scroll_run);
2053   /* begin copy from other terms */
2054   /* Get frame-relative bounding box of the text display area of W,
2055      without mode lines.  Include in this box the left and right
2056      fringe of W.  */
2057   window_box (w, -1, &x, &y, &width, &height);
2059   from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2060   to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2061   bottom_y = y + height;
2063   if (to_y < from_y)
2064     {
2065       /* Scrolling up.  Make sure we don't copy part of the mode
2066          line at the bottom.  */
2067       if (from_y + run->height > bottom_y)
2068         height = bottom_y - from_y;
2069       else
2070         height = run->height;
2071     }
2072   else
2073     {
2074       /* Scrolling down.  Make sure we don't copy over the mode line.
2075          at the bottom.  */
2076       if (to_y + run->height > bottom_y)
2077         height = bottom_y - to_y;
2078       else
2079         height = run->height;
2080     }
2081   /* end copy from other terms */
2083   if (height == 0)
2084       return;
2086   block_input ();
2088   updated_window = w;
2089   x_clear_cursor (w);
2091   {
2092     NSRect srcRect = NSMakeRect (x, from_y, width, height);
2093     NSRect dstRect = NSMakeRect (x, to_y, width, height);
2094     NSPoint dstOrigin = NSMakePoint (x, to_y);
2096     ns_focus (f, &dstRect, 1);
2097     NSCopyBits (0, srcRect , dstOrigin);
2098     ns_unfocus (f);
2099   }
2101   unblock_input ();
2105 static void
2106 ns_after_update_window_line (struct glyph_row *desired_row)
2107 /* --------------------------------------------------------------------------
2108     External (RIF): preparatory to fringe update after text was updated
2109    -------------------------------------------------------------------------- */
2111   struct window *w = updated_window;
2112   struct frame *f;
2113   int width, height;
2115   NSTRACE (ns_after_update_window_line);
2117   /* begin copy from other terms */
2118   eassert (w);
2120   if (!desired_row->mode_line_p && !w->pseudo_window_p)
2121     desired_row->redraw_fringe_bitmaps_p = 1;
2123   /* When a window has disappeared, make sure that no rest of
2124      full-width rows stays visible in the internal border.  */
2125   if (windows_or_buffers_changed
2126       && desired_row->full_width_p
2127       && (f = XFRAME (w->frame),
2128           width = FRAME_INTERNAL_BORDER_WIDTH (f),
2129           width != 0)
2130       && (height = desired_row->visible_height,
2131           height > 0))
2132     {
2133       int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2135       block_input ();
2136       ns_clear_frame_area (f, 0, y, width, height);
2137       ns_clear_frame_area (f,
2138                            FRAME_PIXEL_WIDTH (f) - width,
2139                            y, width, height);
2140       unblock_input ();
2141     }
2145 static void
2146 ns_shift_glyphs_for_insert (struct frame *f,
2147                            int x, int y, int width, int height,
2148                            int shift_by)
2149 /* --------------------------------------------------------------------------
2150     External (RIF): copy an area horizontally, don't worry about clearing src
2151    -------------------------------------------------------------------------- */
2153   NSRect srcRect = NSMakeRect (x, y, width, height);
2154   NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2155   NSPoint dstOrigin = dstRect.origin;
2157   NSTRACE (ns_shift_glyphs_for_insert);
2159   ns_focus (f, &dstRect, 1);
2160   NSCopyBits (0, srcRect, dstOrigin);
2161   ns_unfocus (f);
2166 /* ==========================================================================
2168     Character encoding and metrics
2170    ========================================================================== */
2173 static void
2174 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2175 /* --------------------------------------------------------------------------
2176      External (RIF); compute left/right overhang of whole string and set in s
2177    -------------------------------------------------------------------------- */
2179   struct font *font = s->font;
2181   if (s->char2b)
2182     {
2183       struct font_metrics metrics;
2184       unsigned int codes[2];
2185       codes[0] = *(s->char2b);
2186       codes[1] = *(s->char2b + s->nchars - 1);
2188       font->driver->text_extents (font, codes, 2, &metrics);
2189       s->left_overhang = -metrics.lbearing;
2190       s->right_overhang
2191         = metrics.rbearing > metrics.width
2192         ? metrics.rbearing - metrics.width : 0;
2193     }
2194   else
2195     {
2196       s->left_overhang = 0;
2197       s->right_overhang = ((struct nsfont_info *)font)->ital ?
2198         FONT_HEIGHT (font) * 0.2 : 0;
2199     }
2204 /* ==========================================================================
2206     Fringe and cursor drawing
2208    ========================================================================== */
2211 extern int max_used_fringe_bitmap;
2212 static void
2213 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2214                       struct draw_fringe_bitmap_params *p)
2215 /* --------------------------------------------------------------------------
2216     External (RIF); fringe-related
2217    -------------------------------------------------------------------------- */
2219   struct frame *f = XFRAME (WINDOW_FRAME (w));
2220   struct face *face = p->face;
2221   static EmacsImage **bimgs = NULL;
2222   static int nBimgs = 0;
2224   /* grow bimgs if needed */
2225   if (nBimgs < max_used_fringe_bitmap)
2226     {
2227       bimgs = xrealloc (bimgs, max_used_fringe_bitmap * sizeof *bimgs);
2228       memset (bimgs + nBimgs, 0,
2229               (max_used_fringe_bitmap - nBimgs) * sizeof *bimgs);
2230       nBimgs = max_used_fringe_bitmap;
2231     }
2233   /* Must clip because of partially visible lines.  */
2234   ns_clip_to_row (w, row, -1, YES);
2236   if (!p->overlay_p)
2237     {
2238       int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
2240       /* If the fringe is adjacent to the left (right) scroll bar of a
2241          leftmost (rightmost, respectively) window, then extend its
2242          background to the gap between the fringe and the bar.  */
2243       if ((WINDOW_LEFTMOST_P (w)
2244            && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
2245           || (WINDOW_RIGHTMOST_P (w)
2246               && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w)))
2247         {
2248           int sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
2250           if (sb_width > 0)
2251             {
2252               int bar_area_x = WINDOW_SCROLL_BAR_AREA_X (w);
2253               int bar_area_width = (WINDOW_CONFIG_SCROLL_BAR_COLS (w)
2254                                     * FRAME_COLUMN_WIDTH (f));
2256               if (bx < 0)
2257                 {
2258                   /* Bitmap fills the fringe.  */
2259                   if (bar_area_x + bar_area_width == p->x)
2260                     bx = bar_area_x + sb_width;
2261                   else if (p->x + p->wd == bar_area_x)
2262                     bx = bar_area_x;
2263                   if (bx >= 0)
2264                     {
2265                       int header_line_height = WINDOW_HEADER_LINE_HEIGHT (w);
2267                       nx = bar_area_width - sb_width;
2268                       by = WINDOW_TO_FRAME_PIXEL_Y (w, max (header_line_height,
2269                                                             row->y));
2270                       ny = row->visible_height;
2271                     }
2272                 }
2273               else
2274                 {
2275                   if (bar_area_x + bar_area_width == bx)
2276                     {
2277                       bx = bar_area_x + sb_width;
2278                       nx += bar_area_width - sb_width;
2279                     }
2280                   else if (bx + nx == bar_area_x)
2281                     nx += bar_area_width - sb_width;
2282                 }
2283             }
2284         }
2286       if (bx >= 0 && nx > 0)
2287         {
2288           NSRect r = NSMakeRect (bx, by, nx, ny);
2289           NSRectClip (r);
2290           [ns_lookup_indexed_color (face->background, f) set];
2291           NSRectFill (r);
2292         }
2293     }
2295   if (p->which)
2296     {
2297       NSRect r = NSMakeRect (p->x, p->y, p->wd, p->h);
2298       EmacsImage *img = bimgs[p->which - 1];
2300       if (!img)
2301         {
2302           unsigned short *bits = p->bits + p->dh;
2303           int len = p->h;
2304           int i;
2305           unsigned char *cbits = xmalloc (len);
2307           for (i = 0; i < len; i++)
2308             cbits[i] = ~(bits[i] & 0xff);
2309           img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2310                                            flip: NO];
2311           bimgs[p->which - 1] = img;
2312           xfree (cbits);
2313         }
2315       NSRectClip (r);
2316       /* Since we composite the bitmap instead of just blitting it, we need
2317          to erase the whole background. */
2318       [ns_lookup_indexed_color(face->background, f) set];
2319       NSRectFill (r);
2320       [img setXBMColor: ns_lookup_indexed_color(face->foreground, f)];
2321 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
2322       [img drawInRect: r
2323               fromRect: NSZeroRect
2324              operation: NSCompositeSourceOver
2325               fraction: 1.0
2326            respectFlipped: YES
2327                 hints: nil];
2328 #else
2329       {
2330         NSPoint pt = r.origin;
2331         pt.y += p->h;
2332         [img compositeToPoint: pt operation: NSCompositeSourceOver];
2333       }
2334 #endif
2335     }
2336   ns_unfocus (f);
2340 static void
2341 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2342                        int x, int y, int cursor_type, int cursor_width,
2343                        int on_p, int active_p)
2344 /* --------------------------------------------------------------------------
2345      External call (RIF): draw cursor.
2346      Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2347    -------------------------------------------------------------------------- */
2349   NSRect r, s;
2350   int fx, fy, h, cursor_height;
2351   struct frame *f = WINDOW_XFRAME (w);
2352   struct glyph *phys_cursor_glyph;
2353   struct glyph *cursor_glyph;
2354   struct face *face;
2355   NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2357   /* If cursor is out of bounds, don't draw garbage.  This can happen
2358      in mini-buffer windows when switching between echo area glyphs
2359      and mini-buffer.  */
2361   NSTRACE (dumpcursor);
2363   if (!on_p)
2364     return;
2366   w->phys_cursor_type = cursor_type;
2367   w->phys_cursor_on_p = on_p;
2369   if (cursor_type == NO_CURSOR)
2370     {
2371       w->phys_cursor_width = 0;
2372       return;
2373     }
2375   if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2376     {
2377       if (glyph_row->exact_window_width_line_p
2378           && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2379         {
2380           glyph_row->cursor_in_fringe_p = 1;
2381           draw_fringe_bitmap (w, glyph_row, 0);
2382         }
2383       return;
2384     }
2386   /* We draw the cursor (with NSRectFill), then draw the glyph on top
2387      (other terminals do it the other way round).  We must set
2388      w->phys_cursor_width to the cursor width.  For bar cursors, that
2389      is CURSOR_WIDTH; for box cursors, it is the glyph width.  */
2390   get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2392   /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2393      to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2394   if (cursor_type == BAR_CURSOR)
2395     {
2396       if (cursor_width < 1)
2397         cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2398       w->phys_cursor_width = cursor_width;
2399     }
2400   /* If we have an HBAR, "cursor_width" MAY specify height. */
2401   else if (cursor_type == HBAR_CURSOR)
2402     {
2403       cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2404       fy += h - cursor_height;
2405       h = cursor_height;
2406     }
2408   r.origin.x = fx, r.origin.y = fy;
2409   r.size.height = h;
2410   r.size.width = w->phys_cursor_width;
2412   /* TODO: only needed in rare cases with last-resort font in HELLO..
2413      should we do this more efficiently? */
2414   ns_clip_to_row (w, glyph_row, -1, NO); /* do ns_focus(f, &r, 1); if remove */
2417   face = FACE_FROM_ID (f, phys_cursor_glyph->face_id);
2418   if (face && NS_FACE_BACKGROUND (face)
2419       == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2420     {
2421       [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2422       hollow_color = FRAME_CURSOR_COLOR (f);
2423     }
2424   else
2425     [FRAME_CURSOR_COLOR (f) set];
2427 #ifdef NS_IMPL_COCOA
2428   /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2429            atomic.  Cleaner ways of doing this should be investigated.
2430            One way would be to set a global variable DRAWING_CURSOR
2431            when making the call to draw_phys..(), don't focus in that
2432            case, then move the ns_unfocus() here after that call. */
2433   NSDisableScreenUpdates ();
2434 #endif
2436   switch (cursor_type)
2437     {
2438     case NO_CURSOR:
2439       break;
2440     case FILLED_BOX_CURSOR:
2441       NSRectFill (r);
2442       break;
2443     case HOLLOW_BOX_CURSOR:
2444       NSRectFill (r);
2445       [hollow_color set];
2446       NSRectFill (NSInsetRect (r, 1, 1));
2447       [FRAME_CURSOR_COLOR (f) set];
2448       break;
2449     case HBAR_CURSOR:
2450       NSRectFill (r);
2451       break;
2452     case BAR_CURSOR:
2453       s = r;
2454       /* If the character under cursor is R2L, draw the bar cursor
2455          on the right of its glyph, rather than on the left.  */
2456       cursor_glyph = get_phys_cursor_glyph (w);
2457       if ((cursor_glyph->resolved_level & 1) != 0)
2458         s.origin.x += cursor_glyph->pixel_width - s.size.width;
2460       NSRectFill (s);
2461       break;
2462     }
2463   ns_unfocus (f);
2465   /* draw the character under the cursor */
2466   if (cursor_type != NO_CURSOR)
2467     draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2469 #ifdef NS_IMPL_COCOA
2470   NSEnableScreenUpdates ();
2471 #endif
2476 static void
2477 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2478 /* --------------------------------------------------------------------------
2479      External (RIF): Draw a vertical line.
2480    -------------------------------------------------------------------------- */
2482   struct frame *f = XFRAME (WINDOW_FRAME (w));
2483   struct face *face;
2484   NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2486   NSTRACE (ns_draw_vertical_window_border);
2488   face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2489   if (face)
2490       [ns_lookup_indexed_color(face->foreground, f) set];
2492   ns_focus (f, &r, 1);
2493   NSRectFill(r);
2494   ns_unfocus (f);
2498 void
2499 show_hourglass (struct atimer *timer)
2501   if (hourglass_shown_p)
2502     return;
2504   block_input ();
2506   /* TODO: add NSProgressIndicator to selected frame (see macfns.c) */
2508   hourglass_shown_p = 1;
2509   unblock_input ();
2513 void
2514 hide_hourglass (void)
2516   if (!hourglass_shown_p)
2517     return;
2519   block_input ();
2521   /* TODO: remove NSProgressIndicator from all frames */
2523   hourglass_shown_p = 0;
2524   unblock_input ();
2529 /* ==========================================================================
2531     Glyph drawing operations
2533    ========================================================================== */
2535 static int
2536 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2537 /* --------------------------------------------------------------------------
2538     Wrapper utility to account for internal border width on full-width lines,
2539     and allow top full-width rows to hit the frame top.  nr should be pointer
2540     to two successive NSRects.  Number of rects actually used is returned.
2541    -------------------------------------------------------------------------- */
2543   int n = get_glyph_string_clip_rects (s, nr, 2);
2544   return n;
2547 /* --------------------------------------------------------------------
2548    Draw a wavy line under glyph string s. The wave fills wave_height
2549    pixels from y.
2551                     x          wave_length = 2
2552                                  --
2553                 y    *   *   *   *   *
2554                      |* * * * * * * * *
2555     wave_height = 3  | *   *   *   *
2556   --------------------------------------------------------------------- */
2558 static void
2559 ns_draw_underwave (struct glyph_string *s, EmacsCGFloat width, EmacsCGFloat x)
2561   int wave_height = 3, wave_length = 2;
2562   int y, dx, dy, odd, xmax;
2563   NSPoint a, b;
2564   NSRect waveClip;
2566   dx = wave_length;
2567   dy = wave_height - 1;
2568   y =  s->ybase - wave_height + 3;
2569   xmax = x + width;
2571   /* Find and set clipping rectangle */
2572   waveClip = NSMakeRect (x, y, width, wave_height);
2573   [[NSGraphicsContext currentContext] saveGraphicsState];
2574   NSRectClip (waveClip);
2576   /* Draw the waves */
2577   a.x = x - ((int)(x) % dx) + (EmacsCGFloat) 0.5;
2578   b.x = a.x + dx;
2579   odd = (int)(a.x/dx) % 2;
2580   a.y = b.y = y + 0.5;
2582   if (odd)
2583     a.y += dy;
2584   else
2585     b.y += dy;
2587   while (a.x <= xmax)
2588     {
2589       [NSBezierPath strokeLineFromPoint:a toPoint:b];
2590       a.x = b.x, a.y = b.y;
2591       b.x += dx, b.y = y + 0.5 + odd*dy;
2592       odd = !odd;
2593     }
2595   /* Restore previous clipping rectangle(s) */
2596   [[NSGraphicsContext currentContext] restoreGraphicsState];
2601 void
2602 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
2603                          NSColor *defaultCol, CGFloat width, CGFloat x)
2604 /* --------------------------------------------------------------------------
2605    Draw underline, overline, and strike-through on glyph string s.
2606    -------------------------------------------------------------------------- */
2608   if (s->for_overlaps)
2609     return;
2611   /* Do underline. */
2612   if (face->underline_p)
2613     {
2614       if (s->face->underline_type == FACE_UNDER_WAVE)
2615         {
2616           if (face->underline_defaulted_p)
2617             [defaultCol set];
2618           else
2619             [ns_lookup_indexed_color (face->underline_color, s->f) set];
2621           ns_draw_underwave (s, width, x);
2622         }
2623       else if (s->face->underline_type == FACE_UNDER_LINE)
2624         {
2626           NSRect r;
2627           unsigned long thickness, position;
2629           /* If the prev was underlined, match its appearance. */
2630           if (s->prev && s->prev->face->underline_p
2631               && s->prev->face->underline_type == FACE_UNDER_LINE
2632               && s->prev->underline_thickness > 0)
2633             {
2634               thickness = s->prev->underline_thickness;
2635               position = s->prev->underline_position;
2636             }
2637           else
2638             {
2639               struct font *font;
2640               unsigned long descent;
2642               font=s->font;
2643               descent = s->y + s->height - s->ybase;
2645               /* Use underline thickness of font, defaulting to 1. */
2646               thickness = (font && font->underline_thickness > 0)
2647                 ? font->underline_thickness : 1;
2649               /* Determine the offset of underlining from the baseline. */
2650               if (x_underline_at_descent_line)
2651                 position = descent - thickness;
2652               else if (x_use_underline_position_properties
2653                        && font && font->underline_position >= 0)
2654                 position = font->underline_position;
2655               else if (font)
2656                 position = lround (font->descent / 2);
2657               else
2658                 position = underline_minimum_offset;
2660               position = max (position, underline_minimum_offset);
2662               /* Ensure underlining is not cropped. */
2663               if (descent <= position)
2664                 {
2665                   position = descent - 1;
2666                   thickness = 1;
2667                 }
2668               else if (descent < position + thickness)
2669                 thickness = 1;
2670             }
2672           s->underline_thickness = thickness;
2673           s->underline_position = position;
2675           r = NSMakeRect (x, s->ybase + position, width, thickness);
2677           if (face->underline_defaulted_p)
2678             [defaultCol set];
2679           else
2680             [ns_lookup_indexed_color (face->underline_color, s->f) set];
2681           NSRectFill (r);
2682         }
2683     }
2684   /* Do overline. We follow other terms in using a thickness of 1
2685      and ignoring overline_margin. */
2686   if (face->overline_p)
2687     {
2688       NSRect r;
2689       r = NSMakeRect (x, s->y, width, 1);
2691       if (face->overline_color_defaulted_p)
2692         [defaultCol set];
2693       else
2694         [ns_lookup_indexed_color (face->overline_color, s->f) set];
2695       NSRectFill (r);
2696     }
2698   /* Do strike-through.  We follow other terms for thickness and
2699      vertical position.*/
2700   if (face->strike_through_p)
2701     {
2702       NSRect r;
2703       unsigned long dy;
2705       dy = lrint ((s->height - 1) / 2);
2706       r = NSMakeRect (x, s->y + dy, width, 1);
2708       if (face->strike_through_color_defaulted_p)
2709         [defaultCol set];
2710       else
2711         [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
2712       NSRectFill (r);
2713     }
2716 static void
2717 ns_draw_box (NSRect r, CGFloat thickness, NSColor *col,
2718              char left_p, char right_p)
2719 /* --------------------------------------------------------------------------
2720     Draw an unfilled rect inside r, optionally leaving left and/or right open.
2721     Note we can't just use an NSDrawRect command, because of the possibility
2722     of some sides not being drawn, and because the rect will be filled.
2723    -------------------------------------------------------------------------- */
2725   NSRect s = r;
2726   [col set];
2728   /* top, bottom */
2729   s.size.height = thickness;
2730   NSRectFill (s);
2731   s.origin.y += r.size.height - thickness;
2732   NSRectFill (s);
2734   s.size.height = r.size.height;
2735   s.origin.y = r.origin.y;
2737   /* left, right (optional) */
2738   s.size.width = thickness;
2739   if (left_p)
2740     NSRectFill (s);
2741   if (right_p)
2742     {
2743       s.origin.x += r.size.width - thickness;
2744       NSRectFill (s);
2745     }
2749 static void
2750 ns_draw_relief (NSRect r, int thickness, char raised_p,
2751                char top_p, char bottom_p, char left_p, char right_p,
2752                struct glyph_string *s)
2753 /* --------------------------------------------------------------------------
2754     Draw a relief rect inside r, optionally leaving some sides open.
2755     Note we can't just use an NSDrawBezel command, because of the possibility
2756     of some sides not being drawn, and because the rect will be filled.
2757    -------------------------------------------------------------------------- */
2759   static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2760   NSColor *newBaseCol = nil;
2761   NSRect sr = r;
2763   NSTRACE (ns_draw_relief);
2765   /* set up colors */
2767   if (s->face->use_box_color_for_shadows_p)
2768     {
2769       newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2770     }
2771 /*     else if (s->first_glyph->type == IMAGE_GLYPH
2772            && s->img->pixmap
2773            && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2774        {
2775          newBaseCol = IMAGE_BACKGROUND  (s->img, s->f, 0);
2776        } */
2777   else
2778     {
2779       newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2780     }
2782   if (newBaseCol == nil)
2783     newBaseCol = [NSColor grayColor];
2785   if (newBaseCol != baseCol)  /* TODO: better check */
2786     {
2787       [baseCol release];
2788       baseCol = [newBaseCol retain];
2789       [lightCol release];
2790       lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2791       [darkCol release];
2792       darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2793     }
2795   [(raised_p ? lightCol : darkCol) set];
2797   /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2799   /* top */
2800   sr.size.height = thickness;
2801   if (top_p) NSRectFill (sr);
2803   /* left */
2804   sr.size.height = r.size.height;
2805   sr.size.width = thickness;
2806   if (left_p) NSRectFill (sr);
2808   [(raised_p ? darkCol : lightCol) set];
2810   /* bottom */
2811   sr.size.width = r.size.width;
2812   sr.size.height = thickness;
2813   sr.origin.y += r.size.height - thickness;
2814   if (bottom_p) NSRectFill (sr);
2816   /* right */
2817   sr.size.height = r.size.height;
2818   sr.origin.y = r.origin.y;
2819   sr.size.width = thickness;
2820   sr.origin.x += r.size.width - thickness;
2821   if (right_p) NSRectFill (sr);
2825 static void
2826 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2827 /* --------------------------------------------------------------------------
2828       Function modeled after x_draw_glyph_string_box ().
2829       Sets up parameters for drawing.
2830    -------------------------------------------------------------------------- */
2832   int right_x, last_x;
2833   char left_p, right_p;
2834   struct glyph *last_glyph;
2835   NSRect r;
2836   int thickness;
2837   struct face *face;
2839   if (s->hl == DRAW_MOUSE_FACE)
2840     {
2841       face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2842       if (!face)
2843         face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2844     }
2845   else
2846     face = s->face;
2848   thickness = face->box_line_width;
2850   NSTRACE (ns_dumpglyphs_box_or_relief);
2852   last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2853             ? WINDOW_RIGHT_EDGE_X (s->w)
2854             : window_box_right (s->w, s->area));
2855   last_glyph = (s->cmp || s->img
2856                 ? s->first_glyph : s->first_glyph + s->nchars-1);
2858   right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2859               ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2861   left_p = (s->first_glyph->left_box_line_p
2862             || (s->hl == DRAW_MOUSE_FACE
2863                 && (s->prev == NULL || s->prev->hl != s->hl)));
2864   right_p = (last_glyph->right_box_line_p
2865              || (s->hl == DRAW_MOUSE_FACE
2866                  && (s->next == NULL || s->next->hl != s->hl)));
2868   r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2870   /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
2871   if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
2872     {
2873       ns_draw_box (r, abs (thickness),
2874                    ns_lookup_indexed_color (face->box_color, s->f),
2875                   left_p, right_p);
2876     }
2877   else
2878     {
2879       ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2880                      1, 1, left_p, right_p, s);
2881     }
2885 static void
2886 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2887 /* --------------------------------------------------------------------------
2888       Modeled after x_draw_glyph_string_background, which draws BG in
2889       certain cases.  Others are left to the text rendering routine.
2890    -------------------------------------------------------------------------- */
2892   NSTRACE (ns_maybe_dumpglyphs_background);
2894   if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2895     {
2896       int box_line_width = max (s->face->box_line_width, 0);
2897       if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2898           || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2899         {
2900           struct face *face;
2901           if (s->hl == DRAW_MOUSE_FACE)
2902             {
2903               face = FACE_FROM_ID (s->f,
2904                                    MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2905               if (!face)
2906                 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2907             }
2908           else
2909             face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2910           if (!face->stipple)
2911             [(NS_FACE_BACKGROUND (face) != 0
2912               ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2913               : FRAME_BACKGROUND_COLOR (s->f)) set];
2914           else
2915             {
2916               struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (s->f);
2917               [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2918             }
2920           if (s->hl != DRAW_CURSOR)
2921             {
2922               NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2923                                     s->background_width,
2924                                     s->height-2*box_line_width);
2925               NSRectFill (r);
2926             }
2928           s->background_filled_p = 1;
2929         }
2930     }
2934 static void
2935 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2936 /* --------------------------------------------------------------------------
2937       Renders an image and associated borders.
2938    -------------------------------------------------------------------------- */
2940   EmacsImage *img = s->img->pixmap;
2941   int box_line_vwidth = max (s->face->box_line_width, 0);
2942   int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2943   int bg_x, bg_y, bg_height;
2944   int th;
2945   char raised_p;
2946   NSRect br;
2947   struct face *face;
2948   NSColor *tdCol;
2950   NSTRACE (ns_dumpglyphs_image);
2952   if (s->face->box != FACE_NO_BOX
2953       && s->first_glyph->left_box_line_p && s->slice.x == 0)
2954     x += abs (s->face->box_line_width);
2956   bg_x = x;
2957   bg_y =  s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2958   bg_height = s->height;
2959   /* other terms have this, but was causing problems w/tabbar mode */
2960   /* - 2 * box_line_vwidth; */
2962   if (s->slice.x == 0) x += s->img->hmargin;
2963   if (s->slice.y == 0) y += s->img->vmargin;
2965   /* Draw BG: if we need larger area than image itself cleared, do that,
2966      otherwise, since we composite the image under NS (instead of mucking
2967      with its background color), we must clear just the image area. */
2968   if (s->hl == DRAW_MOUSE_FACE)
2969     {
2970       face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2971       if (!face)
2972        face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2973     }
2974   else
2975     face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2977   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
2979   if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
2980       || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
2981     {
2982       br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
2983       s->background_filled_p = 1;
2984     }
2985   else
2986     {
2987       br = NSMakeRect (x, y, s->slice.width, s->slice.height);
2988     }
2990   NSRectFill (br);
2992   /* Draw the image.. do we need to draw placeholder if img ==nil? */
2993   if (img != nil)
2994     {
2995 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
2996       NSRect dr = NSMakeRect (x, y, s->slice.width, s->slice.height);
2997       NSRect ir = NSMakeRect (s->slice.x, s->slice.y,
2998                               s->slice.width, s->slice.height);
2999       [img drawInRect: dr
3000              fromRect: ir
3001              operation: NSCompositeSourceOver
3002               fraction: 1.0
3003            respectFlipped: YES
3004                 hints: nil];
3005 #else
3006       [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3007                   operation: NSCompositeSourceOver];
3008 #endif
3009     }
3011   if (s->hl == DRAW_CURSOR)
3012     {
3013     [FRAME_CURSOR_COLOR (s->f) set];
3014     if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3015       tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3016     else
3017       /* Currently on NS img->mask is always 0. Since
3018          get_window_cursor_type specifies a hollow box cursor when on
3019          a non-masked image we never reach this clause. But we put it
3020          in in anticipation of better support for image masks on
3021          NS. */
3022       tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3023     }
3024   else
3025     {
3026       tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3027     }
3029   /* Draw underline, overline, strike-through. */
3030   ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3032   /* Draw relief, if requested */
3033   if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3034     {
3035       if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3036         {
3037           th = tool_bar_button_relief >= 0 ?
3038             tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3039           raised_p = (s->hl == DRAW_IMAGE_RAISED);
3040         }
3041       else
3042         {
3043           th = abs (s->img->relief);
3044           raised_p = (s->img->relief > 0);
3045         }
3047       r.origin.x = x - th;
3048       r.origin.y = y - th;
3049       r.size.width = s->slice.width + 2*th-1;
3050       r.size.height = s->slice.height + 2*th-1;
3051       ns_draw_relief (r, th, raised_p,
3052                       s->slice.y == 0,
3053                       s->slice.y + s->slice.height == s->img->height,
3054                       s->slice.x == 0,
3055                       s->slice.x + s->slice.width == s->img->width, s);
3056     }
3058   /* If there is no mask, the background won't be seen,
3059      so draw a rectangle on the image for the cursor.
3060      Do this for all images, getting transparency right is not reliable.  */
3061   if (s->hl == DRAW_CURSOR)
3062     {
3063       int thickness = abs (s->img->relief);
3064       if (thickness == 0) thickness = 1;
3065       ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3066     }
3070 static void
3071 ns_dumpglyphs_stretch (struct glyph_string *s)
3073   NSRect r[2];
3074   int n, i;
3075   struct face *face;
3076   NSColor *fgCol, *bgCol;
3078   if (!s->background_filled_p)
3079     {
3080       n = ns_get_glyph_string_clip_rect (s, r);
3081       *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3083       ns_focus (s->f, r, n);
3085       if (s->hl == DRAW_MOUSE_FACE)
3086        {
3087          face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3088          if (!face)
3089            face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3090        }
3091       else
3092        face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3094       bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3095       fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3097       for (i = 0; i < n; ++i)
3098         {
3099           if (!s->row->full_width_p)
3100             {
3101               int overrun, leftoverrun;
3103               /* truncate to avoid overwriting fringe and/or scrollbar */
3104               overrun = max (0, (s->x + s->background_width)
3105                              - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3106                                 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3107               r[i].size.width -= overrun;
3109               /* truncate to avoid overwriting to left of the window box */
3110               leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3111                              + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3113               if (leftoverrun > 0)
3114                 {
3115                   r[i].origin.x += leftoverrun;
3116                   r[i].size.width -= leftoverrun;
3117                 }
3119               /* XXX: Try to work between problem where a stretch glyph on
3120                  a partially-visible bottom row will clear part of the
3121                  modeline, and another where list-buffers headers and similar
3122                  rows erroneously have visible_height set to 0.  Not sure
3123                  where this is coming from as other terms seem not to show. */
3124               r[i].size.height = min (s->height, s->row->visible_height);
3125             }
3127           [bgCol set];
3129           /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3130              overwriting cursor (usually when cursor on a tab) */
3131           if (s->hl == DRAW_CURSOR)
3132             {
3133               CGFloat x, width;
3135               x = r[i].origin.x;
3136               width = s->w->phys_cursor_width;
3137               r[i].size.width -= width;
3138               r[i].origin.x += width;
3140               NSRectFill (r[i]);
3142               /* Draw overlining, etc. on the cursor. */
3143               if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3144                 ns_draw_text_decoration (s, face, bgCol, width, x);
3145               else
3146                 ns_draw_text_decoration (s, face, fgCol, width, x);
3147             }
3148           else
3149             {
3150               NSRectFill (r[i]);
3151             }
3153           /* Draw overlining, etc. on the stretch glyph (or the part
3154              of the stretch glyph after the cursor). */
3155           ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3156                                    r[i].origin.x);
3157         }
3158       ns_unfocus (s->f);
3159       s->background_filled_p = 1;
3160     }
3164 static void
3165 ns_draw_glyph_string (struct glyph_string *s)
3166 /* --------------------------------------------------------------------------
3167       External (RIF): Main draw-text call.
3168    -------------------------------------------------------------------------- */
3170   /* TODO (optimize): focus for box and contents draw */
3171   NSRect r[2];
3172   int n;
3173   char box_drawn_p = 0;
3175   NSTRACE (ns_draw_glyph_string);
3177   if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3178     {
3179       int width;
3180       struct glyph_string *next;
3182       for (width = 0, next = s->next;
3183            next && width < s->right_overhang;
3184            width += next->width, next = next->next)
3185         if (next->first_glyph->type != IMAGE_GLYPH)
3186           {
3187             if (next->first_glyph->type != STRETCH_GLYPH)
3188               {
3189                 n = ns_get_glyph_string_clip_rect (s->next, r);
3190                 ns_focus (s->f, r, n);
3191                 ns_maybe_dumpglyphs_background (s->next, 1);
3192                 ns_unfocus (s->f);
3193               }
3194             else
3195               {
3196                 ns_dumpglyphs_stretch (s->next);
3197               }
3198             next->num_clips = 0;
3199           }
3200     }
3202   if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3203         && (s->first_glyph->type == CHAR_GLYPH
3204             || s->first_glyph->type == COMPOSITE_GLYPH))
3205     {
3206       n = ns_get_glyph_string_clip_rect (s, r);
3207       ns_focus (s->f, r, n);
3208       ns_maybe_dumpglyphs_background (s, 1);
3209       ns_dumpglyphs_box_or_relief (s);
3210       ns_unfocus (s->f);
3211       box_drawn_p = 1;
3212     }
3214   switch (s->first_glyph->type)
3215     {
3217     case IMAGE_GLYPH:
3218       n = ns_get_glyph_string_clip_rect (s, r);
3219       ns_focus (s->f, r, n);
3220       ns_dumpglyphs_image (s, r[0]);
3221       ns_unfocus (s->f);
3222       break;
3224     case STRETCH_GLYPH:
3225       ns_dumpglyphs_stretch (s);
3226       break;
3228     case CHAR_GLYPH:
3229     case COMPOSITE_GLYPH:
3230       n = ns_get_glyph_string_clip_rect (s, r);
3231       ns_focus (s->f, r, n);
3233       if (s->for_overlaps || (s->cmp_from > 0
3234                               && ! s->first_glyph->u.cmp.automatic))
3235         s->background_filled_p = 1;
3236       else
3237         ns_maybe_dumpglyphs_background
3238           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3240       ns_tmp_flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3241                     (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3242                      (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3243                       NS_DUMPGLYPH_NORMAL));
3244       ns_tmp_font = (struct nsfont_info *)s->face->font;
3245       if (ns_tmp_font == NULL)
3246           ns_tmp_font = (struct nsfont_info *)FRAME_FONT (s->f);
3248       if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3249         {
3250           unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3251           NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3252           NS_FACE_FOREGROUND (s->face) = tmp;
3253         }
3255       ns_tmp_font->font.driver->draw
3256         (s, 0, s->nchars, s->x, s->y,
3257          (ns_tmp_flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3258          || ns_tmp_flags == NS_DUMPGLYPH_MOUSEFACE);
3260       if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3261         {
3262           unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3263           NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3264           NS_FACE_FOREGROUND (s->face) = tmp;
3265         }
3267       ns_unfocus (s->f);
3268       break;
3270     case GLYPHLESS_GLYPH:
3271       n = ns_get_glyph_string_clip_rect (s, r);
3272       ns_focus (s->f, r, n);
3274       if (s->for_overlaps || (s->cmp_from > 0
3275                               && ! s->first_glyph->u.cmp.automatic))
3276         s->background_filled_p = 1;
3277       else
3278         ns_maybe_dumpglyphs_background
3279           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3280       /* ... */
3281       /* Not yet implemented.  */
3282       /* ... */
3283       ns_unfocus (s->f);
3284       break;
3286     default:
3287       emacs_abort ();
3288     }
3290   /* Draw box if not done already. */
3291   if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3292     {
3293       n = ns_get_glyph_string_clip_rect (s, r);
3294       ns_focus (s->f, r, n);
3295       ns_dumpglyphs_box_or_relief (s);
3296       ns_unfocus (s->f);
3297     }
3299   s->num_clips = 0;
3304 /* ==========================================================================
3306     Event loop
3308    ========================================================================== */
3311 static void
3312 ns_send_appdefined (int value)
3313 /* --------------------------------------------------------------------------
3314     Internal: post an appdefined event which EmacsApp-sendEvent will
3315               recognize and take as a command to halt the event loop.
3316    -------------------------------------------------------------------------- */
3318   /*NSTRACE (ns_send_appdefined); */
3320 #ifdef NS_IMPL_GNUSTEP
3321   // GNUStep needs postEvent to happen on the main thread.
3322   if (! [[NSThread currentThread] isMainThread])
3323     {
3324       EmacsApp *app = (EmacsApp *)NSApp;
3325       app->nextappdefined = value;
3326       [app performSelectorOnMainThread:@selector (sendFromMainThread:)
3327                             withObject:nil
3328                          waitUntilDone:YES];
3329       return;
3330     }
3331 #endif
3333   /* Only post this event if we haven't already posted one.  This will end
3334        the [NXApp run] main loop after having processed all events queued at
3335        this moment.  */
3336   if (send_appdefined)
3337     {
3338       NSEvent *nxev;
3340       /* We only need one NX_APPDEFINED event to stop NXApp from running.  */
3341       send_appdefined = NO;
3343       /* Don't need wakeup timer any more */
3344       if (timed_entry)
3345         {
3346           [timed_entry invalidate];
3347           [timed_entry release];
3348           timed_entry = nil;
3349         }
3351       nxev = [NSEvent otherEventWithType: NSApplicationDefined
3352                                 location: NSMakePoint (0, 0)
3353                            modifierFlags: 0
3354                                timestamp: 0
3355                             windowNumber: [[NSApp mainWindow] windowNumber]
3356                                  context: [NSApp context]
3357                                  subtype: 0
3358                                    data1: value
3359                                    data2: 0];
3361       /* Post an application defined event on the event queue.  When this is
3362          received the [NXApp run] will return, thus having processed all
3363          events which are currently queued.  */
3364       [NSApp postEvent: nxev atStart: NO];
3365     }
3368 #ifdef HAVE_NATIVE_FS
3369 static void
3370 check_native_fs ()
3372   Lisp_Object frame, tail;
3374   if (ns_last_use_native_fullscreen == ns_use_native_fullscreen)
3375     return;
3377   ns_last_use_native_fullscreen = ns_use_native_fullscreen;
3379   /* Clear the mouse-moved flag for every frame on this display.  */
3380   FOR_EACH_FRAME (tail, frame)
3381     {
3382       struct frame *f = XFRAME (frame);
3383       if (FRAME_NS_P (f))
3384         {
3385           EmacsView *view = FRAME_NS_VIEW (f);
3386           [view updateCollectionBehaviour];
3387         }
3388     }
3390 #endif
3392 /* GNUStep and OSX <= 10.4 does not have cancelTracking.  */
3393 #if defined (NS_IMPL_COCOA) && \
3394   MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
3395 const char *
3396 ns_get_pending_menu_title ()
3398   return menu_pending_title;
3401 /* Check if menu open should be cancelled or continued as normal.  */
3402 void
3403 ns_check_menu_open (NSMenu *menu)
3405   /* Click in menu bar? */
3406   NSArray *a = [[NSApp mainMenu] itemArray];
3407   int i;
3408   BOOL found = NO;
3409   for (i = 0; ! found && i < [a count]; i++)
3410     found = menu == [[a objectAtIndex:i] submenu];
3411   if (found)
3412     {
3413       if (menu_will_open_state == MENU_NONE && emacs_event)
3414         {
3415           NSEvent *theEvent = [NSApp currentEvent];
3416           struct frame *emacsframe = SELECTED_FRAME ();
3418           [menu cancelTracking];
3419           menu_will_open_state = MENU_PENDING;
3420           emacs_event->kind = MENU_BAR_ACTIVATE_EVENT;
3421           EV_TRAILER (theEvent);
3423           CGEventRef ourEvent = CGEventCreate (NULL);
3424           menu_mouse_point = CGEventGetLocation (ourEvent);
3425           CFRelease (ourEvent);
3426           xfree (menu_pending_title);
3427           menu_pending_title = xstrdup ([[menu title] UTF8String]);
3428         }
3429       else if (menu_will_open_state == MENU_OPENING)
3430         {
3431           menu_will_open_state = MENU_NONE;
3432         }
3433     }
3436 /* Redo saved menu click if state is MENU_PENDING.  */
3437 void
3438 ns_check_pending_open_menu ()
3440   if (menu_will_open_state == MENU_PENDING)
3441     {
3442       CGEventSourceRef source
3443         = CGEventSourceCreate (kCGEventSourceStateHIDSystemState);
3445       CGEventRef event = CGEventCreateMouseEvent (source,
3446                                                   kCGEventLeftMouseDown,
3447                                                   menu_mouse_point,
3448                                                   kCGMouseButtonLeft);
3449       CGEventSetType (event, kCGEventLeftMouseDown);
3450       CGEventPost (kCGHIDEventTap, event);
3451       CFRelease (event);
3452       CFRelease (source);
3454       menu_will_open_state = MENU_OPENING;
3455     }
3457 #endif /* NS_IMPL_COCOA) && >= MAC_OS_X_VERSION_10_5 */
3459 static int
3460 ns_read_socket (struct terminal *terminal, struct input_event *hold_quit)
3461 /* --------------------------------------------------------------------------
3462      External (hook): Post an event to ourself and keep reading events until
3463      we read it back again.  In effect process all events which were waiting.
3464      From 21+ we have to manage the event buffer ourselves.
3465    -------------------------------------------------------------------------- */
3467   struct input_event ev;
3468   int nevents;
3470 /* NSTRACE (ns_read_socket); */
3472 #ifdef HAVE_NATIVE_FS
3473   check_native_fs ();
3474 #endif
3476   if ([NSApp modalWindow] != nil)
3477     return -1;
3479   if (hold_event_q.nr > 0)
3480     {
3481       int i;
3482       for (i = 0; i < hold_event_q.nr; ++i)
3483         kbd_buffer_store_event_hold (&hold_event_q.q[i], hold_quit);
3484       hold_event_q.nr = 0;
3485       return i;
3486     }
3488   block_input ();
3489   n_emacs_events_pending = 0;
3490   EVENT_INIT (ev);
3491   emacs_event = &ev;
3492   q_event_ptr = hold_quit;
3494   /* we manage autorelease pools by allocate/reallocate each time around
3495      the loop; strict nesting is occasionally violated but seems not to
3496      matter.. earlier methods using full nesting caused major memory leaks */
3497   [outerpool release];
3498   outerpool = [[NSAutoreleasePool alloc] init];
3500   /* If have pending open-file requests, attend to the next one of those. */
3501   if (ns_pending_files && [ns_pending_files count] != 0
3502       && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3503     {
3504       [ns_pending_files removeObjectAtIndex: 0];
3505     }
3506   /* Deal with pending service requests. */
3507   else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3508     && [(EmacsApp *)
3509          NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3510                       withArg: [ns_pending_service_args objectAtIndex: 0]])
3511     {
3512       [ns_pending_service_names removeObjectAtIndex: 0];
3513       [ns_pending_service_args removeObjectAtIndex: 0];
3514     }
3515   else
3516     {
3517       /* Run and wait for events.  We must always send one NX_APPDEFINED event
3518          to ourself, otherwise [NXApp run] will never exit.  */
3519       send_appdefined = YES;
3520       ns_send_appdefined (-1);
3522       if (++apploopnr != 1)
3523         {
3524           emacs_abort ();
3525         }
3526       [NSApp run];
3527       --apploopnr;
3528     }
3530   nevents = n_emacs_events_pending;
3531   n_emacs_events_pending = 0;
3532   emacs_event = q_event_ptr = NULL;
3533   unblock_input ();
3535   return nevents;
3540 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3541            fd_set *exceptfds, EMACS_TIME *timeout, sigset_t *sigmask)
3542 /* --------------------------------------------------------------------------
3543      Replacement for select, checking for events
3544    -------------------------------------------------------------------------- */
3546   int result;
3547   int t, k, nr = 0;
3548   struct input_event event;
3549   char c;
3551 /*  NSTRACE (ns_select); */
3553 #ifdef HAVE_NATIVE_FS
3554   check_native_fs ();
3555 #endif
3557   if (hold_event_q.nr > 0)
3558     {
3559       /* We already have events pending. */
3560       raise (SIGIO);
3561       errno = EINTR;
3562       return -1;
3563     }
3565   for (k = 0; k < nfds+1; k++)
3566     {
3567       if (readfds && FD_ISSET(k, readfds)) ++nr;
3568       if (writefds && FD_ISSET(k, writefds)) ++nr;
3569     }
3571   if (NSApp == nil
3572       || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0))
3573     return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
3575   [outerpool release];
3576   outerpool = [[NSAutoreleasePool alloc] init];
3579   send_appdefined = YES;
3580   if (nr > 0)
3581     {
3582       pthread_mutex_lock (&select_mutex);
3583       select_nfds = nfds;
3584       select_valid = 0;
3585       if (readfds)
3586         {
3587           select_readfds = *readfds;
3588           select_valid += SELECT_HAVE_READ;
3589         }
3590       if (writefds)
3591         {
3592           select_writefds = *writefds;
3593           select_valid += SELECT_HAVE_WRITE;
3594         }
3596       if (timeout)
3597         {
3598           select_timeout = *timeout;
3599           select_valid += SELECT_HAVE_TMO;
3600         }
3602       pthread_mutex_unlock (&select_mutex);
3604       /* Inform fd_handler that select should be called */
3605       c = 'g';
3606       emacs_write_sig (selfds[1], &c, 1);
3607     }
3608   else if (nr == 0 && timeout)
3609     {
3610       /* No file descriptor, just a timeout, no need to wake fd_handler  */
3611       double time = EMACS_TIME_TO_DOUBLE (*timeout);
3612       timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3613                                                       target: NSApp
3614                                                     selector:
3615                                   @selector (timeout_handler:)
3616                                                     userInfo: 0
3617                                                      repeats: NO]
3618                       retain];
3619     }
3620   else /* No timeout and no file descriptors, can this happen?  */
3621     {
3622       /* Send appdefined so we exit from the loop */
3623       ns_send_appdefined (-1);
3624     }
3626   EVENT_INIT (event);
3627   block_input ();
3628   emacs_event = &event;
3629   if (++apploopnr != 1)
3630     {
3631       emacs_abort ();
3632     }
3633   [NSApp run];
3634   --apploopnr;
3635   emacs_event = NULL;
3636   if (nr > 0 && readfds)
3637     {
3638       c = 's';
3639       emacs_write_sig (selfds[1], &c, 1);
3640     }
3641   unblock_input ();
3643   t = last_appdefined_event_data;
3645   if (t != NO_APPDEFINED_DATA)
3646     {
3647       last_appdefined_event_data = NO_APPDEFINED_DATA;
3649       if (t == -2)
3650         {
3651           /* The NX_APPDEFINED event we received was a timeout. */
3652           result = 0;
3653         }
3654       else if (t == -1)
3655         {
3656           /* The NX_APPDEFINED event we received was the result of
3657              at least one real input event arriving.  */
3658           errno = EINTR;
3659           result = -1;
3660         }
3661       else
3662         {
3663           /* Received back from select () in fd_handler; copy the results */
3664           pthread_mutex_lock (&select_mutex);
3665           if (readfds) *readfds = select_readfds;
3666           if (writefds) *writefds = select_writefds;
3667           if (timeout) *timeout = select_timeout;
3668           pthread_mutex_unlock (&select_mutex);
3669           result = t;
3670         }
3671     }
3672   else
3673     {
3674       errno = EINTR;
3675       result = -1;
3676     }
3678   return result;
3683 /* ==========================================================================
3685     Scrollbar handling
3687    ========================================================================== */
3690 static void
3691 ns_set_vertical_scroll_bar (struct window *window,
3692                            int portion, int whole, int position)
3693 /* --------------------------------------------------------------------------
3694       External (hook): Update or add scrollbar
3695    -------------------------------------------------------------------------- */
3697   Lisp_Object win;
3698   NSRect r, v;
3699   struct frame *f = XFRAME (WINDOW_FRAME (window));
3700   EmacsView *view = FRAME_NS_VIEW (f);
3701   int window_y, window_height;
3702   int top, left, height, width, sb_width, sb_left;
3703   EmacsScroller *bar;
3704   BOOL fringe_extended_p;
3706   /* optimization; display engine sends WAY too many of these.. */
3707   if (!NILP (window->vertical_scroll_bar))
3708     {
3709       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3710       if ([bar checkSamePosition: position portion: portion whole: whole])
3711         {
3712           if (view->scrollbarsNeedingUpdate == 0)
3713             {
3714               if (!windows_or_buffers_changed)
3715                   return;
3716             }
3717           else
3718             view->scrollbarsNeedingUpdate--;
3719         }
3720     }
3722   NSTRACE (ns_set_vertical_scroll_bar);
3724   /* Get dimensions.  */
3725   window_box (window, -1, 0, &window_y, 0, &window_height);
3726   top = window_y;
3727   height = window_height;
3728   width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3729   left = WINDOW_SCROLL_BAR_AREA_X (window);
3731   /* allow for displaying a skinnier scrollbar than char area allotted */
3732   sb_width = (WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) > 0) ?
3733     WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) : width;
3734   sb_left = left;
3736   r = NSMakeRect (sb_left, top, sb_width, height);
3737   /* the parent view is flipped, so we need to flip y value */
3738   v = [view frame];
3739   r.origin.y = (v.size.height - r.size.height - r.origin.y);
3741   if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (window))
3742     fringe_extended_p = (WINDOW_LEFTMOST_P (window)
3743                          && WINDOW_LEFT_FRINGE_WIDTH (window)
3744                          && (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (window)
3745                              || WINDOW_LEFT_MARGIN_COLS (window) == 0));
3746   else
3747     fringe_extended_p = (WINDOW_RIGHTMOST_P (window)
3748                          && WINDOW_RIGHT_FRINGE_WIDTH (window)
3749                          && (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (window)
3750                              || WINDOW_RIGHT_MARGIN_COLS (window) == 0));
3752   XSETWINDOW (win, window);
3753   block_input ();
3755   /* we want at least 5 lines to display a scrollbar */
3756   if (WINDOW_TOTAL_LINES (window) < 5)
3757     {
3758       if (!NILP (window->vertical_scroll_bar))
3759         {
3760           bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3761           [bar removeFromSuperview];
3762           wset_vertical_scroll_bar (window, Qnil);
3763         }
3764       ns_clear_frame_area (f, sb_left, top, width, height);
3765       unblock_input ();
3766       return;
3767     }
3769   if (NILP (window->vertical_scroll_bar))
3770     {
3771       if (width > 0 && height > 0)
3772         {
3773           if (fringe_extended_p)
3774             ns_clear_frame_area (f, sb_left, top, sb_width, height);
3775           else
3776             ns_clear_frame_area (f, left, top, width, height);
3777         }
3779       bar = [[EmacsScroller alloc] initFrame: r window: win];
3780       wset_vertical_scroll_bar (window, make_save_ptr (bar));
3781     }
3782   else
3783     {
3784       NSRect oldRect;
3785       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3786       oldRect = [bar frame];
3787       r.size.width = oldRect.size.width;
3788       if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3789         {
3790           if (oldRect.origin.x != r.origin.x)
3791               ns_clear_frame_area (f, sb_left, top, width, height);
3792           [bar setFrame: r];
3793         }
3794     }
3796   [bar setPosition: position portion: portion whole: whole];
3797   unblock_input ();
3801 static void
3802 ns_condemn_scroll_bars (struct frame *f)
3803 /* --------------------------------------------------------------------------
3804      External (hook): arrange for all frame's scrollbars to be removed
3805      at next call to judge_scroll_bars, except for those redeemed.
3806    -------------------------------------------------------------------------- */
3808   int i;
3809   id view;
3810   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3812   NSTRACE (ns_condemn_scroll_bars);
3814   for (i =[subviews count]-1; i >= 0; i--)
3815     {
3816       view = [subviews objectAtIndex: i];
3817       if ([view isKindOfClass: [EmacsScroller class]])
3818         [view condemn];
3819     }
3823 static void
3824 ns_redeem_scroll_bar (struct window *window)
3825 /* --------------------------------------------------------------------------
3826      External (hook): arrange to spare this window's scrollbar
3827      at next call to judge_scroll_bars.
3828    -------------------------------------------------------------------------- */
3830   id bar;
3831   NSTRACE (ns_redeem_scroll_bar);
3832   if (!NILP (window->vertical_scroll_bar))
3833     {
3834       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3835       [bar reprieve];
3836     }
3840 static void
3841 ns_judge_scroll_bars (struct frame *f)
3842 /* --------------------------------------------------------------------------
3843      External (hook): destroy all scrollbars on frame that weren't
3844      redeemed after call to condemn_scroll_bars.
3845    -------------------------------------------------------------------------- */
3847   int i;
3848   id view;
3849   EmacsView *eview = FRAME_NS_VIEW (f);
3850   NSArray *subviews = [[eview superview] subviews];
3851   BOOL removed = NO;
3853   NSTRACE (ns_judge_scroll_bars);
3854   for (i = [subviews count]-1; i >= 0; --i)
3855     {
3856       view = [subviews objectAtIndex: i];
3857       if (![view isKindOfClass: [EmacsScroller class]]) continue;
3858       [view judge];
3859       removed = YES;
3860     }
3862   if (removed)
3863     [eview updateFrameSize: NO];
3866 /* ==========================================================================
3868     Initialization
3870    ========================================================================== */
3873 x_display_pixel_height (struct ns_display_info *dpyinfo)
3875   NSArray *screens = [NSScreen screens];
3876   NSEnumerator *enumerator = [screens objectEnumerator];
3877   NSScreen *screen;
3878   NSRect frame;
3880   frame = NSZeroRect;
3881   while ((screen = [enumerator nextObject]) != nil)
3882     frame = NSUnionRect (frame, [screen frame]);
3884   return NSHeight (frame);
3888 x_display_pixel_width (struct ns_display_info *dpyinfo)
3890   NSArray *screens = [NSScreen screens];
3891   NSEnumerator *enumerator = [screens objectEnumerator];
3892   NSScreen *screen;
3893   NSRect frame;
3895   frame = NSZeroRect;
3896   while ((screen = [enumerator nextObject]) != nil)
3897     frame = NSUnionRect (frame, [screen frame]);
3899   return NSWidth (frame);
3903 static Lisp_Object ns_string_to_lispmod (const char *s)
3904 /* --------------------------------------------------------------------------
3905      Convert modifier name to lisp symbol
3906    -------------------------------------------------------------------------- */
3908   if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
3909     return Qmeta;
3910   else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
3911     return Qsuper;
3912   else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
3913     return Qcontrol;
3914   else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
3915     return Qalt;
3916   else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
3917     return Qhyper;
3918   else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
3919     return Qnone;
3920   else
3921     return Qnil;
3925 static void
3926 ns_default (const char *parameter, Lisp_Object *result,
3927            Lisp_Object yesval, Lisp_Object noval,
3928            BOOL is_float, BOOL is_modstring)
3929 /* --------------------------------------------------------------------------
3930       Check a parameter value in user's preferences
3931    -------------------------------------------------------------------------- */
3933   const char *value = ns_get_defaults_value (parameter);
3935   if (value)
3936     {
3937       double f;
3938       char *pos;
3939       if (c_strcasecmp (value, "YES") == 0)
3940         *result = yesval;
3941       else if (c_strcasecmp (value, "NO") == 0)
3942         *result = noval;
3943       else if (is_float && (f = strtod (value, &pos), pos != value))
3944         *result = make_float (f);
3945       else if (is_modstring && value)
3946         *result = ns_string_to_lispmod (value);
3947       else fprintf (stderr,
3948                    "Bad value for default \"%s\": \"%s\"\n", parameter, value);
3949     }
3953 static void
3954 ns_initialize_display_info (struct ns_display_info *dpyinfo)
3955 /* --------------------------------------------------------------------------
3956       Initialize global info and storage for display.
3957    -------------------------------------------------------------------------- */
3959     NSScreen *screen = [NSScreen mainScreen];
3960     NSWindowDepth depth = [screen depth];
3961     Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
3963     dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
3964     dpyinfo->resy = 72.27;
3965     dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
3966                                                   NSColorSpaceFromDepth (depth)]
3967                 && ![NSCalibratedWhiteColorSpace isEqualToString:
3968                                                  NSColorSpaceFromDepth (depth)];
3969     dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
3970     dpyinfo->image_cache = make_image_cache ();
3971     dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
3972     dpyinfo->color_table->colors = NULL;
3973     dpyinfo->root_window = 42; /* a placeholder.. */
3975     hlinfo->mouse_face_mouse_frame = NULL;
3976     hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
3977     hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
3978     hlinfo->mouse_face_face_id = DEFAULT_FACE_ID;
3979     hlinfo->mouse_face_window = hlinfo->mouse_face_overlay = Qnil;
3980     hlinfo->mouse_face_hidden = 0;
3982     hlinfo->mouse_face_mouse_x = hlinfo->mouse_face_mouse_y = 0;
3983     hlinfo->mouse_face_defer = 0;
3985     dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
3987     dpyinfo->n_fonts = 0;
3988     dpyinfo->smallest_font_height = 1;
3989     dpyinfo->smallest_char_width = 1;
3993 /* This and next define (many of the) public functions in this file. */
3994 /* x_... are generic versions in xdisp.c that we, and other terms, get away
3995          with using despite presence in the "system dependent" redisplay
3996          interface.  In addition, many of the ns_ methods have code that is
3997          shared with all terms, indicating need for further refactoring. */
3998 extern frame_parm_handler ns_frame_parm_handlers[];
3999 static struct redisplay_interface ns_redisplay_interface =
4001   ns_frame_parm_handlers,
4002   x_produce_glyphs,
4003   x_write_glyphs,
4004   x_insert_glyphs,
4005   x_clear_end_of_line,
4006   ns_scroll_run,
4007   ns_after_update_window_line,
4008   ns_update_window_begin,
4009   ns_update_window_end,
4010   x_cursor_to,
4011   ns_flush,
4012   0, /* flush_display_optional */
4013   x_clear_window_mouse_face,
4014   x_get_glyph_overhangs,
4015   x_fix_overlapping_area,
4016   ns_draw_fringe_bitmap,
4017   0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
4018   0, /* destroy_fringe_bitmap */
4019   ns_compute_glyph_string_overhangs,
4020   ns_draw_glyph_string, /* interface to nsfont.m */
4021   ns_define_frame_cursor,
4022   ns_clear_frame_area,
4023   ns_draw_window_cursor,
4024   ns_draw_vertical_window_border,
4025   ns_shift_glyphs_for_insert
4029 static void
4030 ns_delete_display (struct ns_display_info *dpyinfo)
4032   /* TODO... */
4036 /* This function is called when the last frame on a display is deleted. */
4037 static void
4038 ns_delete_terminal (struct terminal *terminal)
4040   struct ns_display_info *dpyinfo = terminal->display_info.ns;
4042   /* Protect against recursive calls.  delete_frame in
4043      delete_terminal calls us back when it deletes our last frame.  */
4044   if (!terminal->name)
4045     return;
4047   block_input ();
4049   x_destroy_all_bitmaps (dpyinfo);
4050   ns_delete_display (dpyinfo);
4051   unblock_input ();
4055 static struct terminal *
4056 ns_create_terminal (struct ns_display_info *dpyinfo)
4057 /* --------------------------------------------------------------------------
4058       Set up use of NS before we make the first connection.
4059    -------------------------------------------------------------------------- */
4061   struct terminal *terminal;
4063   NSTRACE (ns_create_terminal);
4065   terminal = create_terminal ();
4067   terminal->type = output_ns;
4068   terminal->display_info.ns = dpyinfo;
4069   dpyinfo->terminal = terminal;
4071   terminal->rif = &ns_redisplay_interface;
4073   terminal->clear_frame_hook = ns_clear_frame;
4074   terminal->ins_del_lines_hook = 0; /* XXX vestigial? */
4075   terminal->delete_glyphs_hook = 0; /* XXX vestigial? */
4076   terminal->ring_bell_hook = ns_ring_bell;
4077   terminal->reset_terminal_modes_hook = ns_reset_terminal_modes;
4078   terminal->set_terminal_modes_hook = ns_set_terminal_modes;
4079   terminal->update_begin_hook = ns_update_begin;
4080   terminal->update_end_hook = ns_update_end;
4081   terminal->set_terminal_window_hook = NULL; /* XXX vestigial? */
4082   terminal->read_socket_hook = ns_read_socket;
4083   terminal->frame_up_to_date_hook = ns_frame_up_to_date;
4084   terminal->mouse_position_hook = ns_mouse_position;
4085   terminal->frame_rehighlight_hook = ns_frame_rehighlight;
4086   terminal->frame_raise_lower_hook = ns_frame_raise_lower;
4088   terminal->fullscreen_hook = ns_fullscreen_hook;
4090   terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
4091   terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
4092   terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
4093   terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
4095   terminal->delete_frame_hook = x_destroy_window;
4096   terminal->delete_terminal_hook = ns_delete_terminal;
4098   terminal->scroll_region_ok = 1;
4099   terminal->char_ins_del_ok = 1;
4100   terminal->line_ins_del_ok = 1;
4101   terminal->fast_clear_end_of_line = 1;
4102   terminal->memory_below_frame = 0;
4104   return terminal;
4108 struct ns_display_info *
4109 ns_term_init (Lisp_Object display_name)
4110 /* --------------------------------------------------------------------------
4111      Start the Application and get things rolling.
4112    -------------------------------------------------------------------------- */
4114   struct terminal *terminal;
4115   struct ns_display_info *dpyinfo;
4116   static int ns_initialized = 0;
4117   Lisp_Object tmp;
4119   if (ns_initialized) return x_display_list;
4120   ns_initialized = 1;
4122   NSTRACE (ns_term_init);
4124   [outerpool release];
4125   outerpool = [[NSAutoreleasePool alloc] init];
4127   /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4128   /*GSDebugAllocationActive (YES); */
4129   block_input ();
4131   baud_rate = 38400;
4132   Fset_input_interrupt_mode (Qnil);
4134   if (selfds[0] == -1)
4135     {
4136       if (emacs_pipe (selfds) != 0)
4137         {
4138           fprintf (stderr, "Failed to create pipe: %s\n",
4139                    emacs_strerror (errno));
4140           emacs_abort ();
4141         }
4143       fcntl (selfds[0], F_SETFL, O_NONBLOCK|fcntl (selfds[0], F_GETFL));
4144       FD_ZERO (&select_readfds);
4145       FD_ZERO (&select_writefds);
4146       pthread_mutex_init (&select_mutex, NULL);
4147     }
4149   ns_pending_files = [[NSMutableArray alloc] init];
4150   ns_pending_service_names = [[NSMutableArray alloc] init];
4151   ns_pending_service_args = [[NSMutableArray alloc] init];
4153 /* Start app and create the main menu, window, view.
4154      Needs to be here because ns_initialize_display_info () uses AppKit classes.
4155      The view will then ask the NSApp to stop and return to Emacs. */
4156   [EmacsApp sharedApplication];
4157   if (NSApp == nil)
4158     return NULL;
4159   [NSApp setDelegate: NSApp];
4161   /* Start the select thread.  */
4162   [NSThread detachNewThreadSelector:@selector (fd_handler:)
4163                            toTarget:NSApp
4164                          withObject:nil];
4166   /* debugging: log all notifications */
4167   /*   [[NSNotificationCenter defaultCenter] addObserver: NSApp
4168                                          selector: @selector (logNotification:)
4169                                              name: nil object: nil]; */
4171   dpyinfo = xzalloc (sizeof *dpyinfo);
4173   ns_initialize_display_info (dpyinfo);
4174   terminal = ns_create_terminal (dpyinfo);
4176   terminal->kboard = xmalloc (sizeof *terminal->kboard);
4177   init_kboard (terminal->kboard);
4178   kset_window_system (terminal->kboard, Qns);
4179   terminal->kboard->next_kboard = all_kboards;
4180   all_kboards = terminal->kboard;
4181   /* Don't let the initial kboard remain current longer than necessary.
4182      That would cause problems if a file loaded on startup tries to
4183      prompt in the mini-buffer.  */
4184   if (current_kboard == initial_kboard)
4185     current_kboard = terminal->kboard;
4186   terminal->kboard->reference_count++;
4188   dpyinfo->next = x_display_list;
4189   x_display_list = dpyinfo;
4191   /* Put it on ns_display_name_list */
4192   ns_display_name_list = Fcons (Fcons (display_name, Qnil),
4193                                 ns_display_name_list);
4194   dpyinfo->name_list_element = XCAR (ns_display_name_list);
4196   terminal->name = xstrdup (SSDATA (display_name));
4198   unblock_input ();
4200   if (!inhibit_x_resources)
4201     {
4202       ns_default ("GSFontAntiAlias", &ns_antialias_text,
4203                  Qt, Qnil, NO, NO);
4204       tmp = Qnil;
4205       /* this is a standard variable */
4206       ns_default ("AppleAntiAliasingThreshold", &tmp,
4207                  make_float (10.0), make_float (6.0), YES, NO);
4208       ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4209     }
4211   ns_selection_color = [[NSUserDefaults standardUserDefaults]
4212                          stringForKey: @"AppleHighlightColor"];
4213   if (ns_selection_color == nil)
4214     ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
4216   {
4217     NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4219     if ( cl == nil )
4220       {
4221         Lisp_Object color_file, color_map, color;
4222         unsigned long c;
4223         char *name;
4225         color_file = Fexpand_file_name (build_string ("rgb.txt"),
4226                          Fsymbol_value (intern ("data-directory")));
4228         color_map = Fx_load_color_file (color_file);
4229         if (NILP (color_map))
4230           fatal ("Could not read %s.\n", SDATA (color_file));
4232         cl = [[NSColorList alloc] initWithName: @"Emacs"];
4233         for ( ; CONSP (color_map); color_map = XCDR (color_map))
4234           {
4235             color = XCAR (color_map);
4236             name = SSDATA (XCAR (color));
4237             c = XINT (XCDR (color));
4238             [cl setColor:
4239                   [NSColor colorWithCalibratedRed: RED_FROM_ULONG (c) / 255.0
4240                                             green: GREEN_FROM_ULONG (c) / 255.0
4241                                              blue: BLUE_FROM_ULONG (c) / 255.0
4242                                             alpha: 1.0]
4243                   forKey: [NSString stringWithUTF8String: name]];
4244           }
4245         [cl writeToFile: nil];
4246       }
4247   }
4249   {
4250 #ifdef NS_IMPL_GNUSTEP
4251     Vwindow_system_version = build_string (gnustep_base_version);
4252 #else
4253     /*PSnextrelease (128, c); */
4254     char c[DBL_BUFSIZE_BOUND];
4255     int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4256     Vwindow_system_version = make_unibyte_string (c, len);
4257 #endif
4258   }
4260   delete_keyboard_wait_descriptor (0);
4262   ns_app_name = [[NSProcessInfo processInfo] processName];
4264 /* Set up OS X app menu */
4265 #ifdef NS_IMPL_COCOA
4266   {
4267     NSMenu *appMenu;
4268     NSMenuItem *item;
4269     /* set up the application menu */
4270     svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4271     [svcsMenu setAutoenablesItems: NO];
4272     appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4273     [appMenu setAutoenablesItems: NO];
4274     mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4275     dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4277     [appMenu insertItemWithTitle: @"About Emacs"
4278                           action: @selector (orderFrontStandardAboutPanel:)
4279                    keyEquivalent: @""
4280                          atIndex: 0];
4281     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4282     [appMenu insertItemWithTitle: @"Preferences..."
4283                           action: @selector (showPreferencesWindow:)
4284                    keyEquivalent: @","
4285                          atIndex: 2];
4286     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4287     item = [appMenu insertItemWithTitle: @"Services"
4288                                  action: @selector (menuDown:)
4289                           keyEquivalent: @""
4290                                 atIndex: 4];
4291     [appMenu setSubmenu: svcsMenu forItem: item];
4292     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4293     [appMenu insertItemWithTitle: @"Hide Emacs"
4294                           action: @selector (hide:)
4295                    keyEquivalent: @"h"
4296                          atIndex: 6];
4297     item =  [appMenu insertItemWithTitle: @"Hide Others"
4298                           action: @selector (hideOtherApplications:)
4299                    keyEquivalent: @"h"
4300                          atIndex: 7];
4301     [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4302     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4303     [appMenu insertItemWithTitle: @"Quit Emacs"
4304                           action: @selector (terminate:)
4305                    keyEquivalent: @"q"
4306                          atIndex: 9];
4308     item = [mainMenu insertItemWithTitle: ns_app_name
4309                                   action: @selector (menuDown:)
4310                            keyEquivalent: @""
4311                                  atIndex: 0];
4312     [mainMenu setSubmenu: appMenu forItem: item];
4313     [dockMenu insertItemWithTitle: @"New Frame"
4314                            action: @selector (newFrame:)
4315                     keyEquivalent: @""
4316                           atIndex: 0];
4318     [NSApp setMainMenu: mainMenu];
4319     [NSApp setAppleMenu: appMenu];
4320     [NSApp setServicesMenu: svcsMenu];
4321     /* Needed at least on Cocoa, to get dock menu to show windows */
4322     [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4324     [[NSNotificationCenter defaultCenter]
4325       addObserver: mainMenu
4326          selector: @selector (trackingNotification:)
4327              name: NSMenuDidBeginTrackingNotification object: mainMenu];
4328     [[NSNotificationCenter defaultCenter]
4329       addObserver: mainMenu
4330          selector: @selector (trackingNotification:)
4331              name: NSMenuDidEndTrackingNotification object: mainMenu];
4332   }
4333 #endif /* MAC OS X menu setup */
4335   /* Register our external input/output types, used for determining
4336      applicable services and also drag/drop eligibility. */
4337   ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
4338   ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
4339                       retain];
4340   ns_drag_types = [[NSArray arrayWithObjects:
4341                             NSStringPboardType,
4342                             NSTabularTextPboardType,
4343                             NSFilenamesPboardType,
4344                             NSURLPboardType,
4345                             NSColorPboardType,
4346                             NSFontPboardType, nil] retain];
4348   /* If fullscreen is in init/default-frame-alist, focus isn't set
4349      right for fullscreen windows, so set this.  */
4350   [NSApp activateIgnoringOtherApps:YES];
4352   [NSApp run];
4353   ns_do_open_file = YES;
4355 #ifdef NS_IMPL_GNUSTEP
4356   /* GNUstep steals SIGCHLD for use in NSTask, but we don't use NSTask.
4357      We must re-catch it so subprocess works.  */
4358   catch_child_signal ();
4359 #endif
4360   return dpyinfo;
4364 void
4365 ns_term_shutdown (int sig)
4367   [[NSUserDefaults standardUserDefaults] synchronize];
4369   /* code not reached in emacs.c after this is called by shut_down_emacs: */
4370   if (STRINGP (Vauto_save_list_file_name))
4371     unlink (SSDATA (Vauto_save_list_file_name));
4373   if (sig == 0 || sig == SIGTERM)
4374     {
4375       [NSApp terminate: NSApp];
4376     }
4377   else // force a stack trace to happen
4378     {
4379       emacs_abort ();
4380     }
4384 /* ==========================================================================
4386     EmacsApp implementation
4388    ========================================================================== */
4391 @implementation EmacsApp
4393 - (void)logNotification: (NSNotification *)notification
4395   const char *name = [[notification name] UTF8String];
4396   if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4397       && !strstr (name, "WindowNumber"))
4398     NSLog (@"notification: '%@'", [notification name]);
4402 - (void)sendEvent: (NSEvent *)theEvent
4403 /* --------------------------------------------------------------------------
4404      Called when NSApp is running for each event received.  Used to stop
4405      the loop when we choose, since there's no way to just run one iteration.
4406    -------------------------------------------------------------------------- */
4408   int type = [theEvent type];
4409   NSWindow *window = [theEvent window];
4411 /*  NSTRACE (sendEvent); */
4412 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4414 #ifdef NS_IMPL_GNUSTEP
4415   // Keyboard events aren't propagated to file dialogs for some reason.
4416   if ([NSApp modalWindow] != nil &&
4417       (type == NSKeyDown || type == NSKeyUp || type == NSFlagsChanged))
4418     {
4419       [[NSApp modalWindow] sendEvent: theEvent];
4420       return;
4421     }
4422 #endif
4424   if (type == NSApplicationDefined)
4425     {
4426       switch ([theEvent data2])
4427         {
4428 #ifdef NS_IMPL_COCOA
4429         case NSAPP_DATA2_RUNASSCRIPT:
4430           ns_run_ascript ();
4431           [self stop: self];
4432           return;
4433 #endif
4434         case NSAPP_DATA2_RUNFILEDIALOG:
4435           ns_run_file_dialog ();
4436           [self stop: self];
4437           return;
4438         }
4439     }
4441   if (type == NSCursorUpdate && window == nil)
4442     {
4443       fprintf (stderr, "Dropping external cursor update event.\n");
4444       return;
4445     }
4447   if (type == NSApplicationDefined)
4448     {
4449       /* Events posted by ns_send_appdefined interrupt the run loop here.
4450          But, if a modal window is up, an appdefined can still come through,
4451          (e.g., from a makeKeyWindow event) but stopping self also stops the
4452          modal loop. Just defer it until later. */
4453       if ([NSApp modalWindow] == nil)
4454         {
4455           last_appdefined_event_data = [theEvent data1];
4456           [self stop: self];
4457         }
4458       else
4459         {
4460           send_appdefined = YES;
4461         }
4462     }
4465 #ifdef NS_IMPL_COCOA
4466   /* If no dialog and none of our frames have focus and it is a move, skip it.
4467      It is a mouse move in an auxiliary menu, i.e. on the top right on OSX,
4468      such as Wifi, sound, date or similar.
4469      This prevents "spooky" highlighting in the frame under the menu.  */
4470   if (type == NSMouseMoved && [NSApp modalWindow] == nil)
4471     {
4472       struct ns_display_info *di;
4473       BOOL has_focus = NO;
4474       for (di = x_display_list; ! has_focus && di; di = di->next)
4475         has_focus = di->x_focus_frame != 0;
4476       if (! has_focus)
4477         return;
4478     }
4479 #endif
4481   [super sendEvent: theEvent];
4485 - (void)showPreferencesWindow: (id)sender
4487   struct frame *emacsframe = SELECTED_FRAME ();
4488   NSEvent *theEvent = [NSApp currentEvent];
4490   if (!emacs_event)
4491     return;
4492   emacs_event->kind = NS_NONKEY_EVENT;
4493   emacs_event->code = KEY_NS_SHOW_PREFS;
4494   emacs_event->modifiers = 0;
4495   EV_TRAILER (theEvent);
4499 - (void)newFrame: (id)sender
4501   struct frame *emacsframe = SELECTED_FRAME ();
4502   NSEvent *theEvent = [NSApp currentEvent];
4504   if (!emacs_event)
4505     return;
4506   emacs_event->kind = NS_NONKEY_EVENT;
4507   emacs_event->code = KEY_NS_NEW_FRAME;
4508   emacs_event->modifiers = 0;
4509   EV_TRAILER (theEvent);
4513 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4514 - (BOOL) openFile: (NSString *)fileName
4516   struct frame *emacsframe = SELECTED_FRAME ();
4517   NSEvent *theEvent = [NSApp currentEvent];
4519   if (!emacs_event)
4520     return NO;
4522   emacs_event->kind = NS_NONKEY_EVENT;
4523   emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4524   ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4525   ns_input_line = Qnil; /* can be start or cons start,end */
4526   emacs_event->modifiers =0;
4527   EV_TRAILER (theEvent);
4529   return YES;
4533 /* **************************************************************************
4535       EmacsApp delegate implementation
4537    ************************************************************************** */
4539 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4540 /* --------------------------------------------------------------------------
4541      When application is loaded, terminate event loop in ns_term_init
4542    -------------------------------------------------------------------------- */
4544   NSTRACE (applicationDidFinishLaunching);
4545   [NSApp setServicesProvider: NSApp];
4546   ns_send_appdefined (-2);
4550 /* Termination sequences:
4551     C-x C-c:
4552     Cmd-Q:
4553     MenuBar | File | Exit:
4554     Select Quit from App menubar:
4555         -terminate
4556         KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4557         ns_term_shutdown()
4559     Select Quit from Dock menu:
4560     Logout attempt:
4561         -appShouldTerminate
4562           Cancel -> Nothing else
4563           Accept ->
4565           -terminate
4566           KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4567           ns_term_shutdown()
4571 - (void) terminate: (id)sender
4573   struct frame *emacsframe = SELECTED_FRAME ();
4575   if (!emacs_event)
4576     return;
4578   emacs_event->kind = NS_NONKEY_EVENT;
4579   emacs_event->code = KEY_NS_POWER_OFF;
4580   emacs_event->arg = Qt; /* mark as non-key event */
4581   EV_TRAILER ((id)nil);
4585 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4587   int ret;
4589   if (NILP (ns_confirm_quit)) //   || ns_shutdown_properly  --> TO DO
4590     return NSTerminateNow;
4592     ret = NSRunAlertPanel(ns_app_name,
4593                           @"Exit requested.  Would you like to Save Buffers and Exit, or Cancel the request?",
4594                           @"Save Buffers and Exit", @"Cancel", nil);
4596     if (ret == NSAlertDefaultReturn)
4597         return NSTerminateNow;
4598     else if (ret == NSAlertAlternateReturn)
4599         return NSTerminateCancel;
4600     return NSTerminateNow;  /* just in case */
4603 static int
4604 not_in_argv (NSString *arg)
4606   int k;
4607   const char *a = [arg UTF8String];
4608   for (k = 1; k < initial_argc; ++k)
4609     if (strcmp (a, initial_argv[k]) == 0) return 0;
4610   return 1;
4613 /*   Notification from the Workspace to open a file */
4614 - (BOOL)application: sender openFile: (NSString *)file
4616   if (ns_do_open_file || not_in_argv (file))
4617     [ns_pending_files addObject: file];
4618   return YES;
4622 /*   Open a file as a temporary file */
4623 - (BOOL)application: sender openTempFile: (NSString *)file
4625   if (ns_do_open_file || not_in_argv (file))
4626     [ns_pending_files addObject: file];
4627   return YES;
4631 /*   Notification from the Workspace to open a file noninteractively (?) */
4632 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4634   if (ns_do_open_file || not_in_argv (file))
4635     [ns_pending_files addObject: file];
4636   return YES;
4639 /*   Notification from the Workspace to open multiple files */
4640 - (void)application: sender openFiles: (NSArray *)fileList
4642   NSEnumerator *files = [fileList objectEnumerator];
4643   NSString *file;
4644   /* Don't open files from the command line unconditionally,
4645      Cocoa parses the command line wrong, --option value tries to open value
4646      if --option is the last option.  */
4647   while ((file = [files nextObject]) != nil)
4648     if (ns_do_open_file || not_in_argv (file))
4649       [ns_pending_files addObject: file];
4651   [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4656 /* Handle dock menu requests.  */
4657 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4659   return dockMenu;
4663 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4664 - (void)applicationWillBecomeActive: (NSNotification *)notification
4666   //ns_app_active=YES;
4668 - (void)applicationDidBecomeActive: (NSNotification *)notification
4670   NSTRACE (applicationDidBecomeActive);
4672   //ns_app_active=YES;
4674   ns_update_auto_hide_menu_bar ();
4675   // No constraining takes place when the application is not active.
4676   ns_constrain_all_frames ();
4678 - (void)applicationDidResignActive: (NSNotification *)notification
4680   //ns_app_active=NO;
4681   ns_send_appdefined (-1);
4686 /* ==========================================================================
4688     EmacsApp aux handlers for managing event loop
4690    ========================================================================== */
4693 - (void)timeout_handler: (NSTimer *)timedEntry
4694 /* --------------------------------------------------------------------------
4695      The timeout specified to ns_select has passed.
4696    -------------------------------------------------------------------------- */
4698   /*NSTRACE (timeout_handler); */
4699   ns_send_appdefined (-2);
4702 #ifdef NS_IMPL_GNUSTEP
4703 - (void)sendFromMainThread:(id)unused
4705   ns_send_appdefined (nextappdefined);
4707 #endif
4709 - (void)fd_handler:(id)unused
4710 /* --------------------------------------------------------------------------
4711      Check data waiting on file descriptors and terminate if so
4712    -------------------------------------------------------------------------- */
4714   int result;
4715   int waiting = 1, nfds;
4716   char c;
4718   SELECT_TYPE readfds, writefds, *wfds;
4719   EMACS_TIME timeout, *tmo;
4720   NSAutoreleasePool *pool = nil;
4722   /* NSTRACE (fd_handler); */
4724   for (;;)
4725     {
4726       [pool release];
4727       pool = [[NSAutoreleasePool alloc] init];
4729       if (waiting)
4730         {
4731           SELECT_TYPE fds;
4732           FD_ZERO (&fds);
4733           FD_SET (selfds[0], &fds);
4734           result = select (selfds[0]+1, &fds, NULL, NULL, NULL);
4735           if (result > 0 && read (selfds[0], &c, 1) == 1 && c == 'g')
4736             waiting = 0;
4737         }
4738       else
4739         {
4740           pthread_mutex_lock (&select_mutex);
4741           nfds = select_nfds;
4743           if (select_valid & SELECT_HAVE_READ)
4744             readfds = select_readfds;
4745           else
4746             FD_ZERO (&readfds);
4748           if (select_valid & SELECT_HAVE_WRITE)
4749             {
4750               writefds = select_writefds;
4751               wfds = &writefds;
4752             }
4753           else
4754             wfds = NULL;
4755           if (select_valid & SELECT_HAVE_TMO)
4756             {
4757               timeout = select_timeout;
4758               tmo = &timeout;
4759             }
4760           else
4761             tmo = NULL;
4763           pthread_mutex_unlock (&select_mutex);
4765           FD_SET (selfds[0], &readfds);
4766           if (selfds[0] >= nfds) nfds = selfds[0]+1;
4768           result = pselect (nfds, &readfds, wfds, NULL, tmo, NULL);
4770           if (result == 0)
4771             ns_send_appdefined (-2);
4772           else if (result > 0)
4773             {
4774               if (FD_ISSET (selfds[0], &readfds))
4775                 {
4776                   if (read (selfds[0], &c, 1) == 1 && c == 's')
4777                     waiting = 1;
4778                 }
4779               else
4780                 {
4781                   pthread_mutex_lock (&select_mutex);
4782                   if (select_valid & SELECT_HAVE_READ)
4783                     select_readfds = readfds;
4784                   if (select_valid & SELECT_HAVE_WRITE)
4785                     select_writefds = writefds;
4786                   if (select_valid & SELECT_HAVE_TMO)
4787                     select_timeout = timeout;
4788                   pthread_mutex_unlock (&select_mutex);
4790                   ns_send_appdefined (result);
4791                 }
4792             }
4793           waiting = 1;
4794         }
4795     }
4800 /* ==========================================================================
4802     Service provision
4804    ========================================================================== */
4806 /* called from system: queue for next pass through event loop */
4807 - (void)requestService: (NSPasteboard *)pboard
4808               userData: (NSString *)userData
4809                  error: (NSString **)error
4811   [ns_pending_service_names addObject: userData];
4812   [ns_pending_service_args addObject: [NSString stringWithUTF8String:
4813       SSDATA (ns_string_from_pasteboard (pboard))]];
4817 /* called from ns_read_socket to clear queue */
4818 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
4820   struct frame *emacsframe = SELECTED_FRAME ();
4821   NSEvent *theEvent = [NSApp currentEvent];
4823   if (!emacs_event)
4824     return NO;
4826   emacs_event->kind = NS_NONKEY_EVENT;
4827   emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
4828   ns_input_spi_name = build_string ([name UTF8String]);
4829   ns_input_spi_arg = build_string ([arg UTF8String]);
4830   emacs_event->modifiers = EV_MODIFIERS (theEvent);
4831   EV_TRAILER (theEvent);
4833   return YES;
4837 @end  /* EmacsApp */
4841 /* ==========================================================================
4843     EmacsView implementation
4845    ========================================================================== */
4848 @implementation EmacsView
4850 /* needed to inform when window closed from LISP */
4851 - (void) setWindowClosing: (BOOL)closing
4853   windowClosing = closing;
4857 - (void)dealloc
4859   NSTRACE (EmacsView_dealloc);
4860   [toolbar release];
4861   if (fs_state == FULLSCREEN_BOTH)
4862     [nonfs_window release];
4863   [super dealloc];
4867 /* called on font panel selection */
4868 - (void)changeFont: (id)sender
4870   NSEvent *e =[[self window] currentEvent];
4871   struct face *face =FRAME_DEFAULT_FACE (emacsframe);
4872   id newFont;
4873   CGFloat size;
4875   NSTRACE (changeFont);
4876   if (!emacs_event)
4877     return;
4879   if ((newFont = [sender convertFont:
4880                            ((struct nsfont_info *)face->font)->nsfont]))
4881     {
4882       SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
4884       emacs_event->kind = NS_NONKEY_EVENT;
4885       emacs_event->modifiers = 0;
4886       emacs_event->code = KEY_NS_CHANGE_FONT;
4888       size = [newFont pointSize];
4889       ns_input_fontsize = make_number (lrint (size));
4890       ns_input_font = build_string ([[newFont familyName] UTF8String]);
4891       EV_TRAILER (e);
4892     }
4896 - (BOOL)acceptsFirstResponder
4898   NSTRACE (acceptsFirstResponder);
4899   return YES;
4903 - (void)resetCursorRects
4905   NSRect visible = [self visibleRect];
4906   NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
4907   NSTRACE (resetCursorRects);
4909   if (currentCursor == nil)
4910     currentCursor = [NSCursor arrowCursor];
4912   if (!NSIsEmptyRect (visible))
4913     [self addCursorRect: visible cursor: currentCursor];
4914   [currentCursor setOnMouseEntered: YES];
4919 /*****************************************************************************/
4920 /* Keyboard handling. */
4921 #define NS_KEYLOG 0
4923 - (void)keyDown: (NSEvent *)theEvent
4925   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
4926   int code;
4927   unsigned fnKeysym = 0;
4928   static NSMutableArray *nsEvArray;
4929 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
4930   static BOOL firstTime = YES;
4931 #endif
4932   int left_is_none;
4933   unsigned int flags = [theEvent modifierFlags];
4935   NSTRACE (keyDown);
4937   /* Rhapsody and OS X give up and down events for the arrow keys */
4938   if (ns_fake_keydown == YES)
4939     ns_fake_keydown = NO;
4940   else if ([theEvent type] != NSKeyDown)
4941     return;
4943   if (!emacs_event)
4944     return;
4946  if (![[self window] isKeyWindow]
4947      && [[theEvent window] isKindOfClass: [EmacsWindow class]]
4948      /* we must avoid an infinite loop here. */
4949      && (EmacsView *)[[theEvent window] delegate] != self)
4950    {
4951      /* XXX: There is an occasional condition in which, when Emacs display
4952          updates a different frame from the current one, and temporarily
4953          selects it, then processes some interrupt-driven input
4954          (dispnew.c:3878), OS will send the event to the correct NSWindow, but
4955          for some reason that window has its first responder set to the NSView
4956          most recently updated (I guess), which is not the correct one. */
4957      [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
4958      return;
4959    }
4961   if (nsEvArray == nil)
4962     nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
4964   [NSCursor setHiddenUntilMouseMoves: YES];
4966   if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
4967     {
4968       clear_mouse_face (hlinfo);
4969       hlinfo->mouse_face_hidden = 1;
4970     }
4972   if (!processingCompose)
4973     {
4974       /* When using screen sharing, no left or right information is sent,
4975          so use Left key in those cases.  */
4976       int is_left_key, is_right_key;
4978       code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
4979         0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
4981       /* (Carbon way: [theEvent keyCode]) */
4983       /* is it a "function key"? */
4984       fnKeysym = (code < 0x00ff && (flags&NSNumericPadKeyMask))
4985         ? ns_convert_key ([theEvent keyCode] | NSNumericPadKeyMask)
4986         : ns_convert_key (code);
4988       if (fnKeysym)
4989         {
4990           /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
4991              because Emacs treats Delete and KP-Delete same (in simple.el). */
4992           if ((fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
4993 #ifdef NS_IMPL_GNUSTEP
4994               /*  GNUstep uses incompatible keycodes, even for those that are
4995                   supposed to be hardware independent.  Just check for delete.
4996                   Keypad delete does not have keysym 0xFFFF.
4997                   See http://savannah.gnu.org/bugs/?25395
4998               */
4999               || (fnKeysym == 0xFFFF && code == 127)
5000 #endif
5001             )
5002             code = 0xFF08; /* backspace */
5003           else
5004             code = fnKeysym;
5005         }
5007       /* are there modifiers? */
5008       emacs_event->modifiers = 0;
5010       if (flags & NSHelpKeyMask)
5011           emacs_event->modifiers |= hyper_modifier;
5013       if (flags & NSShiftKeyMask)
5014         emacs_event->modifiers |= shift_modifier;
5016       is_right_key = (flags & NSRightCommandKeyMask) == NSRightCommandKeyMask;
5017       is_left_key = (flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask
5018         || (! is_right_key && (flags & NSCommandKeyMask) == NSCommandKeyMask);
5020       if (is_right_key)
5021         emacs_event->modifiers |= parse_solitary_modifier
5022           (EQ (ns_right_command_modifier, Qleft)
5023            ? ns_command_modifier
5024            : ns_right_command_modifier);
5026       if (is_left_key)
5027         {
5028           emacs_event->modifiers |= parse_solitary_modifier
5029             (ns_command_modifier);
5031           /* if super (default), take input manager's word so things like
5032              dvorak / qwerty layout work */
5033           if (EQ (ns_command_modifier, Qsuper)
5034               && !fnKeysym
5035               && [[theEvent characters] length] != 0)
5036             {
5037               /* XXX: the code we get will be unshifted, so if we have
5038                  a shift modifier, must convert ourselves */
5039               if (!(flags & NSShiftKeyMask))
5040                 code = [[theEvent characters] characterAtIndex: 0];
5041 #if 0
5042               /* this is ugly and also requires linking w/Carbon framework
5043                  (for LMGetKbdType) so for now leave this rare (?) case
5044                  undealt with.. in future look into CGEvent methods */
5045               else
5046                 {
5047                   long smv = GetScriptManagerVariable (smKeyScript);
5048                   Handle uchrHandle = GetResource
5049                     ('uchr', GetScriptVariable (smv, smScriptKeys));
5050                   UInt32 dummy = 0;
5051                   UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
5052                                  [[theEvent characters] characterAtIndex: 0],
5053                                  kUCKeyActionDisplay,
5054                                  (flags & ~NSCommandKeyMask) >> 8,
5055                                  LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
5056                                  &dummy, 1, &dummy, &code);
5057                   code &= 0xFF;
5058                 }
5059 #endif
5060             }
5061         }
5063       is_right_key = (flags & NSRightControlKeyMask) == NSRightControlKeyMask;
5064       is_left_key = (flags & NSLeftControlKeyMask) == NSLeftControlKeyMask
5065         || (! is_right_key && (flags & NSControlKeyMask) == NSControlKeyMask);
5067       if (is_right_key)
5068           emacs_event->modifiers |= parse_solitary_modifier
5069               (EQ (ns_right_control_modifier, Qleft)
5070                ? ns_control_modifier
5071                : ns_right_control_modifier);
5073       if (is_left_key)
5074         emacs_event->modifiers |= parse_solitary_modifier
5075           (ns_control_modifier);
5077       if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
5078           emacs_event->modifiers |=
5079             parse_solitary_modifier (ns_function_modifier);
5081       left_is_none = NILP (ns_alternate_modifier)
5082         || EQ (ns_alternate_modifier, Qnone);
5084       is_right_key = (flags & NSRightAlternateKeyMask)
5085         == NSRightAlternateKeyMask;
5086       is_left_key = (flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask
5087         || (! is_right_key
5088             && (flags & NSAlternateKeyMask) == NSAlternateKeyMask);
5090       if (is_right_key)
5091         {
5092           if ((NILP (ns_right_alternate_modifier)
5093                || EQ (ns_right_alternate_modifier, Qnone)
5094                || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
5095               && !fnKeysym)
5096             {   /* accept pre-interp alt comb */
5097               if ([[theEvent characters] length] > 0)
5098                 code = [[theEvent characters] characterAtIndex: 0];
5099               /*HACK: clear lone shift modifier to stop next if from firing */
5100               if (emacs_event->modifiers == shift_modifier)
5101                 emacs_event->modifiers = 0;
5102             }
5103           else
5104             emacs_event->modifiers |= parse_solitary_modifier
5105               (EQ (ns_right_alternate_modifier, Qleft)
5106                ? ns_alternate_modifier
5107                : ns_right_alternate_modifier);
5108         }
5110       if (is_left_key) /* default = meta */
5111         {
5112           if (left_is_none && !fnKeysym)
5113             {   /* accept pre-interp alt comb */
5114               if ([[theEvent characters] length] > 0)
5115                 code = [[theEvent characters] characterAtIndex: 0];
5116               /*HACK: clear lone shift modifier to stop next if from firing */
5117               if (emacs_event->modifiers == shift_modifier)
5118                 emacs_event->modifiers = 0;
5119             }
5120           else
5121               emacs_event->modifiers |=
5122                 parse_solitary_modifier (ns_alternate_modifier);
5123         }
5125   if (NS_KEYLOG)
5126     fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
5127              code, fnKeysym, flags, emacs_event->modifiers);
5129       /* if it was a function key or had modifiers, pass it directly to emacs */
5130       if (fnKeysym || (emacs_event->modifiers
5131                        && (emacs_event->modifiers != shift_modifier)
5132                        && [[theEvent charactersIgnoringModifiers] length] > 0))
5133 /*[[theEvent characters] length] */
5134         {
5135           emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5136           if (code < 0x20)
5137             code |= (1<<28)|(3<<16);
5138           else if (code == 0x7f)
5139             code |= (1<<28)|(3<<16);
5140           else if (!fnKeysym)
5141             emacs_event->kind = code > 0xFF
5142               ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5144           emacs_event->code = code;
5145           EV_TRAILER (theEvent);
5146           processingCompose = NO;
5147           return;
5148         }
5149     }
5152 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
5153   /* if we get here we should send the key for input manager processing */
5154   /* Disable warning, there is nothing a user can do about it anyway, and
5155      it does not seem to matter.  */
5156 #if 0
5157   if (firstTime && [[NSInputManager currentInputManager]
5158                      wantsToDelayTextChangeNotifications] == NO)
5159     fprintf (stderr,
5160           "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
5161 #endif
5162   firstTime = NO;
5163 #endif
5164   if (NS_KEYLOG && !processingCompose)
5165     fprintf (stderr, "keyDown: Begin compose sequence.\n");
5167   processingCompose = YES;
5168   [nsEvArray addObject: theEvent];
5169   [self interpretKeyEvents: nsEvArray];
5170   [nsEvArray removeObject: theEvent];
5174 #ifdef NS_IMPL_COCOA
5175 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
5176    decided not to send key-down for.
5177    See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
5178    This only applies on Tiger and earlier.
5179    If it matches one of these, send it on to keyDown. */
5180 -(void)keyUp: (NSEvent *)theEvent
5182   int flags = [theEvent modifierFlags];
5183   int code = [theEvent keyCode];
5184   if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
5185       code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
5186     {
5187       if (NS_KEYLOG)
5188         fprintf (stderr, "keyUp: passed test");
5189       ns_fake_keydown = YES;
5190       [self keyDown: theEvent];
5191     }
5193 #endif
5196 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
5199 /* <NSTextInput>: called when done composing;
5200    NOTE: also called when we delete over working text, followed immed.
5201          by doCommandBySelector: deleteBackward: */
5202 - (void)insertText: (id)aString
5204   int code;
5205   int len = [(NSString *)aString length];
5206   int i;
5208   if (NS_KEYLOG)
5209     NSLog (@"insertText '%@'\tlen = %d", aString, len);
5210   processingCompose = NO;
5212   if (!emacs_event)
5213     return;
5215   /* first, clear any working text */
5216   if (workingText != nil)
5217     [self deleteWorkingText];
5219   /* now insert the string as keystrokes */
5220   for (i =0; i<len; i++)
5221     {
5222       code = [aString characterAtIndex: i];
5223       /* TODO: still need this? */
5224       if (code == 0x2DC)
5225         code = '~'; /* 0x7E */
5226       if (code != 32) /* Space */
5227         emacs_event->modifiers = 0;
5228       emacs_event->kind
5229         = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5230       emacs_event->code = code;
5231       EV_TRAILER ((id)nil);
5232     }
5236 /* <NSTextInput>: inserts display of composing characters */
5237 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
5239   NSString *str = [aString respondsToSelector: @selector (string)] ?
5240     [aString string] : aString;
5241   if (NS_KEYLOG)
5242     NSLog (@"setMarkedText '%@' len =%d range %d from %d", str, [str length],
5243            selRange.length, selRange.location);
5245   if (workingText != nil)
5246     [self deleteWorkingText];
5247   if ([str length] == 0)
5248     return;
5250   if (!emacs_event)
5251     return;
5253   processingCompose = YES;
5254   workingText = [str copy];
5255   ns_working_text = build_string ([workingText UTF8String]);
5257   emacs_event->kind = NS_TEXT_EVENT;
5258   emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
5259   EV_TRAILER ((id)nil);
5263 /* delete display of composing characters [not in <NSTextInput>] */
5264 - (void)deleteWorkingText
5266   if (workingText == nil)
5267     return;
5268   if (NS_KEYLOG)
5269     NSLog(@"deleteWorkingText len =%d\n", [workingText length]);
5270   [workingText release];
5271   workingText = nil;
5272   processingCompose = NO;
5274   if (!emacs_event)
5275     return;
5277   emacs_event->kind = NS_TEXT_EVENT;
5278   emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
5279   EV_TRAILER ((id)nil);
5283 - (BOOL)hasMarkedText
5285   return workingText != nil;
5289 - (NSRange)markedRange
5291   NSRange rng = workingText != nil
5292     ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
5293   if (NS_KEYLOG)
5294     NSLog (@"markedRange request");
5295   return rng;
5299 - (void)unmarkText
5301   if (NS_KEYLOG)
5302     NSLog (@"unmark (accept) text");
5303   [self deleteWorkingText];
5304   processingCompose = NO;
5308 /* used to position char selection windows, etc. */
5309 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
5311   NSRect rect;
5312   NSPoint pt;
5313   struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
5314   if (NS_KEYLOG)
5315     NSLog (@"firstRectForCharRange request");
5317   rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
5318   rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
5319   pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
5320   pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
5321                                        +FRAME_LINE_HEIGHT (emacsframe));
5323   pt = [self convertPoint: pt toView: nil];
5324   pt = [[self window] convertBaseToScreen: pt];
5325   rect.origin = pt;
5326   return rect;
5330 - (NSInteger)conversationIdentifier
5332   return (NSInteger)self;
5336 - (void)doCommandBySelector: (SEL)aSelector
5338   if (NS_KEYLOG)
5339     NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
5341   processingCompose = NO;
5342   if (aSelector == @selector (deleteBackward:))
5343     {
5344       /* happens when user backspaces over an ongoing composition:
5345          throw a 'delete' into the event queue */
5346       if (!emacs_event)
5347         return;
5348       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5349       emacs_event->code = 0xFF08;
5350       EV_TRAILER ((id)nil);
5351     }
5354 - (NSArray *)validAttributesForMarkedText
5356   static NSArray *arr = nil;
5357   if (arr == nil) arr = [NSArray new];
5358  /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
5359   return arr;
5362 - (NSRange)selectedRange
5364   if (NS_KEYLOG)
5365     NSLog (@"selectedRange request");
5366   return NSMakeRange (NSNotFound, 0);
5369 #if defined (NS_IMPL_COCOA) || GNUSTEP_GUI_MAJOR_VERSION > 0 || \
5370     GNUSTEP_GUI_MINOR_VERSION > 22
5371 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
5372 #else
5373 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
5374 #endif
5376   if (NS_KEYLOG)
5377     NSLog (@"characterIndexForPoint request");
5378   return 0;
5381 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
5383   static NSAttributedString *str = nil;
5384   if (str == nil) str = [NSAttributedString new];
5385   if (NS_KEYLOG)
5386     NSLog (@"attributedSubstringFromRange request");
5387   return str;
5390 /* End <NSTextInput> impl. */
5391 /*****************************************************************************/
5394 /* This is what happens when the user presses a mouse button.  */
5395 - (void)mouseDown: (NSEvent *)theEvent
5397   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5399   NSTRACE (mouseDown);
5401   [self deleteWorkingText];
5403   if (!emacs_event)
5404     return;
5406   last_mouse_frame = emacsframe;
5407   /* appears to be needed to prevent spurious movement events generated on
5408      button clicks */
5409   last_mouse_frame->mouse_moved = 0;
5411   if ([theEvent type] == NSScrollWheel)
5412     {
5413       CGFloat delta = [theEvent deltaY];
5414       /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
5415       if (delta == 0)
5416         return;
5417       emacs_event->kind = WHEEL_EVENT;
5418       emacs_event->code = 0;
5419       emacs_event->modifiers = EV_MODIFIERS (theEvent) |
5420         ((delta > 0) ? up_modifier : down_modifier);
5421     }
5422   else
5423     {
5424       emacs_event->kind = MOUSE_CLICK_EVENT;
5425       emacs_event->code = EV_BUTTON (theEvent);
5426       emacs_event->modifiers = EV_MODIFIERS (theEvent)
5427                              | EV_UDMODIFIERS (theEvent);
5428     }
5429   XSETINT (emacs_event->x, lrint (p.x));
5430   XSETINT (emacs_event->y, lrint (p.y));
5431   EV_TRAILER (theEvent);
5435 - (void)rightMouseDown: (NSEvent *)theEvent
5437   NSTRACE (rightMouseDown);
5438   [self mouseDown: theEvent];
5442 - (void)otherMouseDown: (NSEvent *)theEvent
5444   NSTRACE (otherMouseDown);
5445   [self mouseDown: theEvent];
5449 - (void)mouseUp: (NSEvent *)theEvent
5451   NSTRACE (mouseUp);
5452   [self mouseDown: theEvent];
5456 - (void)rightMouseUp: (NSEvent *)theEvent
5458   NSTRACE (rightMouseUp);
5459   [self mouseDown: theEvent];
5463 - (void)otherMouseUp: (NSEvent *)theEvent
5465   NSTRACE (otherMouseUp);
5466   [self mouseDown: theEvent];
5470 - (void) scrollWheel: (NSEvent *)theEvent
5472   NSTRACE (scrollWheel);
5473   [self mouseDown: theEvent];
5477 /* Tell emacs the mouse has moved. */
5478 - (void)mouseMoved: (NSEvent *)e
5480   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5481   Lisp_Object frame;
5483 //  NSTRACE (mouseMoved);
5485   last_mouse_movement_time = EV_TIMESTAMP (e);
5486   last_mouse_motion_position
5487     = [self convertPoint: [e locationInWindow] fromView: nil];
5489   /* update any mouse face */
5490   if (hlinfo->mouse_face_hidden)
5491     {
5492       hlinfo->mouse_face_hidden = 0;
5493       clear_mouse_face (hlinfo);
5494     }
5496   /* tooltip handling */
5497   previous_help_echo_string = help_echo_string;
5498   help_echo_string = Qnil;
5500   if (!note_mouse_movement (emacsframe, last_mouse_motion_position.x,
5501                             last_mouse_motion_position.y))
5502     help_echo_string = previous_help_echo_string;
5504   XSETFRAME (frame, emacsframe);
5505   if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
5506     {
5507       /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
5508          (note_mouse_highlight), which is called through the
5509          note_mouse_movement () call above */
5510       gen_help_event (help_echo_string, frame, help_echo_window,
5511                       help_echo_object, help_echo_pos);
5512     }
5513   else
5514     {
5515       help_echo_string = Qnil;
5516       gen_help_event (Qnil, frame, Qnil, Qnil, 0);
5517     }
5519   if (emacsframe->mouse_moved && send_appdefined)
5520     ns_send_appdefined (-1);
5524 - (void)mouseDragged: (NSEvent *)e
5526   NSTRACE (mouseDragged);
5527   [self mouseMoved: e];
5531 - (void)rightMouseDragged: (NSEvent *)e
5533   NSTRACE (rightMouseDragged);
5534   [self mouseMoved: e];
5538 - (void)otherMouseDragged: (NSEvent *)e
5540   NSTRACE (otherMouseDragged);
5541   [self mouseMoved: e];
5545 - (BOOL)windowShouldClose: (id)sender
5547   NSEvent *e =[[self window] currentEvent];
5549   NSTRACE (windowShouldClose);
5550   windowClosing = YES;
5551   if (!emacs_event)
5552     return NO;
5553   emacs_event->kind = DELETE_WINDOW_EVENT;
5554   emacs_event->modifiers = 0;
5555   emacs_event->code = 0;
5556   EV_TRAILER (e);
5557   /* Don't close this window, let this be done from lisp code.  */
5558   return NO;
5561 - (void) updateFrameSize: (BOOL) delay;
5563   NSWindow *window = [self window];
5564   NSRect wr = [window frame];
5565   int extra = 0;
5566   int gsextra = 0;
5567 #ifdef NS_IMPL_GNUSTEP
5568   gsextra = 3;
5569 #endif
5571   int oldc = cols, oldr = rows;
5572   int oldw = FRAME_PIXEL_WIDTH (emacsframe),
5573     oldh = FRAME_PIXEL_HEIGHT (emacsframe);
5574   int neww, newh;
5576   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, wr.size.width + gsextra);
5578   if (cols < MINWIDTH)
5579     cols = MINWIDTH;
5581   if (! [self isFullscreen])
5582     {
5583       extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5584         + FRAME_TOOLBAR_HEIGHT (emacsframe) - gsextra;
5585     }
5587   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, wr.size.height - extra);
5589   if (rows < MINHEIGHT)
5590     rows = MINHEIGHT;
5592   neww = (int)wr.size.width - emacsframe->border_width;
5593   newh = (int)wr.size.height - extra;
5595   if (oldr != rows || oldc != cols || neww != oldw || newh != oldh)
5596     {
5597       NSView *view = FRAME_NS_VIEW (emacsframe);
5598       NSWindow *win = [view window];
5599       NSSize sz = [win resizeIncrements];
5601       FRAME_PIXEL_WIDTH (emacsframe) = neww;
5602       FRAME_PIXEL_HEIGHT (emacsframe) = newh;
5603       change_frame_size (emacsframe, rows, cols, 0, delay, 0);
5604       SET_FRAME_GARBAGED (emacsframe);
5605       cancel_mouse_face (emacsframe);
5607       // Did resize increments change because of a font change?
5608       if (sz.width != FRAME_COLUMN_WIDTH (emacsframe) ||
5609           sz.height != FRAME_LINE_HEIGHT (emacsframe))
5610         {
5611           sz.width = FRAME_COLUMN_WIDTH (emacsframe);
5612           sz.height = FRAME_LINE_HEIGHT (emacsframe);
5613           [win setResizeIncrements: sz];
5614         }
5616       [view setFrame: NSMakeRect (0, 0, neww, newh)];
5617       [self windowDidMove:nil];   // Update top/left.
5618     }
5621 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
5622 /* normalize frame to gridded text size */
5624   int extra = 0;
5625   int gsextra = 0;
5626 #ifdef NS_IMPL_GNUSTEP
5627   gsextra = 3;
5628 #endif
5630   NSTRACE (windowWillResize);
5631 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
5633   if (fs_state == FULLSCREEN_MAXIMIZED
5634       && (maximized_width != (int)frameSize.width
5635           || maximized_height != (int)frameSize.height))
5636     [self setFSValue: FULLSCREEN_NONE];
5637   else if (fs_state == FULLSCREEN_WIDTH
5638            && maximized_width != (int)frameSize.width)
5639     [self setFSValue: FULLSCREEN_NONE];
5640   else if (fs_state == FULLSCREEN_HEIGHT
5641            && maximized_height != (int)frameSize.height)
5642     [self setFSValue: FULLSCREEN_NONE];
5643   if (fs_state == FULLSCREEN_NONE)
5644     maximized_width = maximized_height = -1;
5646   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe,
5647                                          frameSize.width + gsextra);
5648   if (cols < MINWIDTH)
5649     cols = MINWIDTH;
5651   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe,
5652                                            frameSize.height - extra);
5653   if (rows < MINHEIGHT)
5654     rows = MINHEIGHT;
5655 #ifdef NS_IMPL_COCOA
5656   {
5657     /* this sets window title to have size in it; the wm does this under GS */
5658     NSRect r = [[self window] frame];
5659     if (r.size.height == frameSize.height && r.size.width == frameSize.width)
5660       {
5661         if (old_title != 0)
5662           {
5663             xfree (old_title);
5664             old_title = 0;
5665           }
5666       }
5667     else
5668       {
5669         char *size_title;
5670         NSWindow *window = [self window];
5671         if (old_title == 0)
5672           {
5673             const char *t = [[[self window] title] UTF8String];
5674             char *pos = strstr (t, "  â€”  ");
5675             if (pos)
5676               *pos = '\0';
5677             old_title = xstrdup (t);
5678           }
5679         size_title = xmalloc (strlen (old_title) + 40);
5680         esprintf (size_title, "%s  â€”  (%d x %d)", old_title, cols, rows);
5681         [window setTitle: [NSString stringWithUTF8String: size_title]];
5682         [window display];
5683         xfree (size_title);
5684       }
5685   }
5686 #endif /* NS_IMPL_COCOA */
5687 /*fprintf (stderr,"    ...size became %.0f x %.0f  (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
5689   return frameSize;
5693 - (void)windowDidResize: (NSNotification *)notification
5695   if (! [self fsIsNative])
5696     {
5697       NSWindow *theWindow = [notification object];
5698       /* We can get notification on the non-FS window when in
5699          fullscreen mode.  */
5700       if ([self window] != theWindow) return;
5701     }
5703 #ifdef NS_IMPL_GNUSTEP
5704   NSWindow *theWindow = [notification object];
5706    /* In GNUstep, at least currently, it's possible to get a didResize
5707       without getting a willResize.. therefore we need to act as if we got
5708       the willResize now */
5709   NSSize sz = [theWindow frame].size;
5710   sz = [self windowWillResize: theWindow toSize: sz];
5711 #endif /* NS_IMPL_GNUSTEP */
5713   NSTRACE (windowDidResize);
5714 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
5716 #ifdef NS_IMPL_COCOA
5717   if (old_title != 0)
5718     {
5719       xfree (old_title);
5720       old_title = 0;
5721     }
5722 #endif /* NS_IMPL_COCOA */
5724   if (cols > 0 && rows > 0)
5725     {
5726       [self updateFrameSize: YES];
5727     }
5729   ns_send_appdefined (-1);
5733 - (void)windowDidBecomeKey: (NSNotification *)notification
5734 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5736   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5737   struct frame *old_focus = dpyinfo->x_focus_frame;
5739   NSTRACE (windowDidBecomeKey);
5741   if (emacsframe != old_focus)
5742     dpyinfo->x_focus_frame = emacsframe;
5744   ns_frame_rehighlight (emacsframe);
5746   if (emacs_event)
5747     {
5748       emacs_event->kind = FOCUS_IN_EVENT;
5749       EV_TRAILER ((id)nil);
5750     }
5754 - (void)windowDidResignKey: (NSNotification *)notification
5755 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5757   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5758   BOOL is_focus_frame = dpyinfo->x_focus_frame == emacsframe;
5759   NSTRACE (windowDidResignKey);
5761   if (is_focus_frame)
5762     dpyinfo->x_focus_frame = 0;
5764   ns_frame_rehighlight (emacsframe);
5766   /* FIXME: for some reason needed on second and subsequent clicks away
5767             from sole-frame Emacs to get hollow box to show */
5768   if (!windowClosing && [[self window] isVisible] == YES)
5769     {
5770       x_update_cursor (emacsframe, 1);
5771       x_set_frame_alpha (emacsframe);
5772     }
5774   if (emacs_event && is_focus_frame)
5775     {
5776       [self deleteWorkingText];
5777       emacs_event->kind = FOCUS_OUT_EVENT;
5778       EV_TRAILER ((id)nil);
5779     }
5783 - (void)windowWillMiniaturize: sender
5785   NSTRACE (windowWillMiniaturize);
5789 - (BOOL)isFlipped
5791   return YES;
5795 - (BOOL)isOpaque
5797   return NO;
5801 - initFrameFromEmacs: (struct frame *)f
5803   NSRect r, wr;
5804   Lisp_Object tem;
5805   NSWindow *win;
5806   NSSize sz;
5807   NSColor *col;
5808   NSString *name;
5810   NSTRACE (initFrameFromEmacs);
5812   windowClosing = NO;
5813   processingCompose = NO;
5814   scrollbarsNeedingUpdate = 0;
5815   fs_state = FULLSCREEN_NONE;
5816   fs_before_fs = next_maximized = -1;
5817 #ifdef HAVE_NATIVE_FS
5818   fs_is_native = ns_use_native_fullscreen;
5819 #else
5820   fs_is_native = NO;
5821 #endif
5822   maximized_width = maximized_height = -1;
5823   nonfs_window = nil;
5825 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
5827   ns_userRect = NSMakeRect (0, 0, 0, 0);
5828   r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
5829                  FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
5830   [self initWithFrame: r];
5831   [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
5833   FRAME_NS_VIEW (f) = self;
5834   emacsframe = f;
5835   old_title = 0;
5837   win = [[EmacsWindow alloc]
5838             initWithContentRect: r
5839                       styleMask: (NSResizableWindowMask |
5840 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
5841                                   NSTitledWindowMask |
5842 #endif
5843                                   NSMiniaturizableWindowMask |
5844                                   NSClosableWindowMask)
5845                         backing: NSBackingStoreBuffered
5846                           defer: YES];
5848 #ifdef HAVE_NATIVE_FS
5849     [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
5850 #endif
5852   wr = [win frame];
5853   bwidth = f->border_width = wr.size.width - r.size.width;
5854   tibar_height = FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
5856   [win setAcceptsMouseMovedEvents: YES];
5857   [win setDelegate: self];
5858   [win useOptimizedDrawing: YES];
5860   sz.width = FRAME_COLUMN_WIDTH (f);
5861   sz.height = FRAME_LINE_HEIGHT (f);
5862   [win setResizeIncrements: sz];
5864   [[win contentView] addSubview: self];
5866   if (ns_drag_types)
5867     [self registerForDraggedTypes: ns_drag_types];
5869   tem = f->name;
5870   name = [NSString stringWithUTF8String:
5871                    NILP (tem) ? "Emacs" : SSDATA (tem)];
5872   [win setTitle: name];
5874   /* toolbar support */
5875   toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
5876                          [NSString stringWithFormat: @"Emacs Frame %d",
5877                                    ns_window_num]];
5878   [win setToolbar: toolbar];
5879   [toolbar setVisible: NO];
5880 #ifdef NS_IMPL_COCOA
5881   {
5882     NSButton *toggleButton;
5883   toggleButton = [win standardWindowButton: NSWindowToolbarButton];
5884   [toggleButton setTarget: self];
5885   [toggleButton setAction: @selector (toggleToolbar: )];
5886   }
5887 #endif
5888   FRAME_TOOLBAR_HEIGHT (f) = 0;
5890   tem = f->icon_name;
5891   if (!NILP (tem))
5892     [win setMiniwindowTitle:
5893            [NSString stringWithUTF8String: SSDATA (tem)]];
5895   {
5896     NSScreen *screen = [win screen];
5898     if (screen != 0)
5899       [win setFrameTopLeftPoint: NSMakePoint
5900            (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
5901             IN_BOUND (-SCREENMAX,
5902                      [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
5903   }
5905   [win makeFirstResponder: self];
5907   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5908                                   (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
5909   [win setBackgroundColor: col];
5910   if ([col alphaComponent] != (EmacsCGFloat) 1.0)
5911     [win setOpaque: NO];
5913   [self allocateGState];
5915   [NSApp registerServicesMenuSendTypes: ns_send_types
5916                            returnTypes: nil];
5918   ns_window_num++;
5919   return self;
5923 - (void)windowDidMove: sender
5925   NSWindow *win = [self window];
5926   NSRect r = [win frame];
5927   NSArray *screens = [NSScreen screens];
5928   NSScreen *screen = [screens objectAtIndex: 0];
5930   NSTRACE (windowDidMove);
5932   if (!emacsframe->output_data.ns)
5933     return;
5934   if (screen != nil)
5935     {
5936       emacsframe->left_pos = r.origin.x;
5937       emacsframe->top_pos =
5938         [screen frame].size.height - (r.origin.y + r.size.height);
5939     }
5943 /* Called AFTER method below, but before our windowWillResize call there leads
5944    to windowDidResize -> x_set_window_size.  Update emacs' notion of frame
5945    location so set_window_size moves the frame. */
5946 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
5948   emacsframe->output_data.ns->zooming = 1;
5949   return YES;
5953 /* Override to do something slightly nonstandard, but nice.  First click on
5954    zoom button will zoom vertically.  Second will zoom completely.  Third
5955    returns to original. */
5956 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
5957                         defaultFrame:(NSRect)defaultFrame
5959   NSRect result = [sender frame];
5961   NSTRACE (windowWillUseStandardFrame);
5963   if (fs_before_fs != -1) /* Entering fullscreen */
5964       {
5965         result = defaultFrame;
5966       }
5967   else if (next_maximized == FULLSCREEN_HEIGHT
5968       || (next_maximized == -1
5969           && abs (defaultFrame.size.height - result.size.height)
5970           > FRAME_LINE_HEIGHT (emacsframe)))
5971     {
5972       /* first click */
5973       ns_userRect = result;
5974       maximized_height = result.size.height = defaultFrame.size.height;
5975       maximized_width = -1;
5976       result.origin.y = defaultFrame.origin.y;
5977       [self setFSValue: FULLSCREEN_HEIGHT];
5978     }
5979   else if (next_maximized == FULLSCREEN_WIDTH)
5980     {
5981       ns_userRect = result;
5982       maximized_width = result.size.width = defaultFrame.size.width;
5983       maximized_height = -1;
5984       result.origin.x = defaultFrame.origin.x;
5985       [self setFSValue: FULLSCREEN_WIDTH];
5986     }
5987   else if (next_maximized == FULLSCREEN_MAXIMIZED
5988            || (next_maximized == -1
5989                && abs (defaultFrame.size.width - result.size.width)
5990                > FRAME_COLUMN_WIDTH (emacsframe)))
5991     {
5992       result = defaultFrame;  /* second click */
5993       maximized_width = result.size.width;
5994       maximized_height = result.size.height;
5995       [self setFSValue: FULLSCREEN_MAXIMIZED];
5996     }
5997   else
5998     {
5999       /* restore */
6000       result = ns_userRect.size.height ? ns_userRect : result;
6001       ns_userRect = NSMakeRect (0, 0, 0, 0);
6002       [self setFSValue: FULLSCREEN_NONE];
6003       maximized_width = maximized_height = -1;
6004     }
6006   if (fs_before_fs == -1) next_maximized = -1;
6007   [self windowWillResize: sender toSize: result.size];
6008   return result;
6012 - (void)windowDidDeminiaturize: sender
6014   NSTRACE (windowDidDeminiaturize);
6015   if (!emacsframe->output_data.ns)
6016     return;
6018   SET_FRAME_ICONIFIED (emacsframe, 0);
6019   SET_FRAME_VISIBLE (emacsframe, 1);
6020   windows_or_buffers_changed++;
6022   if (emacs_event)
6023     {
6024       emacs_event->kind = DEICONIFY_EVENT;
6025       EV_TRAILER ((id)nil);
6026     }
6030 - (void)windowDidExpose: sender
6032   NSTRACE (windowDidExpose);
6033   if (!emacsframe->output_data.ns)
6034     return;
6036   SET_FRAME_VISIBLE (emacsframe, 1);
6037   SET_FRAME_GARBAGED (emacsframe);
6039   if (send_appdefined)
6040     ns_send_appdefined (-1);
6044 - (void)windowDidMiniaturize: sender
6046   NSTRACE (windowDidMiniaturize);
6047   if (!emacsframe->output_data.ns)
6048     return;
6050   SET_FRAME_ICONIFIED (emacsframe, 1);
6051   SET_FRAME_VISIBLE (emacsframe, 0);
6053   if (emacs_event)
6054     {
6055       emacs_event->kind = ICONIFY_EVENT;
6056       EV_TRAILER ((id)nil);
6057     }
6060 #ifdef HAVE_NATIVE_FS
6061 - (NSApplicationPresentationOptions)window:(NSWindow *)window
6062       willUseFullScreenPresentationOptions:
6063   (NSApplicationPresentationOptions)proposedOptions
6065   return proposedOptions|NSApplicationPresentationAutoHideToolbar;
6067 #endif
6069 - (void)windowWillEnterFullScreen:(NSNotification *)notification
6071   fs_before_fs = fs_state;
6074 - (void)windowDidEnterFullScreen:(NSNotification *)notification
6076   [self setFSValue: FULLSCREEN_BOTH];
6077   if (! [self fsIsNative])
6078     {
6079       [self windowDidBecomeKey:notification];
6080       [nonfs_window orderOut:self];
6081     }
6082   else if (! FRAME_EXTERNAL_TOOL_BAR (emacsframe))
6083     [toolbar setVisible:NO];
6086 - (void)windowWillExitFullScreen:(NSNotification *)notification
6088   if (next_maximized != -1)
6089     fs_before_fs = next_maximized;
6092 - (void)windowDidExitFullScreen:(NSNotification *)notification
6094   [self setFSValue: fs_before_fs];
6095   fs_before_fs = -1;
6096 #ifdef NS_IMPL_COCOA
6097   [self updateCollectionBehaviour];
6098 #endif
6099   if (FRAME_EXTERNAL_TOOL_BAR (emacsframe))
6100     {
6101       [toolbar setVisible:YES];
6102       update_frame_tool_bar (emacsframe);
6103       [self updateFrameSize:YES];
6104       [[self window] display];
6105     }
6106   else
6107     [toolbar setVisible:NO];
6109   if (next_maximized != -1)
6110     [[self window] performZoom:self];
6113 - (BOOL)fsIsNative
6115   return fs_is_native;
6118 - (BOOL)isFullscreen
6120   if (! fs_is_native) return nonfs_window != nil;
6121 #ifdef HAVE_NATIVE_FS
6122   return ([[self window] styleMask] & NSFullScreenWindowMask) != 0;
6123 #else
6124   return NO;
6125 #endif
6128 #ifdef HAVE_NATIVE_FS
6129 - (void)updateCollectionBehaviour
6131   if (! [self isFullscreen])
6132     {
6133       NSWindow *win = [self window];
6134       NSWindowCollectionBehavior b = [win collectionBehavior];
6135       if (ns_use_native_fullscreen)
6136         b |= NSWindowCollectionBehaviorFullScreenPrimary;
6137       else
6138         b &= ~NSWindowCollectionBehaviorFullScreenPrimary;
6140       [win setCollectionBehavior: b];
6141       fs_is_native = ns_use_native_fullscreen;
6142     }
6144 #endif
6146 - (void)toggleFullScreen: (id)sender
6148   NSWindow *w, *fw;
6149   BOOL onFirstScreen;
6150   struct frame *f;
6151   NSSize sz;
6152   NSRect r, wr;
6153   NSColor *col;
6155   if (fs_is_native)
6156     {
6157 #ifdef NS_IMPL_COCOA
6158       [[self window] toggleFullScreen:sender];
6159 #endif
6160       return;
6161     }
6163   w = [self window];
6164   onFirstScreen = [[w screen] isEqual:[[NSScreen screens] objectAtIndex:0]];
6165   f = emacsframe;
6166   wr = [w frame];
6167   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6168                                  (FRAME_DEFAULT_FACE (f)),
6169                                  f);
6171   sz.width = FRAME_COLUMN_WIDTH (f);
6172   sz.height = FRAME_LINE_HEIGHT (f);
6174   if (fs_state != FULLSCREEN_BOTH)
6175     {
6176       /* Hide dock and menubar if we are on the primary screen.  */
6177       if (onFirstScreen)
6178         {
6179 #if defined (NS_IMPL_COCOA) && \
6180   MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
6181           NSApplicationPresentationOptions options
6182             = NSApplicationPresentationAutoHideDock
6183             | NSApplicationPresentationAutoHideMenuBar;
6185           [NSApp setPresentationOptions: options];
6186 #else
6187           [NSMenu setMenuBarVisible:NO];
6188 #endif
6189         }
6191       fw = [[EmacsFSWindow alloc]
6192                        initWithContentRect:[w contentRectForFrameRect:wr]
6193                                  styleMask:NSBorderlessWindowMask
6194                                    backing:NSBackingStoreBuffered
6195                                      defer:YES
6196                                     screen:[w screen]];
6198       [fw setContentView:[w contentView]];
6199       [fw setTitle:[w title]];
6200       [fw setDelegate:self];
6201       [fw setAcceptsMouseMovedEvents: YES];
6202       [fw useOptimizedDrawing: YES];
6203       [fw setResizeIncrements: sz];
6204       [fw setBackgroundColor: col];
6205       if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6206         [fw setOpaque: NO];
6208       f->border_width = 0;
6209       FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
6210       tobar_height = FRAME_TOOLBAR_HEIGHT (f);
6211       FRAME_TOOLBAR_HEIGHT (f) = 0;
6213       nonfs_window = w;
6215       [self windowWillEnterFullScreen:nil];
6216       [fw makeKeyAndOrderFront:NSApp];
6217       [fw makeFirstResponder:self];
6218       [w orderOut:self];
6219       r = [fw frameRectForContentRect:[[fw screen] frame]];
6220       [fw setFrame: r display:YES animate:YES];
6221       [self windowDidEnterFullScreen:nil];
6222       [fw display];
6223     }
6224   else
6225     {
6226       fw = w;
6227       w = nonfs_window;
6228       nonfs_window = nil;
6230       if (onFirstScreen)
6231         {
6232 #if defined (NS_IMPL_COCOA) && \
6233   MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
6234           [NSApp setPresentationOptions: NSApplicationPresentationDefault];
6235 #else
6236           [NSMenu setMenuBarVisible:YES];
6237 #endif
6238         }
6240       [w setContentView:[fw contentView]];
6241       [w setResizeIncrements: sz];
6242       [w setBackgroundColor: col];
6243       if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6244         [w setOpaque: NO];
6246       f->border_width = bwidth;
6247       FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
6248       if (FRAME_EXTERNAL_TOOL_BAR (f))
6249         FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
6251       [self windowWillExitFullScreen:nil];
6252       [fw setFrame: [w frame] display:YES animate:YES];
6253       [fw close];
6254       [w makeKeyAndOrderFront:NSApp];
6255       [self windowDidExitFullScreen:nil];
6256       [self updateFrameSize:YES];
6257     }
6260 - (void)handleFS
6262   if (fs_state != emacsframe->want_fullscreen)
6263     {
6264       if (fs_state == FULLSCREEN_BOTH)
6265         {
6266           [self toggleFullScreen:self];
6267         }
6269       switch (emacsframe->want_fullscreen)
6270         {
6271         case FULLSCREEN_BOTH:
6272           [self toggleFullScreen:self];
6273           break;
6274         case FULLSCREEN_WIDTH:
6275           next_maximized = FULLSCREEN_WIDTH;
6276           if (fs_state != FULLSCREEN_BOTH)
6277             [[self window] performZoom:self];
6278           break;
6279         case FULLSCREEN_HEIGHT:
6280           next_maximized = FULLSCREEN_HEIGHT;
6281           if (fs_state != FULLSCREEN_BOTH)
6282             [[self window] performZoom:self];
6283           break;
6284         case FULLSCREEN_MAXIMIZED:
6285           next_maximized = FULLSCREEN_MAXIMIZED;
6286           if (fs_state != FULLSCREEN_BOTH)
6287             [[self window] performZoom:self];
6288           break;
6289         case FULLSCREEN_NONE:
6290           if (fs_state != FULLSCREEN_BOTH)
6291             {
6292               next_maximized = FULLSCREEN_NONE;
6293               [[self window] performZoom:self];
6294             }
6295           break;
6296         }
6298       emacsframe->want_fullscreen = FULLSCREEN_NONE;
6299     }
6303 - (void) setFSValue: (int)value
6305   Lisp_Object lval = Qnil;
6306   switch (value)
6307     {
6308     case FULLSCREEN_BOTH:
6309       lval = Qfullboth;
6310       break;
6311     case FULLSCREEN_WIDTH:
6312       lval = Qfullwidth;
6313       break;
6314     case FULLSCREEN_HEIGHT:
6315       lval = Qfullheight;
6316       break;
6317     case FULLSCREEN_MAXIMIZED:
6318       lval = Qmaximized;
6319       break;
6320     }
6321   store_frame_param (emacsframe, Qfullscreen, lval);
6322   fs_state = value;
6325 - (void)mouseEntered: (NSEvent *)theEvent
6327   NSTRACE (mouseEntered);
6328   last_mouse_movement_time = EV_TIMESTAMP (theEvent);
6332 - (void)mouseExited: (NSEvent *)theEvent
6334   Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
6336   NSTRACE (mouseExited);
6338   if (!hlinfo)
6339     return;
6341   last_mouse_movement_time = EV_TIMESTAMP (theEvent);
6343   if (emacsframe == hlinfo->mouse_face_mouse_frame)
6344     {
6345       clear_mouse_face (hlinfo);
6346       hlinfo->mouse_face_mouse_frame = 0;
6347     }
6351 - menuDown: sender
6353   NSTRACE (menuDown);
6354   if (context_menu_value == -1)
6355     context_menu_value = [sender tag];
6356   else
6357     {
6358       NSInteger tag = [sender tag];
6359       find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
6360                                     emacsframe->menu_bar_vector,
6361                                     (void *)tag);
6362     }
6364   ns_send_appdefined (-1);
6365   return self;
6369 - (EmacsToolbar *)toolbar
6371   return toolbar;
6375 /* this gets called on toolbar button click */
6376 - toolbarClicked: (id)item
6378   NSEvent *theEvent;
6379   int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
6381   NSTRACE (toolbarClicked);
6383   if (!emacs_event)
6384     return self;
6386   /* send first event (for some reason two needed) */
6387   theEvent = [[self window] currentEvent];
6388   emacs_event->kind = TOOL_BAR_EVENT;
6389   XSETFRAME (emacs_event->arg, emacsframe);
6390   EV_TRAILER (theEvent);
6392   emacs_event->kind = TOOL_BAR_EVENT;
6393 /*   XSETINT (emacs_event->code, 0); */
6394   emacs_event->arg = AREF (emacsframe->tool_bar_items,
6395                            idx + TOOL_BAR_ITEM_KEY);
6396   emacs_event->modifiers = EV_MODIFIERS (theEvent);
6397   EV_TRAILER (theEvent);
6398   return self;
6402 - toggleToolbar: (id)sender
6404   if (!emacs_event)
6405     return self;
6407   emacs_event->kind = NS_NONKEY_EVENT;
6408   emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
6409   EV_TRAILER ((id)nil);
6410   return self;
6414 - (void)drawRect: (NSRect)rect
6416   int x = NSMinX (rect), y = NSMinY (rect);
6417   int width = NSWidth (rect), height = NSHeight (rect);
6419   NSTRACE (drawRect);
6421   if (!emacsframe || !emacsframe->output_data.ns)
6422     return;
6424   ns_clear_frame_area (emacsframe, x, y, width, height);
6425   expose_frame (emacsframe, x, y, width, height);
6427   /*
6428     drawRect: may be called (at least in OS X 10.5) for invisible
6429     views as well for some reason.  Thus, do not infer visibility
6430     here.
6432     emacsframe->async_visible = 1;
6433     emacsframe->async_iconified = 0;
6434   */
6438 /* NSDraggingDestination protocol methods.  Actually this is not really a
6439    protocol, but a category of Object.  O well...  */
6441 -(NSUInteger) draggingEntered: (id <NSDraggingInfo>) sender
6443   NSTRACE (draggingEntered);
6444   return NSDragOperationGeneric;
6448 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
6450   return YES;
6454 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
6456   id pb;
6457   int x, y;
6458   NSString *type;
6459   NSEvent *theEvent = [[self window] currentEvent];
6460   NSPoint position;
6462   NSTRACE (performDragOperation);
6464   if (!emacs_event)
6465     return NO;
6467   position = [self convertPoint: [sender draggingLocation] fromView: nil];
6468   x = lrint (position.x);  y = lrint (position.y);
6470   pb = [sender draggingPasteboard];
6471   type = [pb availableTypeFromArray: ns_drag_types];
6472   if (type == 0)
6473     {
6474       return NO;
6475     }
6476   else if ([type isEqualToString: NSFilenamesPboardType])
6477     {
6478       NSArray *files;
6479       NSEnumerator *fenum;
6480       NSString *file;
6482       if (!(files = [pb propertyListForType: type]))
6483         return NO;
6485       fenum = [files objectEnumerator];
6486       while ( (file = [fenum nextObject]) )
6487         {
6488           emacs_event->kind = NS_NONKEY_EVENT;
6489           emacs_event->code = KEY_NS_DRAG_FILE;
6490           XSETINT (emacs_event->x, x);
6491           XSETINT (emacs_event->y, y);
6492           ns_input_file = append2 (ns_input_file,
6493                                    build_string ([file UTF8String]));
6494           emacs_event->modifiers = EV_MODIFIERS (theEvent);
6495           EV_TRAILER (theEvent);
6496         }
6497       return YES;
6498     }
6499   else if ([type isEqualToString: NSURLPboardType])
6500     {
6501       NSString *file;
6502       NSURL *fileURL;
6504       if (!(fileURL = [NSURL URLFromPasteboard: pb]) ||
6505           [fileURL isFileURL] == NO)
6506         return NO;
6508       file = [fileURL path];
6509       emacs_event->kind = NS_NONKEY_EVENT;
6510       emacs_event->code = KEY_NS_DRAG_FILE;
6511       XSETINT (emacs_event->x, x);
6512       XSETINT (emacs_event->y, y);
6513       ns_input_file = append2 (ns_input_file, build_string ([file UTF8String]));
6514       emacs_event->modifiers = EV_MODIFIERS (theEvent);
6515       EV_TRAILER (theEvent);
6516       return YES;
6517     }
6518   else if ([type isEqualToString: NSStringPboardType]
6519            || [type isEqualToString: NSTabularTextPboardType])
6520     {
6521       NSString *data;
6523       if (! (data = [pb stringForType: type]))
6524         return NO;
6526       emacs_event->kind = NS_NONKEY_EVENT;
6527       emacs_event->code = KEY_NS_DRAG_TEXT;
6528       XSETINT (emacs_event->x, x);
6529       XSETINT (emacs_event->y, y);
6530       ns_input_text = build_string ([data UTF8String]);
6531       emacs_event->modifiers = EV_MODIFIERS (theEvent);
6532       EV_TRAILER (theEvent);
6533       return YES;
6534     }
6535   else if ([type isEqualToString: NSColorPboardType])
6536     {
6537       NSColor *c = [NSColor colorFromPasteboard: pb];
6538       emacs_event->kind = NS_NONKEY_EVENT;
6539       emacs_event->code = KEY_NS_DRAG_COLOR;
6540       XSETINT (emacs_event->x, x);
6541       XSETINT (emacs_event->y, y);
6542       ns_input_color = ns_color_to_lisp (c);
6543       emacs_event->modifiers = EV_MODIFIERS (theEvent);
6544       EV_TRAILER (theEvent);
6545       return YES;
6546     }
6547   else if ([type isEqualToString: NSFontPboardType])
6548     {
6549       /* impl based on GNUstep NSTextView.m */
6550       NSData *data = [pb dataForType: NSFontPboardType];
6551       NSDictionary *dict = [NSUnarchiver unarchiveObjectWithData: data];
6552       NSFont *font = [dict objectForKey: NSFontAttributeName];
6553       char fontSize[10];
6555       if (font == nil)
6556         return NO;
6558       emacs_event->kind = NS_NONKEY_EVENT;
6559       emacs_event->code = KEY_NS_CHANGE_FONT;
6560       XSETINT (emacs_event->x, x);
6561       XSETINT (emacs_event->y, y);
6562       ns_input_font = build_string ([[font fontName] UTF8String]);
6563       snprintf (fontSize, 10, "%f", [font pointSize]);
6564       ns_input_fontsize = build_string (fontSize);
6565       emacs_event->modifiers = EV_MODIFIERS (theEvent);
6566       EV_TRAILER (theEvent);
6567       return YES;
6568     }
6569   else
6570     {
6571       error ("Invalid data type in dragging pasteboard.");
6572       return NO;
6573     }
6577 - (id) validRequestorForSendType: (NSString *)typeSent
6578                       returnType: (NSString *)typeReturned
6580   NSTRACE (validRequestorForSendType);
6581   if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
6582       && typeReturned == nil)
6583     {
6584       if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
6585         return self;
6586     }
6588   return [super validRequestorForSendType: typeSent
6589                                returnType: typeReturned];
6593 /* The next two methods are part of NSServicesRequests informal protocol,
6594    supposedly called when a services menu item is chosen from this app.
6595    But this should not happen because we override the services menu with our
6596    own entries which call ns-perform-service.
6597    Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
6598    So let's at least stub them out until further investigation can be done. */
6600 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
6602   /* we could call ns_string_from_pasteboard(pboard) here but then it should
6603      be written into the buffer in place of the existing selection..
6604      ordinary service calls go through functions defined in ns-win.el */
6605   return NO;
6608 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
6610   NSArray *typesDeclared;
6611   Lisp_Object val;
6613   /* We only support NSStringPboardType */
6614   if ([types containsObject:NSStringPboardType] == NO) {
6615     return NO;
6616   }
6618   val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
6619   if (CONSP (val) && SYMBOLP (XCAR (val)))
6620     {
6621       val = XCDR (val);
6622       if (CONSP (val) && NILP (XCDR (val)))
6623         val = XCAR (val);
6624     }
6625   if (! STRINGP (val))
6626     return NO;
6628   typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
6629   [pb declareTypes:typesDeclared owner:nil];
6630   ns_string_to_pasteboard (pb, val);
6631   return YES;
6635 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
6636    (gives a miniaturized version of the window); currently we use the latter for
6637    frames whose active buffer doesn't correspond to any file
6638    (e.g., '*scratch*') */
6639 - setMiniwindowImage: (BOOL) setMini
6641   id image = [[self window] miniwindowImage];
6642   NSTRACE (setMiniwindowImage);
6644   /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
6645      about "AppleDockIconEnabled" notwithstanding, however the set message
6646      below has its effect nonetheless. */
6647   if (image != emacsframe->output_data.ns->miniimage)
6648     {
6649       if (image && [image isKindOfClass: [EmacsImage class]])
6650         [image release];
6651       [[self window] setMiniwindowImage:
6652                        setMini ? emacsframe->output_data.ns->miniimage : nil];
6653     }
6655   return self;
6659 - (void) setRows: (int) r andColumns: (int) c
6661   rows = r;
6662   cols = c;
6665 @end  /* EmacsView */
6669 /* ==========================================================================
6671     EmacsWindow implementation
6673    ========================================================================== */
6675 @implementation EmacsWindow
6677 #ifdef NS_IMPL_COCOA
6678 - (id)accessibilityAttributeValue:(NSString *)attribute
6680   Lisp_Object str = Qnil;
6681   struct frame *f = SELECTED_FRAME ();
6682   struct buffer *curbuf = XBUFFER (XWINDOW (f->selected_window)->contents);
6684   if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
6685     return NSAccessibilityTextFieldRole;
6687   if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]
6688       && curbuf && ! NILP (BVAR (curbuf, mark_active)))
6689     {
6690       str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
6691     }
6692   else if (curbuf && [attribute isEqualToString:NSAccessibilityValueAttribute])
6693     {
6694       if (! NILP (BVAR (curbuf, mark_active)))
6695           str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
6697       if (NILP (str))
6698         {
6699           ptrdiff_t start_byte = BUF_BEGV_BYTE (curbuf);
6700           ptrdiff_t byte_range = BUF_ZV_BYTE (curbuf) - start_byte;
6701           ptrdiff_t range = BUF_ZV (curbuf) - BUF_BEGV (curbuf);
6703           if (! NILP (BVAR (curbuf, enable_multibyte_characters)))
6704             str = make_uninit_multibyte_string (range, byte_range);
6705           else
6706             str = make_uninit_string (range);
6707           /* To check: This returns emacs-utf-8, which is a superset of utf-8.
6708              Is this a problem?  */
6709           memcpy (SDATA (str), BYTE_POS_ADDR (start_byte), byte_range);
6710         }
6711     }
6714   if (! NILP (str))
6715     {
6716       if (CONSP (str) && SYMBOLP (XCAR (str)))
6717         {
6718           str = XCDR (str);
6719           if (CONSP (str) && NILP (XCDR (str)))
6720             str = XCAR (str);
6721         }
6722       if (STRINGP (str))
6723         {
6724           const char *utfStr = SSDATA (str);
6725           NSString *nsStr = [NSString stringWithUTF8String: utfStr];
6726           return nsStr;
6727         }
6728     }
6730   return [super accessibilityAttributeValue:attribute];
6732 #endif /* NS_IMPL_COCOA */
6734 /* If we have multiple monitors, one above the other, we don't want to
6735    restrict the height to just one monitor.  So we override this.  */
6736 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
6738   /* When making the frame visible for the first time or if there is just
6739      one screen, we want to constrain.  Other times not.  */
6740   NSUInteger nr_screens = [[NSScreen screens] count];
6741   struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
6742   NSTRACE (constrainFrameRect);
6744   if (nr_screens == 1)
6745     {
6746       NSRect r = [super constrainFrameRect:frameRect toScreen:screen];
6747       return r;
6748     }
6750   if (f->output_data.ns->dont_constrain
6751       || ns_menu_bar_should_be_hidden ())
6752     return frameRect;
6754   f->output_data.ns->dont_constrain = 1;
6755   return [super constrainFrameRect:frameRect toScreen:screen];
6758 @end /* EmacsWindow */
6761 @implementation EmacsFSWindow
6763 - (BOOL)canBecomeKeyWindow
6765   return YES;
6768 - (BOOL)canBecomeMainWindow
6770   return YES;
6773 @end
6775 /* ==========================================================================
6777     EmacsScroller implementation
6779    ========================================================================== */
6782 @implementation EmacsScroller
6784 /* for repeat button push */
6785 #define SCROLL_BAR_FIRST_DELAY 0.5
6786 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
6788 + (CGFloat) scrollerWidth
6790   /* TODO: if we want to allow variable widths, this is the place to do it,
6791            however neither GNUstep nor Cocoa support it very well */
6792   return [NSScroller scrollerWidth];
6796 - initFrame: (NSRect )r window: (Lisp_Object)nwin
6798   NSTRACE (EmacsScroller_initFrame);
6800   r.size.width = [EmacsScroller scrollerWidth];
6801   [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
6802   [self setContinuous: YES];
6803   [self setEnabled: YES];
6805   /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
6806      locked against the top and bottom edges, and right edge on OS X, where
6807      scrollers are on right. */
6808 #ifdef NS_IMPL_GNUSTEP
6809   [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
6810 #else
6811   [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
6812 #endif
6814   win = nwin;
6815   condemned = NO;
6816   pixel_height = NSHeight (r);
6817   if (pixel_height == 0) pixel_height = 1;
6818   min_portion = 20 / pixel_height;
6820   frame = XFRAME (XWINDOW (win)->frame);
6821   if (FRAME_LIVE_P (frame))
6822     {
6823       int i;
6824       EmacsView *view = FRAME_NS_VIEW (frame);
6825       NSView *sview = [[view window] contentView];
6826       NSArray *subs = [sview subviews];
6828       /* disable optimization stopping redraw of other scrollbars */
6829       view->scrollbarsNeedingUpdate = 0;
6830       for (i =[subs count]-1; i >= 0; i--)
6831         if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
6832           view->scrollbarsNeedingUpdate++;
6833       [sview addSubview: self];
6834     }
6836 /*  [self setFrame: r]; */
6838   return self;
6842 - (void)setFrame: (NSRect)newRect
6844   NSTRACE (EmacsScroller_setFrame);
6845 /*  block_input (); */
6846   pixel_height = NSHeight (newRect);
6847   if (pixel_height == 0) pixel_height = 1;
6848   min_portion = 20 / pixel_height;
6849   [super setFrame: newRect];
6850   [self display];
6851 /*  unblock_input (); */
6855 - (void)dealloc
6857   NSTRACE (EmacsScroller_dealloc);
6858   if (!NILP (win))
6859     wset_vertical_scroll_bar (XWINDOW (win), Qnil);
6860   [super dealloc];
6864 - condemn
6866   NSTRACE (condemn);
6867   condemned =YES;
6868   return self;
6872 - reprieve
6874   NSTRACE (reprieve);
6875   condemned =NO;
6876   return self;
6880 - judge
6882   NSTRACE (judge);
6883   if (condemned)
6884     {
6885       EmacsView *view;
6886       block_input ();
6887       /* ensure other scrollbar updates after deletion */
6888       view = (EmacsView *)FRAME_NS_VIEW (frame);
6889       if (view != nil)
6890         view->scrollbarsNeedingUpdate++;
6891       [self removeFromSuperview];
6892       [self release];
6893       unblock_input ();
6894     }
6895   return self;
6899 - (void)resetCursorRects
6901   NSRect visible = [self visibleRect];
6902   NSTRACE (resetCursorRects);
6904   if (!NSIsEmptyRect (visible))
6905     [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
6906   [[NSCursor arrowCursor] setOnMouseEntered: YES];
6910 - (int) checkSamePosition: (int) position portion: (int) portion
6911                     whole: (int) whole
6913   return em_position ==position && em_portion ==portion && em_whole ==whole
6914     && portion != whole; /* needed for resize empty buf */
6918 - setPosition: (int)position portion: (int)portion whole: (int)whole
6920   NSTRACE (setPosition);
6922   em_position = position;
6923   em_portion = portion;
6924   em_whole = whole;
6926   if (portion >= whole)
6927     {
6928 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
6929       [self setKnobProportion: 1.0];
6930       [self setDoubleValue: 1.0];
6931 #else
6932       [self setFloatValue: 0.0 knobProportion: 1.0];
6933 #endif
6934     }
6935   else
6936     {
6937       float pos;
6938       CGFloat por;
6939       portion = max ((float)whole*min_portion/pixel_height, portion);
6940       pos = (float)position / (whole - portion);
6941       por = (CGFloat)portion/whole;
6942 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
6943       [self setKnobProportion: por];
6944       [self setDoubleValue: pos];
6945 #else
6946       [self setFloatValue: pos knobProportion: por];
6947 #endif
6948     }
6950   /* Events may come here even if the event loop is not running.
6951      If we don't enter the event loop, the scroll bar will not update.
6952      So send SIGIO to ourselves.  */
6953   if (apploopnr == 0) raise (SIGIO);
6955   return self;
6958 /* FIXME: unused at moment (see ns_mouse_position) at the moment because
6959      drag events will go directly to the EmacsScroller.  Leaving in for now. */
6960 -(void)getMouseMotionPart: (int *)part window: (Lisp_Object *)window
6961                         x: (Lisp_Object *)x y: ( Lisp_Object *)y
6963   *part = last_hit_part;
6964   *window = win;
6965   XSETINT (*y, pixel_height);
6966   if ([self floatValue] > 0.999F)
6967     XSETINT (*x, pixel_height);
6968   else
6969     XSETINT (*x, pixel_height * [self floatValue]);
6973 /* set up emacs_event */
6974 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
6976   if (!emacs_event)
6977     return;
6979   emacs_event->part = last_hit_part;
6980   emacs_event->code = 0;
6981   emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
6982   emacs_event->frame_or_window = win;
6983   emacs_event->timestamp = EV_TIMESTAMP (e);
6984   emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
6985   emacs_event->arg = Qnil;
6986   XSETINT (emacs_event->x, loc * pixel_height);
6987   XSETINT (emacs_event->y, pixel_height-20);
6989   if (q_event_ptr)
6990     {
6991       n_emacs_events_pending++;
6992       kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
6993     }
6994   else
6995     hold_event (emacs_event);
6996   EVENT_INIT (*emacs_event);
6997   ns_send_appdefined (-1);
7001 /* called manually thru timer to implement repeated button action w/hold-down */
7002 - repeatScroll: (NSTimer *)scrollEntry
7004   NSEvent *e = [[self window] currentEvent];
7005   NSPoint p =  [[self window] mouseLocationOutsideOfEventStream];
7006   BOOL inKnob = [self testPart: p] == NSScrollerKnob;
7008   /* clear timer if need be */
7009   if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
7010     {
7011         [scroll_repeat_entry invalidate];
7012         [scroll_repeat_entry release];
7013         scroll_repeat_entry = nil;
7015         if (inKnob)
7016           return self;
7018         scroll_repeat_entry
7019           = [[NSTimer scheduledTimerWithTimeInterval:
7020                         SCROLL_BAR_CONTINUOUS_DELAY
7021                                             target: self
7022                                           selector: @selector (repeatScroll:)
7023                                           userInfo: 0
7024                                            repeats: YES]
7025               retain];
7026     }
7028   [self sendScrollEventAtLoc: 0 fromEvent: e];
7029   return self;
7033 /* Asynchronous mouse tracking for scroller.  This allows us to dispatch
7034    mouseDragged events without going into a modal loop. */
7035 - (void)mouseDown: (NSEvent *)e
7037   NSRect sr, kr;
7038   /* hitPart is only updated AFTER event is passed on */
7039   NSScrollerPart part = [self testPart: [e locationInWindow]];
7040   CGFloat inc = 0.0, loc, kloc, pos;
7041   int edge = 0;
7043   NSTRACE (EmacsScroller_mouseDown);
7045   switch (part)
7046     {
7047     case NSScrollerDecrementPage:
7048         last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
7049     case NSScrollerIncrementPage:
7050         last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
7051     case NSScrollerDecrementLine:
7052       last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
7053     case NSScrollerIncrementLine:
7054       last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
7055     case NSScrollerKnob:
7056       last_hit_part = scroll_bar_handle; break;
7057     case NSScrollerKnobSlot:  /* GNUstep-only */
7058       last_hit_part = scroll_bar_move_ratio; break;
7059     default:  /* NSScrollerNoPart? */
7060       fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
7061                (long) part);
7062       return;
7063     }
7065   if (inc != 0.0)
7066     {
7067       pos = 0;      /* ignored */
7069       /* set a timer to repeat, as we can't let superclass do this modally */
7070       scroll_repeat_entry
7071         = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
7072                                             target: self
7073                                           selector: @selector (repeatScroll:)
7074                                           userInfo: 0
7075                                            repeats: YES]
7076             retain];
7077     }
7078   else
7079     {
7080       /* handle, or on GNUstep possibly slot */
7081       NSEvent *fake_event;
7083       /* compute float loc in slot and mouse offset on knob */
7084       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
7085                       toView: nil];
7086       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
7087       if (loc <= 0.0)
7088         {
7089           loc = 0.0;
7090           edge = -1;
7091         }
7092       else if (loc >= NSHeight (sr))
7093         {
7094           loc = NSHeight (sr);
7095           edge = 1;
7096         }
7098       if (edge)
7099         kloc = 0.5 * edge;
7100       else
7101         {
7102           kr = [self convertRect: [self rectForPart: NSScrollerKnob]
7103                           toView: nil];
7104           kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
7105         }
7106       last_mouse_offset = kloc;
7108       /* if knob, tell emacs a location offset by knob pos
7109          (to indicate top of handle) */
7110       if (part == NSScrollerKnob)
7111           pos = (loc - last_mouse_offset) / NSHeight (sr);
7112       else
7113         /* else this is a slot click on GNUstep: go straight there */
7114         pos = loc / NSHeight (sr);
7116       /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
7117       fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
7118                                       location: [e locationInWindow]
7119                                  modifierFlags: [e modifierFlags]
7120                                      timestamp: [e timestamp]
7121                                   windowNumber: [e windowNumber]
7122                                        context: [e context]
7123                                    eventNumber: [e eventNumber]
7124                                     clickCount: [e clickCount]
7125                                       pressure: [e pressure]];
7126       [super mouseUp: fake_event];
7127     }
7129   if (part != NSScrollerKnob)
7130     [self sendScrollEventAtLoc: pos fromEvent: e];
7134 /* Called as we manually track scroller drags, rather than superclass. */
7135 - (void)mouseDragged: (NSEvent *)e
7137     NSRect sr;
7138     double loc, pos;
7140     NSTRACE (EmacsScroller_mouseDragged);
7142       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
7143                       toView: nil];
7144       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
7146       if (loc <= 0.0)
7147         {
7148           loc = 0.0;
7149         }
7150       else if (loc >= NSHeight (sr) + last_mouse_offset)
7151         {
7152           loc = NSHeight (sr) + last_mouse_offset;
7153         }
7155       pos = (loc - last_mouse_offset) / NSHeight (sr);
7156       [self sendScrollEventAtLoc: pos fromEvent: e];
7160 - (void)mouseUp: (NSEvent *)e
7162   if (scroll_repeat_entry)
7163     {
7164       [scroll_repeat_entry invalidate];
7165       [scroll_repeat_entry release];
7166       scroll_repeat_entry = nil;
7167     }
7168   last_hit_part = 0;
7172 /* treat scrollwheel events in the bar as though they were in the main window */
7173 - (void) scrollWheel: (NSEvent *)theEvent
7175   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
7176   [view mouseDown: theEvent];
7179 @end  /* EmacsScroller */
7182 #ifdef NS_IMPL_GNUSTEP
7183 /* Dummy class to get rid of startup warnings.  */
7184 @implementation EmacsDocument
7186 @end
7187 #endif
7190 /* ==========================================================================
7192    Font-related functions; these used to be in nsfaces.m
7194    ========================================================================== */
7197 Lisp_Object
7198 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
7200   struct font *font = XFONT_OBJECT (font_object);
7202   if (fontset < 0)
7203     fontset = fontset_from_font (font_object);
7204   FRAME_FONTSET (f) = fontset;
7206   if (FRAME_FONT (f) == font)
7207     /* This font is already set in frame F.  There's nothing more to
7208        do.  */
7209     return font_object;
7211   FRAME_FONT (f) = font;
7213   FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
7214   FRAME_COLUMN_WIDTH (f) = font->average_width;
7215   FRAME_LINE_HEIGHT (f) = font->height;
7217   compute_fringe_widths (f, 1);
7219   /* Compute the scroll bar width in character columns.  */
7220   if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
7221     {
7222       int wid = FRAME_COLUMN_WIDTH (f);
7223       FRAME_CONFIG_SCROLL_BAR_COLS (f)
7224         = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
7225     }
7226   else
7227     {
7228       int wid = FRAME_COLUMN_WIDTH (f);
7229       FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
7230     }
7232   /* Now make the frame display the given font.  */
7233   if (FRAME_NS_WINDOW (f) != 0)
7234         x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
7236   return font_object;
7240 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
7241 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
7242          in 1.43. */
7244 const char *
7245 ns_xlfd_to_fontname (const char *xlfd)
7246 /* --------------------------------------------------------------------------
7247     Convert an X font name (XLFD) to an NS font name.
7248     Only family is used.
7249     The string returned is temporarily allocated.
7250    -------------------------------------------------------------------------- */
7252   char *name = xmalloc (180);
7253   int i, len;
7254   const char *ret;
7256   if (!strncmp (xlfd, "--", 2))
7257     sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
7258   else
7259     sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
7261   /* stopgap for malformed XLFD input */
7262   if (strlen (name) == 0)
7263     strcpy (name, "Monaco");
7265   /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
7266      also uppercase after '-' or ' ' */
7267   name[0] = c_toupper (name[0]);
7268   for (len =strlen (name), i =0; i<len; i++)
7269     {
7270       if (name[i] == '$')
7271         {
7272           name[i] = '-';
7273           if (i+1<len)
7274             name[i+1] = c_toupper (name[i+1]);
7275         }
7276       else if (name[i] == '_')
7277         {
7278           name[i] = ' ';
7279           if (i+1<len)
7280             name[i+1] = c_toupper (name[i+1]);
7281         }
7282     }
7283 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name);  */
7284   ret = [[NSString stringWithUTF8String: name] UTF8String];
7285   xfree (name);
7286   return ret;
7290 void
7291 syms_of_nsterm (void)
7293   NSTRACE (syms_of_nsterm);
7295   ns_antialias_threshold = 10.0;
7297   /* from 23+ we need to tell emacs what modifiers there are.. */
7298   DEFSYM (Qmodifier_value, "modifier-value");
7299   DEFSYM (Qalt, "alt");
7300   DEFSYM (Qhyper, "hyper");
7301   DEFSYM (Qmeta, "meta");
7302   DEFSYM (Qsuper, "super");
7303   DEFSYM (Qcontrol, "control");
7304   DEFSYM (QUTF8_STRING, "UTF8_STRING");
7306   Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
7307   Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
7308   Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
7309   Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
7310   Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
7312   DEFVAR_LISP ("ns-input-file", ns_input_file,
7313               "The file specified in the last NS event.");
7314   ns_input_file =Qnil;
7316   DEFVAR_LISP ("ns-input-text", ns_input_text,
7317               "The data received in the last NS text drag event.");
7318   ns_input_text =Qnil;
7320   DEFVAR_LISP ("ns-working-text", ns_working_text,
7321               "String for visualizing working composition sequence.");
7322   ns_working_text =Qnil;
7324   DEFVAR_LISP ("ns-input-font", ns_input_font,
7325               "The font specified in the last NS event.");
7326   ns_input_font =Qnil;
7328   DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
7329               "The fontsize specified in the last NS event.");
7330   ns_input_fontsize =Qnil;
7332   DEFVAR_LISP ("ns-input-line", ns_input_line,
7333                "The line specified in the last NS event.");
7334   ns_input_line =Qnil;
7336   DEFVAR_LISP ("ns-input-color", ns_input_color,
7337                "The color specified in the last NS event.");
7338   ns_input_color =Qnil;
7340   DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
7341                "The service name specified in the last NS event.");
7342   ns_input_spi_name =Qnil;
7344   DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
7345                "The service argument specified in the last NS event.");
7346   ns_input_spi_arg =Qnil;
7348   DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
7349                "This variable describes the behavior of the alternate or option key.\n\
7350 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7351 Set to none means that the alternate / option key is not interpreted by Emacs\n\
7352 at all, allowing it to be used at a lower level for accented character entry.");
7353   ns_alternate_modifier = Qmeta;
7355   DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
7356                "This variable describes the behavior of the right alternate or option key.\n\
7357 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7358 Set to left means be the same key as `ns-alternate-modifier'.\n\
7359 Set to none means that the alternate / option key is not interpreted by Emacs\n\
7360 at all, allowing it to be used at a lower level for accented character entry.");
7361   ns_right_alternate_modifier = Qleft;
7363   DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
7364                "This variable describes the behavior of the command key.\n\
7365 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
7366   ns_command_modifier = Qsuper;
7368   DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
7369                "This variable describes the behavior of the right command key.\n\
7370 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7371 Set to left means be the same key as `ns-command-modifier'.\n\
7372 Set to none means that the command / option key is not interpreted by Emacs\n\
7373 at all, allowing it to be used at a lower level for accented character entry.");
7374   ns_right_command_modifier = Qleft;
7376   DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
7377                "This variable describes the behavior of the control key.\n\
7378 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
7379   ns_control_modifier = Qcontrol;
7381   DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
7382                "This variable describes the behavior of the right control key.\n\
7383 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7384 Set to left means be the same key as `ns-control-modifier'.\n\
7385 Set to none means that the control / option key is not interpreted by Emacs\n\
7386 at all, allowing it to be used at a lower level for accented character entry.");
7387   ns_right_control_modifier = Qleft;
7389   DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
7390                "This variable describes the behavior of the function key (on laptops).\n\
7391 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7392 Set to none means that the function key is not interpreted by Emacs at all,\n\
7393 allowing it to be used at a lower level for accented character entry.");
7394   ns_function_modifier = Qnone;
7396   DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
7397                "Non-nil (the default) means to render text antialiased.");
7398   ns_antialias_text = Qt;
7400   DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
7401                "Whether to confirm application quit using dialog.");
7402   ns_confirm_quit = Qnil;
7404   staticpro (&ns_display_name_list);
7405   ns_display_name_list = Qnil;
7407   staticpro (&last_mouse_motion_frame);
7408   last_mouse_motion_frame = Qnil;
7410   DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
7411                doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
7412 Only works on OSX 10.6 or later.  */);
7413   ns_auto_hide_menu_bar = Qnil;
7415   DEFVAR_BOOL ("ns-use-native-fullscreen", ns_use_native_fullscreen,
7416      doc: /*Non-nil means to use native fullscreen on OSX >= 10.7.
7417 Nil means use fullscreen the old (< 10.7) way.  The old way works better with
7418 multiple monitors, but lacks tool bar.  This variable is ignored on OSX < 10.7.
7419 Default is t for OSX >= 10.7, nil otherwise. */);
7420 #ifdef HAVE_NATIVE_FS
7421   ns_use_native_fullscreen = YES;
7422 #else
7423   ns_use_native_fullscreen = NO;
7424 #endif
7425   ns_last_use_native_fullscreen = ns_use_native_fullscreen;
7427   /* TODO: move to common code */
7428   DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
7429                doc: /* Which toolkit scroll bars Emacs uses, if any.
7430 A value of nil means Emacs doesn't use toolkit scroll bars.
7431 With the X Window system, the value is a symbol describing the
7432 X toolkit.  Possible values are: gtk, motif, xaw, or xaw3d.
7433 With MS Windows or Nextstep, the value is t.  */);
7434   Vx_toolkit_scroll_bars = Qt;
7436   DEFVAR_BOOL ("x-use-underline-position-properties",
7437                x_use_underline_position_properties,
7438      doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
7439 A value of nil means ignore them.  If you encounter fonts with bogus
7440 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
7441 to 4.1, set this to nil. */);
7442   x_use_underline_position_properties = 0;
7444   DEFVAR_BOOL ("x-underline-at-descent-line",
7445                x_underline_at_descent_line,
7446      doc: /* Non-nil means to draw the underline at the same place as the descent line.
7447 A value of nil means to draw the underline according to the value of the
7448 variable `x-use-underline-position-properties', which is usually at the
7449 baseline level.  The default value is nil.  */);
7450   x_underline_at_descent_line = 0;
7452   /* Tell emacs about this window system. */
7453   Fprovide (intern ("ns"), Qnil);