Fixed a typo in emacsclientw.exe's name.
[emacs.git] / src / nsterm.m
blob9baa95a506b0b24b64391265369cc151d6fd9844
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 /* call tracing */
64 #if 0
65 int term_trace_num = 0;
66 #define NSTRACE(x)        fprintf (stderr, "%s:%d: [%d] " #x "\n",         \
67                                 __FILE__, __LINE__, ++term_trace_num)
68 #else
69 #define NSTRACE(x)
70 #endif
72 extern NSString *NSMenuDidBeginTrackingNotification;
74 /* ==========================================================================
76     Local declarations
78    ========================================================================== */
80 /* Convert a symbol indexed with an NSxxx value to a value as defined
81    in keyboard.c (lispy_function_key). I hope this is a correct way
82    of doing things... */
83 static unsigned convert_ns_to_X_keysym[] =
85   NSHomeFunctionKey,            0x50,
86   NSLeftArrowFunctionKey,       0x51,
87   NSUpArrowFunctionKey,         0x52,
88   NSRightArrowFunctionKey,      0x53,
89   NSDownArrowFunctionKey,       0x54,
90   NSPageUpFunctionKey,          0x55,
91   NSPageDownFunctionKey,        0x56,
92   NSEndFunctionKey,             0x57,
93   NSBeginFunctionKey,           0x58,
94   NSSelectFunctionKey,          0x60,
95   NSPrintFunctionKey,           0x61,
96   NSClearLineFunctionKey,       0x0B,
97   NSExecuteFunctionKey,         0x62,
98   NSInsertFunctionKey,          0x63,
99   NSUndoFunctionKey,            0x65,
100   NSRedoFunctionKey,            0x66,
101   NSMenuFunctionKey,            0x67,
102   NSFindFunctionKey,            0x68,
103   NSHelpFunctionKey,            0x6A,
104   NSBreakFunctionKey,           0x6B,
106   NSF1FunctionKey,              0xBE,
107   NSF2FunctionKey,              0xBF,
108   NSF3FunctionKey,              0xC0,
109   NSF4FunctionKey,              0xC1,
110   NSF5FunctionKey,              0xC2,
111   NSF6FunctionKey,              0xC3,
112   NSF7FunctionKey,              0xC4,
113   NSF8FunctionKey,              0xC5,
114   NSF9FunctionKey,              0xC6,
115   NSF10FunctionKey,             0xC7,
116   NSF11FunctionKey,             0xC8,
117   NSF12FunctionKey,             0xC9,
118   NSF13FunctionKey,             0xCA,
119   NSF14FunctionKey,             0xCB,
120   NSF15FunctionKey,             0xCC,
121   NSF16FunctionKey,             0xCD,
122   NSF17FunctionKey,             0xCE,
123   NSF18FunctionKey,             0xCF,
124   NSF19FunctionKey,             0xD0,
125   NSF20FunctionKey,             0xD1,
126   NSF21FunctionKey,             0xD2,
127   NSF22FunctionKey,             0xD3,
128   NSF23FunctionKey,             0xD4,
129   NSF24FunctionKey,             0xD5,
131   NSBackspaceCharacter,         0x08,  /* 8: Not on some KBs. */
132   NSDeleteCharacter,            0xFF,  /* 127: Big 'delete' key upper right. */
133   NSDeleteFunctionKey,          0x9F,  /* 63272: Del forw key off main array. */
135   NSTabCharacter,               0x09,
136   0x19,                         0x09,  /* left tab->regular since pass shift */
137   NSCarriageReturnCharacter,    0x0D,
138   NSNewlineCharacter,           0x0D,
139   NSEnterCharacter,             0x8D,
141   0x41|NSNumericPadKeyMask,     0xAE,  /* KP_Decimal */
142   0x43|NSNumericPadKeyMask,     0xAA,  /* KP_Multiply */
143   0x45|NSNumericPadKeyMask,     0xAB,  /* KP_Add */
144   0x4B|NSNumericPadKeyMask,     0xAF,  /* KP_Divide */
145   0x4E|NSNumericPadKeyMask,     0xAD,  /* KP_Subtract */
146   0x51|NSNumericPadKeyMask,     0xBD,  /* KP_Equal */
147   0x52|NSNumericPadKeyMask,     0xB0,  /* KP_0 */
148   0x53|NSNumericPadKeyMask,     0xB1,  /* KP_1 */
149   0x54|NSNumericPadKeyMask,     0xB2,  /* KP_2 */
150   0x55|NSNumericPadKeyMask,     0xB3,  /* KP_3 */
151   0x56|NSNumericPadKeyMask,     0xB4,  /* KP_4 */
152   0x57|NSNumericPadKeyMask,     0xB5,  /* KP_5 */
153   0x58|NSNumericPadKeyMask,     0xB6,  /* KP_6 */
154   0x59|NSNumericPadKeyMask,     0xB7,  /* KP_7 */
155   0x5B|NSNumericPadKeyMask,     0xB8,  /* KP_8 */
156   0x5C|NSNumericPadKeyMask,     0xB9,  /* KP_9 */
158   0x1B,                         0x1B   /* escape */
161 static Lisp_Object Qmodifier_value;
162 Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper;
163 extern Lisp_Object Qcursor_color, Qcursor_type, Qns, Qleft;
165 static Lisp_Object QUTF8_STRING;
167 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
168    the maximum font size to NOT antialias.  On GNUstep there is currently
169    no way to control this behavior. */
170 float ns_antialias_threshold;
172 /* Used to pick up AppleHighlightColor on OS X */
173 NSString *ns_selection_color;
175 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
176 NSString *ns_app_name = @"Emacs";  /* default changed later */
178 /* Display variables */
179 struct ns_display_info *x_display_list; /* Chain of existing displays */
180 Lisp_Object ns_display_name_list;
181 long context_menu_value = 0;
183 /* display update */
184 NSPoint last_mouse_motion_position;
185 static NSRect last_mouse_glyph;
186 static Time last_mouse_movement_time = 0;
187 static Lisp_Object last_mouse_motion_frame;
188 static EmacsScroller *last_mouse_scroll_bar = nil;
189 static struct frame *ns_updating_frame;
190 static NSView *focus_view = NULL;
191 static int ns_window_num = 0;
192 #ifdef NS_IMPL_GNUSTEP
193 static NSRect uRect;
194 #endif
195 static BOOL gsaved = NO;
196 static BOOL ns_fake_keydown = NO;
197 int ns_tmp_flags; /* FIXME */
198 struct nsfont_info *ns_tmp_font; /* FIXME */
199 static BOOL ns_menu_bar_is_hidden = NO;
200 /*static int debug_lock = 0; */
202 /* event loop */
203 static BOOL send_appdefined = YES;
204 #define NO_APPDEFINED_DATA (-8)
205 static int last_appdefined_event_data = NO_APPDEFINED_DATA;
206 static NSTimer *timed_entry = 0;
207 static NSTimer *scroll_repeat_entry = nil;
208 static fd_set select_readfds, select_writefds;
209 enum { SELECT_HAVE_READ = 1, SELECT_HAVE_WRITE = 2, SELECT_HAVE_TMO = 4 };
210 static int select_nfds = 0, select_valid = 0;
211 static EMACS_TIME select_timeout = { 0, 0 };
212 static int selfds[2] = { -1, -1 };
213 static pthread_mutex_t select_mutex;
214 static int apploopnr = 0;
215 static NSAutoreleasePool *outerpool;
216 static struct input_event *emacs_event = NULL;
217 static struct input_event *q_event_ptr = NULL;
218 static int n_emacs_events_pending = 0;
219 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
220   *ns_pending_service_args;
221 static BOOL ns_do_open_file = NO;
222 static BOOL ns_last_use_native_fullscreen;
224 static struct {
225   struct input_event *q;
226   int nr, cap;
227 } hold_event_q = {
228   NULL, 0, 0
232  * State for pending menu activation:
233  * MENU_NONE     Normal state
234  * MENU_PENDING  A menu has been clicked on, but has been canceled so we can
235  *               run lisp to update the menu.
236  * MENU_OPENING  Menu is up to date, and the click event is redone so the menu
237  *               will open.
238  */
239 #define MENU_NONE 0
240 #define MENU_PENDING 1
241 #define MENU_OPENING 2
242 static int menu_will_open_state = MENU_NONE;
244 /* Saved position for menu click.  */
245 static CGPoint menu_mouse_point;
247 /* Title for the menu to open.  */
248 static char *menu_pending_title = 0;
250 /* Convert modifiers in a NeXTstep event to emacs style modifiers.  */
251 #define NS_FUNCTION_KEY_MASK 0x800000
252 #define NSLeftControlKeyMask    (0x000001 | NSControlKeyMask)
253 #define NSRightControlKeyMask   (0x002000 | NSControlKeyMask)
254 #define NSLeftCommandKeyMask    (0x000008 | NSCommandKeyMask)
255 #define NSRightCommandKeyMask   (0x000010 | NSCommandKeyMask)
256 #define NSLeftAlternateKeyMask  (0x000020 | NSAlternateKeyMask)
257 #define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
258 #define EV_MODIFIERS(e)                               \
259     ((([e modifierFlags] & NSHelpKeyMask) ?           \
260            hyper_modifier : 0)                        \
261      | (!EQ (ns_right_alternate_modifier, Qleft) && \
262         (([e modifierFlags] & NSRightAlternateKeyMask) \
263          == NSRightAlternateKeyMask) ? \
264            parse_solitary_modifier (ns_right_alternate_modifier) : 0) \
265      | (([e modifierFlags] & NSAlternateKeyMask) ?                 \
266            parse_solitary_modifier (ns_alternate_modifier) : 0)   \
267      | (([e modifierFlags] & NSShiftKeyMask) ?     \
268            shift_modifier : 0)                        \
269      | (!EQ (ns_right_control_modifier, Qleft) && \
270         (([e modifierFlags] & NSRightControlKeyMask) \
271          == NSRightControlKeyMask) ? \
272            parse_solitary_modifier (ns_right_control_modifier) : 0) \
273      | (([e modifierFlags] & NSControlKeyMask) ?      \
274            parse_solitary_modifier (ns_control_modifier) : 0)     \
275      | (([e modifierFlags] & NS_FUNCTION_KEY_MASK) ?  \
276            parse_solitary_modifier (ns_function_modifier) : 0)    \
277      | (!EQ (ns_right_command_modifier, Qleft) && \
278         (([e modifierFlags] & NSRightCommandKeyMask) \
279          == NSRightCommandKeyMask) ? \
280            parse_solitary_modifier (ns_right_command_modifier) : 0) \
281      | (([e modifierFlags] & NSCommandKeyMask) ?      \
282            parse_solitary_modifier (ns_command_modifier):0))
284 #define EV_UDMODIFIERS(e)                                      \
285     ((([e type] == NSLeftMouseDown) ? down_modifier : 0)       \
286      | (([e type] == NSRightMouseDown) ? down_modifier : 0)    \
287      | (([e type] == NSOtherMouseDown) ? down_modifier : 0)    \
288      | (([e type] == NSLeftMouseDragged) ? down_modifier : 0)  \
289      | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
290      | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
291      | (([e type] == NSLeftMouseUp)   ? up_modifier   : 0)     \
292      | (([e type] == NSRightMouseUp)   ? up_modifier   : 0)    \
293      | (([e type] == NSOtherMouseUp)   ? up_modifier   : 0))
295 #define EV_BUTTON(e)                                                         \
296     ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 :    \
297       (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
298      [e buttonNumber] - 1)
300 /* Convert the time field to a timestamp in milliseconds. */
301 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
303 /* This is a piece of code which is common to all the event handling
304    methods.  Maybe it should even be a function.  */
305 #define EV_TRAILER(e)                                                   \
306     {                                                                   \
307       XSETFRAME (emacs_event->frame_or_window, emacsframe);             \
308       if (e) emacs_event->timestamp = EV_TIMESTAMP (e);                 \
309       if (q_event_ptr)                                                  \
310         {                                                               \
311           n_emacs_events_pending++;                                     \
312           kbd_buffer_store_event_hold (emacs_event, q_event_ptr);       \
313         }                                                               \
314       else                                                              \
315         hold_event (emacs_event);                                       \
316       EVENT_INIT (*emacs_event);                                        \
317       ns_send_appdefined (-1);                                          \
318     }
320 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
322 /* TODO: get rid of need for these forward declarations */
323 static void ns_condemn_scroll_bars (struct frame *f);
324 static void ns_judge_scroll_bars (struct frame *f);
325 void x_set_frame_alpha (struct frame *f);
328 /* ==========================================================================
330     Utilities
332    ========================================================================== */
334 static void
335 hold_event (struct input_event *event)
337   if (hold_event_q.nr == hold_event_q.cap)
338     {
339       if (hold_event_q.cap == 0) hold_event_q.cap = 10;
340       else hold_event_q.cap *= 2;
341       hold_event_q.q = (struct input_event *)
342         xrealloc (hold_event_q.q, hold_event_q.cap * sizeof (*hold_event_q.q));
343     }
345   hold_event_q.q[hold_event_q.nr++] = *event;
346   /* Make sure ns_read_socket is called, i.e. we have input.  */
347   raise (SIGIO);
348   send_appdefined = YES;
351 static Lisp_Object
352 append2 (Lisp_Object list, Lisp_Object item)
353 /* --------------------------------------------------------------------------
354    Utility to append to a list
355    -------------------------------------------------------------------------- */
357   Lisp_Object array[2];
358   array[0] = list;
359   array[1] = Fcons (item, Qnil);
360   return Fnconc (2, &array[0]);
364 const char *
365 ns_etc_directory (void)
366 /* If running as a self-contained app bundle, return as a string the
367    filename of the etc directory, if present; else nil.  */
369   NSBundle *bundle = [NSBundle mainBundle];
370   NSString *resourceDir = [bundle resourcePath];
371   NSString *resourcePath;
372   NSFileManager *fileManager = [NSFileManager defaultManager];
373   BOOL isDir;
375   resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
376   if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
377     {
378       if (isDir) return [resourcePath UTF8String];
379     }
380   return NULL;
384 const char *
385 ns_exec_path (void)
386 /* If running as a self-contained app bundle, return as a path string
387    the filenames of the libexec and bin directories, ie libexec:bin.
388    Otherwise, return nil.
389    Normally, Emacs does not add its own bin/ directory to the PATH.
390    However, a self-contained NS build has a different layout, with
391    bin/ and libexec/ subdirectories in the directory that contains
392    Emacs.app itself.
393    We put libexec first, because init_callproc_1 uses the first
394    element to initialize exec-directory.  An alternative would be
395    for init_callproc to check for invocation-directory/libexec.
398   NSBundle *bundle = [NSBundle mainBundle];
399   NSString *resourceDir = [bundle resourcePath];
400   NSString *binDir = [bundle bundlePath];
401   NSString *resourcePath, *resourcePaths;
402   NSRange range;
403   NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
404   NSFileManager *fileManager = [NSFileManager defaultManager];
405   NSArray *paths;
406   NSEnumerator *pathEnum;
407   BOOL isDir;
409   range = [resourceDir rangeOfString: @"Contents"];
410   if (range.location != NSNotFound)
411     {
412       binDir = [binDir stringByAppendingPathComponent: @"Contents"];
413 #ifdef NS_IMPL_COCOA
414       binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
415 #endif
416     }
418   paths = [binDir stringsByAppendingPaths:
419                 [NSArray arrayWithObjects: @"libexec", @"bin", nil]];
420   pathEnum = [paths objectEnumerator];
421   resourcePaths = @"";
423   while ((resourcePath = [pathEnum nextObject]))
424     {
425       if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
426         if (isDir)
427           {
428             if ([resourcePaths length] > 0)
429               resourcePaths
430                 = [resourcePaths stringByAppendingString: pathSeparator];
431             resourcePaths
432               = [resourcePaths stringByAppendingString: resourcePath];
433           }
434     }
435   if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
437   return NULL;
441 const char *
442 ns_load_path (void)
443 /* If running as a self-contained app bundle, return as a path string
444    the filenames of the site-lisp, lisp and leim directories.
445    Ie, site-lisp:lisp:leim.  Otherwise, return nil.  */
447   NSBundle *bundle = [NSBundle mainBundle];
448   NSString *resourceDir = [bundle resourcePath];
449   NSString *resourcePath, *resourcePaths;
450   NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
451   NSFileManager *fileManager = [NSFileManager defaultManager];
452   BOOL isDir;
453   NSArray *paths = [resourceDir stringsByAppendingPaths:
454                               [NSArray arrayWithObjects:
455                                          @"site-lisp", @"lisp", @"leim", nil]];
456   NSEnumerator *pathEnum = [paths objectEnumerator];
457   resourcePaths = @"";
459   /* Hack to skip site-lisp.  */
460   if (no_site_lisp) resourcePath = [pathEnum nextObject];
462   while ((resourcePath = [pathEnum nextObject]))
463     {
464       if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
465         if (isDir)
466           {
467             if ([resourcePaths length] > 0)
468               resourcePaths
469                 = [resourcePaths stringByAppendingString: pathSeparator];
470             resourcePaths
471               = [resourcePaths stringByAppendingString: resourcePath];
472           }
473     }
474   if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
476   return NULL;
479 static void
480 ns_timeout (int usecs)
481 /* --------------------------------------------------------------------------
482      Blocking timer utility used by ns_ring_bell
483    -------------------------------------------------------------------------- */
485   EMACS_TIME wakeup = add_emacs_time (current_emacs_time (),
486                                       make_emacs_time (0, usecs * 1000));
488   /* Keep waiting until past the time wakeup.  */
489   while (1)
490     {
491       EMACS_TIME timeout, now = current_emacs_time ();
492       if (EMACS_TIME_LE (wakeup, now))
493         break;
494       timeout = sub_emacs_time (wakeup, now);
496       /* Try to wait that long--but we might wake up sooner.  */
497       pselect (0, NULL, NULL, NULL, &timeout, NULL);
498     }
502 void
503 ns_release_object (void *obj)
504 /* --------------------------------------------------------------------------
505     Release an object (callable from C)
506    -------------------------------------------------------------------------- */
508     [(id)obj release];
512 void
513 ns_retain_object (void *obj)
514 /* --------------------------------------------------------------------------
515     Retain an object (callable from C)
516    -------------------------------------------------------------------------- */
518     [(id)obj retain];
522 void *
523 ns_alloc_autorelease_pool (void)
524 /* --------------------------------------------------------------------------
525      Allocate a pool for temporary objects (callable from C)
526    -------------------------------------------------------------------------- */
528   return [[NSAutoreleasePool alloc] init];
532 void
533 ns_release_autorelease_pool (void *pool)
534 /* --------------------------------------------------------------------------
535      Free a pool and temporary objects it refers to (callable from C)
536    -------------------------------------------------------------------------- */
538   ns_release_object (pool);
543 /* ==========================================================================
545     Focus (clipping) and screen update
547    ========================================================================== */
550 // Window constraining
551 // -------------------
553 // To ensure that the windows are not placed under the menu bar, they
554 // are typically moved by the call-back constrainFrameRect. However,
555 // by overriding it, it's possible to inhibit this, leaving the window
556 // in it's original position.
558 // It's possible to hide the menu bar. However, technically, it's only
559 // possible to hide it when the application is active. To ensure that
560 // this work properly, the menu bar and window constraining are
561 // deferred until the application becomes active.
563 // Even though it's not possible to manually move a window above the
564 // top of the screen, it is allowed if it's done programmatically,
565 // when the menu is hidden. This allows the editable area to cover the
566 // full screen height.
568 // Test cases
569 // ----------
571 // Use the following extra files:
573 //    init.el:
574 //       ;; Hide menu and place frame slightly above the top of the screen.
575 //       (setq ns-auto-hide-menu-bar t)
576 //       (set-frame-position (selected-frame) 0 -20)
578 // Test 1:
580 //    emacs -Q -l init.el
582 //    Result: No menu bar, and the title bar should be above the screen.
584 // Test 2:
586 //    emacs -Q
588 //    Result: Menu bar visible, frame placed immediately below the menu.
591 static void
592 ns_constrain_all_frames (void)
594   Lisp_Object tail, frame;
596   FOR_EACH_FRAME (tail, frame)
597     {
598       struct frame *f = XFRAME (frame);
599       if (FRAME_NS_P (f))
600         {
601           NSView *view = FRAME_NS_VIEW (f);
602           /* This no-op will trigger the default window placing
603            * constraint system. */
604           f->output_data.ns->dont_constrain = 0;
605           [[view window] setFrameOrigin:[[view window] frame].origin];
606         }
607     }
611 /* True, if the menu bar should be hidden.  */
613 static BOOL
614 ns_menu_bar_should_be_hidden (void)
616   return !NILP (ns_auto_hide_menu_bar)
617     && [NSApp respondsToSelector:@selector(setPresentationOptions:)];
621 /* Show or hide the menu bar, based on user setting.  */
623 static void
624 ns_update_auto_hide_menu_bar (void)
626 #ifdef NS_IMPL_COCOA
627 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
628   block_input ();
630   NSTRACE (ns_update_auto_hide_menu_bar);
632   if (NSApp != nil
633       && [NSApp isActive]
634       && [NSApp respondsToSelector:@selector(setPresentationOptions:)])
635     {
636       // Note, "setPresentationOptions" triggers an error unless the
637       // application is active.
638       BOOL menu_bar_should_be_hidden = ns_menu_bar_should_be_hidden ();
640       if (menu_bar_should_be_hidden != ns_menu_bar_is_hidden)
641         {
642           NSApplicationPresentationOptions options
643             = NSApplicationPresentationAutoHideDock;
645           if (menu_bar_should_be_hidden)
646             options |= NSApplicationPresentationAutoHideMenuBar;
648           [NSApp setPresentationOptions: options];
650           ns_menu_bar_is_hidden = menu_bar_should_be_hidden;
652           if (!ns_menu_bar_is_hidden)
653             {
654               ns_constrain_all_frames ();
655             }
656         }
657     }
659   unblock_input ();
660 #endif
661 #endif
665 static void
666 ns_update_begin (struct frame *f)
667 /* --------------------------------------------------------------------------
668    Prepare for a grouped sequence of drawing calls
669    external (RIF) call; whole frame, called before update_window_begin
670    -------------------------------------------------------------------------- */
672   NSView *view = FRAME_NS_VIEW (f);
673   NSRect r = [view frame];
674   NSBezierPath *bp;
675   NSTRACE (ns_update_begin);
677   ns_update_auto_hide_menu_bar ();
679   ns_updating_frame = f;
680   [view lockFocus];
682   /* drawRect may have been called for say the minibuffer, and then clip path
683      is for the minibuffer.  But the display engine may draw more because
684      we have set the frame as garbaged.  So reset clip path to the whole
685      view.  */
686   bp = [[NSBezierPath bezierPathWithRect: r] retain];
687   [bp setClip];
688   [bp release];
690 #ifdef NS_IMPL_GNUSTEP
691   uRect = NSMakeRect (0, 0, 0, 0);
692 #endif
696 static void
697 ns_update_window_begin (struct window *w)
698 /* --------------------------------------------------------------------------
699    Prepare for a grouped sequence of drawing calls
700    external (RIF) call; for one window, called after update_begin
701    -------------------------------------------------------------------------- */
703   struct frame *f = XFRAME (WINDOW_FRAME (w));
704  Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
705   NSTRACE (ns_update_window_begin);
706   updated_window = w;
707   set_output_cursor (&w->cursor);
709   block_input ();
711   if (f == hlinfo->mouse_face_mouse_frame)
712     {
713       /* Don't do highlighting for mouse motion during the update.  */
714       hlinfo->mouse_face_defer = 1;
716         /* If the frame needs to be redrawn,
717            simply forget about any prior mouse highlighting.  */
718       if (FRAME_GARBAGED_P (f))
719         hlinfo->mouse_face_window = Qnil;
721       /* (further code for mouse faces ifdef'd out in other terms elided) */
722     }
724   unblock_input ();
728 static void
729 ns_update_window_end (struct window *w, int cursor_on_p,
730                       int mouse_face_overwritten_p)
731 /* --------------------------------------------------------------------------
732    Finished a grouped sequence of drawing calls
733    external (RIF) call; for one window called before update_end
734    -------------------------------------------------------------------------- */
736   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (XFRAME (w->frame));
738   /* note: this fn is nearly identical in all terms */
739   if (!w->pseudo_window_p)
740     {
741       block_input ();
743       if (cursor_on_p)
744         display_and_set_cursor (w, 1,
745                                 output_cursor.hpos, output_cursor.vpos,
746                                 output_cursor.x, output_cursor.y);
748       if (draw_window_fringes (w, 1))
749         x_draw_vertical_border (w);
751       unblock_input ();
752     }
754   /* If a row with mouse-face was overwritten, arrange for
755      frame_up_to_date to redisplay the mouse highlight.  */
756   if (mouse_face_overwritten_p)
757     {
758       hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
759       hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
760       hlinfo->mouse_face_window = Qnil;
761     }
763   updated_window = NULL;
764   NSTRACE (update_window_end);
768 static void
769 ns_update_end (struct frame *f)
770 /* --------------------------------------------------------------------------
771    Finished a grouped sequence of drawing calls
772    external (RIF) call; for whole frame, called after update_window_end
773    -------------------------------------------------------------------------- */
775   NSView *view = FRAME_NS_VIEW (f);
777 /*   if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
778     MOUSE_HL_INFO (f)->mouse_face_defer = 0;
780     block_input ();
782 #ifdef NS_IMPL_GNUSTEP
783   /* trigger flush only in the rectangle we tracked as being drawn */
784   [view unlockFocusNeedsFlush: NO];
785 /*fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", uRect.origin.x, uRect.origin.y, uRect.size.width, uRect.size.height); */
786   [view lockFocusInRect: uRect];
787 #endif
789   [view unlockFocus];
790   [[view window] flushWindow];
792   unblock_input ();
793   ns_updating_frame = NULL;
794   NSTRACE (ns_update_end);
798 static void
799 ns_flush (struct frame *f)
800 /* --------------------------------------------------------------------------
801    external (RIF) call
802    NS impl is no-op since currently we flush in ns_update_end and elsewhere
803    -------------------------------------------------------------------------- */
805     NSTRACE (ns_flush);
809 static void
810 ns_focus (struct frame *f, NSRect *r, int n)
811 /* --------------------------------------------------------------------------
812    Internal: Focus on given frame.  During small local updates this is used to
813      draw, however during large updates, ns_update_begin and ns_update_end are
814      called to wrap the whole thing, in which case these calls are stubbed out.
815      Except, on GNUstep, we accumulate the rectangle being drawn into, because
816      the back end won't do this automatically, and will just end up flushing
817      the entire window.
818    -------------------------------------------------------------------------- */
820 //  NSTRACE (ns_focus);
821 #ifdef NS_IMPL_GNUSTEP
822   NSRect u;
823     if (n == 2)
824       u = NSUnionRect (r[0], r[1]);
825     else if (r)
826       u = *r;
827 #endif
828 /* static int c =0;
829    fprintf (stderr, "focus: %d", c++);
830    if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
831    fprintf (stderr, "\n"); */
833   if (f != ns_updating_frame)
834     {
835       NSView *view = FRAME_NS_VIEW (f);
836       if (view != focus_view)
837         {
838           if (focus_view != NULL)
839             {
840               [focus_view unlockFocus];
841               [[focus_view window] flushWindow];
842 /*debug_lock--; */
843             }
845           if (view)
846 #ifdef NS_IMPL_GNUSTEP
847             r ? [view lockFocusInRect: u] : [view lockFocus];
848 #else
849             [view lockFocus];
850 #endif
851           focus_view = view;
852 /*if (view) debug_lock++; */
853         }
854 #ifdef NS_IMPL_GNUSTEP
855       else
856         {
857           /* more than one rect being drawn into */
858           if (view && r)
859             {
860               [view unlockFocus]; /* add prev rect to redraw list */
861               [view lockFocusInRect: u]; /* focus for draw in new rect */
862             }
863         }
864 #endif
865     }
866 #ifdef NS_IMPL_GNUSTEP
867   else
868     {
869       /* in batch mode, but in GNUstep must still track rectangles explicitly */
870       uRect = (r ? NSUnionRect (uRect, u) : [FRAME_NS_VIEW (f) visibleRect]);
871     }
872 #endif
874   /* clipping */
875   if (r)
876     {
877       [[NSGraphicsContext currentContext] saveGraphicsState];
878       if (n == 2)
879         NSRectClipList (r, 2);
880       else
881         NSRectClip (*r);
882       gsaved = YES;
883     }
887 static void
888 ns_unfocus (struct frame *f)
889 /* --------------------------------------------------------------------------
890      Internal: Remove focus on given frame
891    -------------------------------------------------------------------------- */
893 //  NSTRACE (ns_unfocus);
895   if (gsaved)
896     {
897       [[NSGraphicsContext currentContext] restoreGraphicsState];
898       gsaved = NO;
899     }
901   if (f != ns_updating_frame)
902     {
903       if (focus_view != NULL)
904         {
905           [focus_view unlockFocus];
906           [[focus_view window] flushWindow];
907           focus_view = NULL;
908 /*debug_lock--; */
909         }
910     }
914 static void
915 ns_clip_to_row (struct window *w, struct glyph_row *row, int area, BOOL gc)
916 /* --------------------------------------------------------------------------
917      Internal (but parallels other terms): Focus drawing on given row
918    -------------------------------------------------------------------------- */
920   struct frame *f = XFRAME (WINDOW_FRAME (w));
921   NSRect clip_rect;
922   int window_x, window_y, window_width;
924   window_box (w, area, &window_x, &window_y, &window_width, 0);
926   clip_rect.origin.x = window_x;
927   clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
928   clip_rect.origin.y = max (clip_rect.origin.y, window_y);
929   clip_rect.size.width = window_width;
930   clip_rect.size.height = row->visible_height;
932   ns_focus (f, &clip_rect, 1);
936 static void
937 ns_ring_bell (struct frame *f)
938 /* --------------------------------------------------------------------------
939      "Beep" routine
940    -------------------------------------------------------------------------- */
942   NSTRACE (ns_ring_bell);
943   if (visible_bell)
944     {
945       NSAutoreleasePool *pool;
946       struct frame *frame = SELECTED_FRAME ();
947       NSView *view;
949       block_input ();
950       pool = [[NSAutoreleasePool alloc] init];
952       view = FRAME_NS_VIEW (frame);
953       if (view != nil)
954         {
955           NSRect r, surr;
956           NSPoint dim = NSMakePoint (128, 128);
958           r = [view bounds];
959           r.origin.x += (r.size.width - dim.x) / 2;
960           r.origin.y += (r.size.height - dim.y) / 2;
961           r.size.width = dim.x;
962           r.size.height = dim.y;
963           surr = NSInsetRect (r, -2, -2);
964           ns_focus (frame, &surr, 1);
965           [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
966           [ns_lookup_indexed_color (NS_FACE_FOREGROUND
967                                       (FRAME_DEFAULT_FACE (frame)), frame) set];
968           NSRectFill (r);
969           [[view window] flushWindow];
970           ns_timeout (150000);
971           [[view window] restoreCachedImage];
972           [[view window] flushWindow];
973           ns_unfocus (frame);
974         }
975       [pool release];
976       unblock_input ();
977     }
978   else
979     {
980       NSBeep ();
981     }
985 static void
986 ns_reset_terminal_modes (struct terminal *terminal)
987 /*  Externally called as hook */
989   NSTRACE (ns_reset_terminal_modes);
993 static void
994 ns_set_terminal_modes (struct terminal *terminal)
995 /*  Externally called as hook */
997   NSTRACE (ns_set_terminal_modes);
1002 /* ==========================================================================
1004     Frame / window manager related functions
1006    ========================================================================== */
1009 static void
1010 ns_raise_frame (struct frame *f)
1011 /* --------------------------------------------------------------------------
1012      Bring window to foreground and make it active
1013    -------------------------------------------------------------------------- */
1015   NSView *view = FRAME_NS_VIEW (f);
1016   check_ns ();
1017   block_input ();
1018   if (FRAME_VISIBLE_P (f))
1019     [[view window] makeKeyAndOrderFront: NSApp];
1020   unblock_input ();
1024 static void
1025 ns_lower_frame (struct frame *f)
1026 /* --------------------------------------------------------------------------
1027      Send window to back
1028    -------------------------------------------------------------------------- */
1030   NSView *view = FRAME_NS_VIEW (f);
1031   check_ns ();
1032   block_input ();
1033   [[view window] orderBack: NSApp];
1034   unblock_input ();
1038 static void
1039 ns_frame_raise_lower (struct frame *f, int raise)
1040 /* --------------------------------------------------------------------------
1041      External (hook)
1042    -------------------------------------------------------------------------- */
1044   NSTRACE (ns_frame_raise_lower);
1046   if (raise)
1047     ns_raise_frame (f);
1048   else
1049     ns_lower_frame (f);
1053 static void
1054 ns_frame_rehighlight (struct frame *frame)
1055 /* --------------------------------------------------------------------------
1056      External (hook): called on things like window switching within frame
1057    -------------------------------------------------------------------------- */
1059   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
1060   struct frame *old_highlight = dpyinfo->x_highlight_frame;
1062   NSTRACE (ns_frame_rehighlight);
1063   if (dpyinfo->x_focus_frame)
1064     {
1065       dpyinfo->x_highlight_frame
1066         = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1067            ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1068            : dpyinfo->x_focus_frame);
1069       if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
1070         {
1071           fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
1072           dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
1073         }
1074     }
1075   else
1076       dpyinfo->x_highlight_frame = 0;
1078   if (dpyinfo->x_highlight_frame &&
1079          dpyinfo->x_highlight_frame != old_highlight)
1080     {
1081       if (old_highlight)
1082         {
1083           x_update_cursor (old_highlight, 1);
1084           x_set_frame_alpha (old_highlight);
1085         }
1086       if (dpyinfo->x_highlight_frame)
1087         {
1088           x_update_cursor (dpyinfo->x_highlight_frame, 1);
1089           x_set_frame_alpha (dpyinfo->x_highlight_frame);
1090         }
1091     }
1095 void
1096 x_make_frame_visible (struct frame *f)
1097 /* --------------------------------------------------------------------------
1098      External: Show the window (X11 semantics)
1099    -------------------------------------------------------------------------- */
1101   NSTRACE (x_make_frame_visible);
1102   /* XXX: at some points in past this was not needed, as the only place that
1103      called this (frame.c:Fraise_frame ()) also called raise_lower;
1104      if this ends up the case again, comment this out again. */
1105   if (!FRAME_VISIBLE_P (f))
1106     {
1107       EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1109       SET_FRAME_VISIBLE (f, 1);
1110       ns_raise_frame (f);
1112       /* Making a new frame from a fullscreen frame will make the new frame
1113          fullscreen also.  So skip handleFS as this will print an error.  */
1114       if ([view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH
1115           && [view isFullscreen])
1116         return;
1118       if (f->want_fullscreen != FULLSCREEN_NONE)
1119         {
1120           block_input ();
1121           [view handleFS];
1122           unblock_input ();
1123         }
1124     }
1128 void
1129 x_make_frame_invisible (struct frame *f)
1130 /* --------------------------------------------------------------------------
1131      External: Hide the window (X11 semantics)
1132    -------------------------------------------------------------------------- */
1134   NSView * view = FRAME_NS_VIEW (f);
1135   NSTRACE (x_make_frame_invisible);
1136   check_ns ();
1137   [[view window] orderOut: NSApp];
1138   SET_FRAME_VISIBLE (f, 0);
1139   SET_FRAME_ICONIFIED (f, 0);
1143 void
1144 x_iconify_frame (struct frame *f)
1145 /* --------------------------------------------------------------------------
1146      External: Iconify window
1147    -------------------------------------------------------------------------- */
1149   NSView * view = FRAME_NS_VIEW (f);
1150   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1151   NSTRACE (x_iconify_frame);
1152   check_ns ();
1154   if (dpyinfo->x_highlight_frame == f)
1155     dpyinfo->x_highlight_frame = 0;
1157   if ([[view window] windowNumber] <= 0)
1158     {
1159       /* the window is still deferred.  Make it very small, bring it
1160          on screen and order it out. */
1161       NSRect s = { { 100, 100}, {0, 0} };
1162       NSRect t;
1163       t = [[view window] frame];
1164       [[view window] setFrame: s display: NO];
1165       [[view window] orderBack: NSApp];
1166       [[view window] orderOut: NSApp];
1167       [[view window] setFrame: t display: NO];
1168     }
1169   [[view window] miniaturize: NSApp];
1172 /* Free X resources of frame F.  */
1174 void
1175 x_free_frame_resources (struct frame *f)
1177   NSView *view = FRAME_NS_VIEW (f);
1178   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1179   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1180   NSTRACE (x_free_frame_resources);
1181   check_ns ();
1183   [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1185   block_input ();
1187   free_frame_menubar (f);
1189   if (FRAME_FACE_CACHE (f))
1190     free_frame_faces (f);
1192   if (f == dpyinfo->x_focus_frame)
1193     dpyinfo->x_focus_frame = 0;
1194   if (f == dpyinfo->x_highlight_frame)
1195     dpyinfo->x_highlight_frame = 0;
1196   if (f == hlinfo->mouse_face_mouse_frame)
1197     {
1198       hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
1199       hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
1200       hlinfo->mouse_face_window = Qnil;
1201       hlinfo->mouse_face_mouse_frame = 0;
1202     }
1204   if (f->output_data.ns->miniimage != nil)
1205     [f->output_data.ns->miniimage release];
1207   [[view window] close];
1208   [view release];
1210   xfree (f->output_data.ns);
1212   unblock_input ();
1215 void
1216 x_destroy_window (struct frame *f)
1217 /* --------------------------------------------------------------------------
1218      External: Delete the window
1219    -------------------------------------------------------------------------- */
1221   NSTRACE (x_destroy_window);
1222   check_ns ();
1223   x_free_frame_resources (f);
1224   ns_window_num--;
1228 void
1229 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1230 /* --------------------------------------------------------------------------
1231      External: Position the window
1232    -------------------------------------------------------------------------- */
1234   NSView *view = FRAME_NS_VIEW (f);
1235   NSArray *screens = [NSScreen screens];
1236   NSScreen *fscreen = [screens objectAtIndex: 0];
1237   NSScreen *screen = [[view window] screen];
1239   NSTRACE (x_set_offset);
1241   block_input ();
1243   f->left_pos = xoff;
1244   f->top_pos = yoff;
1246   if (view != nil && screen && fscreen)
1247     {
1248       f->left_pos = f->size_hint_flags & XNegative
1249         ? [screen visibleFrame].size.width + f->left_pos - FRAME_PIXEL_WIDTH (f)
1250         : f->left_pos;
1251       /* We use visibleFrame here to take menu bar into account.
1252          Ideally we should also adjust left/top with visibleFrame.origin.  */
1254       f->top_pos = f->size_hint_flags & YNegative
1255         ? ([screen visibleFrame].size.height + f->top_pos
1256            - FRAME_PIXEL_HEIGHT (f) - FRAME_NS_TITLEBAR_HEIGHT (f)
1257            - FRAME_TOOLBAR_HEIGHT (f))
1258         : f->top_pos;
1259 #ifdef NS_IMPL_GNUSTEP
1260       if (f->left_pos < 100)
1261         f->left_pos = 100;  /* don't overlap menu */
1262 #endif
1263       /* Constrain the setFrameTopLeftPoint so we don't move behind the
1264          menu bar.  */
1265       f->output_data.ns->dont_constrain = 0;
1266       [[view window] setFrameTopLeftPoint:
1267                        NSMakePoint (SCREENMAXBOUND (f->left_pos),
1268                                     SCREENMAXBOUND ([fscreen frame].size.height
1269                                                     - NS_TOP_POS (f)))];
1270       f->size_hint_flags &= ~(XNegative|YNegative);
1271     }
1273   unblock_input ();
1277 void
1278 x_set_window_size (struct frame *f, int change_grav, int cols, int rows)
1279 /* --------------------------------------------------------------------------
1280      Adjust window pixel size based on given character grid size
1281      Impl is a bit more complex than other terms, need to do some
1282      internal clipping.
1283    -------------------------------------------------------------------------- */
1285   EmacsView *view = FRAME_NS_VIEW (f);
1286   NSWindow *window = [view window];
1287   NSRect wr = [window frame];
1288   int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1289   int pixelwidth, pixelheight;
1291   NSTRACE (x_set_window_size);
1293   if (view == nil)
1294     return;
1296 /*fprintf (stderr, "\tsetWindowSize: %d x %d, font size %d x %d\n", cols, rows, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f)); */
1298   block_input ();
1300   check_frame_size (f, &rows, &cols);
1302   f->scroll_bar_actual_width = NS_SCROLL_BAR_WIDTH (f);
1303   compute_fringe_widths (f, 0);
1305   pixelwidth =  FRAME_TEXT_COLS_TO_PIXEL_WIDTH   (f, cols);
1306   pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
1308   /* If we have a toolbar, take its height into account. */
1309   if (tb && ! [view isFullscreen])
1310     /* NOTE: previously this would generate wrong result if toolbar not
1311              yet displayed and fixing toolbar_height=32 helped, but
1312              now (200903) seems no longer needed */
1313     FRAME_TOOLBAR_HEIGHT (f) =
1314       NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1315         - FRAME_NS_TITLEBAR_HEIGHT (f);
1316   else
1317     FRAME_TOOLBAR_HEIGHT (f) = 0;
1319   wr.size.width = pixelwidth + f->border_width;
1320   wr.size.height = pixelheight;
1321   if (! [view isFullscreen])
1322     wr.size.height += FRAME_NS_TITLEBAR_HEIGHT (f)
1323       + FRAME_TOOLBAR_HEIGHT (f);
1325   /* Do not try to constrain to this screen.  We may have multiple
1326      screens, and want Emacs to span those.  Constraining to screen
1327      prevents that, and that is not nice to the user.  */
1328  if (f->output_data.ns->zooming)
1329    f->output_data.ns->zooming = 0;
1330  else
1331    wr.origin.y += FRAME_PIXEL_HEIGHT (f) - pixelheight;
1333   [view setRows: rows andColumns: cols];
1334   [window setFrame: wr display: YES];
1336 /*fprintf (stderr, "\tx_set_window_size %d, %d\t%d, %d\n", cols, rows, pixelwidth, pixelheight); */
1338   /* This is a trick to compensate for Emacs' managing the scrollbar area
1339      as a fixed number of standard character columns.  Instead of leaving
1340      blank space for the extra, we chopped it off above.  Now for
1341      left-hand scrollbars, we shift all rendering to the left by the
1342      difference between the real width and Emacs' imagined one.  For
1343      right-hand bars, don't worry about it since the extra is never used.
1344      (Obviously doesn't work for vertically split windows tho..) */
1345   {
1346     NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1347       ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1348                      - NS_SCROLL_BAR_WIDTH (f), 0)
1349       : NSMakePoint (0, 0);
1350     [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1351     [view setBoundsOrigin: origin];
1352   }
1354   change_frame_size (f, rows, cols, 0, 1, 0); /* pretend, delay, safe */
1355   FRAME_PIXEL_WIDTH (f) = pixelwidth;
1356   FRAME_PIXEL_HEIGHT (f) = pixelheight;
1357 /*  SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */
1359   mark_window_cursors_off (XWINDOW (f->root_window));
1360   cancel_mouse_face (f);
1362   unblock_input ();
1366 static void
1367 ns_fullscreen_hook (FRAME_PTR f)
1369   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1371   if (!FRAME_VISIBLE_P (f))
1372     return;
1374    if (! [view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH)
1375     {
1376       /* Old style fs don't initiate correctly if created from
1377          init/default-frame alist, so use a timer (not nice...).
1378       */
1379       [NSTimer scheduledTimerWithTimeInterval: 0.5 target: view
1380                                      selector: @selector (handleFS)
1381                                      userInfo: nil repeats: NO];
1382       return;
1383     }
1385   block_input ();
1386   [view handleFS];
1387   unblock_input ();
1390 /* ==========================================================================
1392     Color management
1394    ========================================================================== */
1397 NSColor *
1398 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1400   struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1401   if (idx < 1 || idx >= color_table->avail)
1402     return nil;
1403   return color_table->colors[idx];
1407 unsigned long
1408 ns_index_color (NSColor *color, struct frame *f)
1410   struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1411   ptrdiff_t idx;
1412   ptrdiff_t i;
1414   if (!color_table->colors)
1415     {
1416       color_table->size = NS_COLOR_CAPACITY;
1417       color_table->avail = 1; /* skip idx=0 as marker */
1418       color_table->colors = xmalloc (color_table->size * sizeof (NSColor *));
1419       color_table->colors[0] = nil;
1420       color_table->empty_indices = [[NSMutableSet alloc] init];
1421     }
1423   /* do we already have this color ? */
1424   for (i = 1; i < color_table->avail; i++)
1425     if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1426       return i;
1428   if ([color_table->empty_indices count] > 0)
1429     {
1430       NSNumber *index = [color_table->empty_indices anyObject];
1431       [color_table->empty_indices removeObject: index];
1432       idx = [index unsignedLongValue];
1433     }
1434   else
1435     {
1436       if (color_table->avail == color_table->size)
1437         color_table->colors =
1438           xpalloc (color_table->colors, &color_table->size, 1,
1439                    min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1440       idx = color_table->avail++;
1441     }
1443   color_table->colors[idx] = color;
1444   [color retain];
1445 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1446   return idx;
1450 void
1451 ns_free_indexed_color (unsigned long idx, struct frame *f)
1453   struct ns_color_table *color_table;
1454   NSColor *color;
1455   NSNumber *index;
1457   if (!f)
1458     return;
1460   color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1462   if (idx <= 0 || idx >= color_table->size) {
1463     message1 ("ns_free_indexed_color: Color index out of range.\n");
1464     return;
1465   }
1467   index = [NSNumber numberWithUnsignedInt: idx];
1468   if ([color_table->empty_indices containsObject: index]) {
1469     message1 ("ns_free_indexed_color: attempt to free already freed color.\n");
1470     return;
1471   }
1473   color = color_table->colors[idx];
1474   [color release];
1475   color_table->colors[idx] = nil;
1476   [color_table->empty_indices addObject: index];
1477 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1481 static int
1482 ns_get_color (const char *name, NSColor **col)
1483 /* --------------------------------------------------------------------------
1484      Parse a color name
1485    -------------------------------------------------------------------------- */
1486 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1487    X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1488    See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1490   NSColor *new = nil;
1491   static char hex[20];
1492   int scaling;
1493   float r = -1.0, g, b;
1494   NSString *nsname = [NSString stringWithUTF8String: name];
1496 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1497   block_input ();
1499   if ([nsname isEqualToString: @"ns_selection_color"])
1500     {
1501       nsname = ns_selection_color;
1502       name = [ns_selection_color UTF8String];
1503     }
1505   /* First, check for some sort of numeric specification. */
1506   hex[0] = '\0';
1508   if (name[0] == '0' || name[0] == '1' || name[0] == '.')  /* RGB decimal */
1509     {
1510       NSScanner *scanner = [NSScanner scannerWithString: nsname];
1511       [scanner scanFloat: &r];
1512       [scanner scanFloat: &g];
1513       [scanner scanFloat: &b];
1514     }
1515   else if (!strncmp(name, "rgb:", 4))  /* A newer X11 format -- rgb:r/g/b */
1516     scaling = (snprintf (hex, sizeof hex, "%s", name + 4) - 2) / 3;
1517   else if (name[0] == '#')        /* An old X11 format; convert to newer */
1518     {
1519       int len = (strlen(name) - 1);
1520       int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1521       int i;
1522       scaling = strlen(name+start) / 3;
1523       for (i = 0; i < 3; i++)
1524         sprintf (hex + i * (scaling + 1), "%.*s/", scaling,
1525                  name + start + i * scaling);
1526       hex[3 * (scaling + 1) - 1] = '\0';
1527     }
1529   if (hex[0])
1530     {
1531       int rr, gg, bb;
1532       float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1533       if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1534         {
1535           r = rr / fscale;
1536           g = gg / fscale;
1537           b = bb / fscale;
1538         }
1539     }
1541   if (r >= 0.0)
1542     {
1543       *col = [NSColor colorWithCalibratedRed: r green: g blue: b alpha: 1.0];
1544       unblock_input ();
1545       return 0;
1546     }
1548   /* Otherwise, color is expected to be from a list */
1549   {
1550     NSEnumerator *lenum, *cenum;
1551     NSString *name;
1552     NSColorList *clist;
1554 #ifdef NS_IMPL_GNUSTEP
1555     /* XXX: who is wrong, the requestor or the implementation? */
1556     if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1557         == NSOrderedSame)
1558       nsname = @"highlightColor";
1559 #endif
1561     lenum = [[NSColorList availableColorLists] objectEnumerator];
1562     while ( (clist = [lenum nextObject]) && new == nil)
1563       {
1564         cenum = [[clist allKeys] objectEnumerator];
1565         while ( (name = [cenum nextObject]) && new == nil )
1566           {
1567             if ([name compare: nsname
1568                       options: NSCaseInsensitiveSearch] == NSOrderedSame )
1569               new = [clist colorWithKey: name];
1570           }
1571       }
1572   }
1574   if (new)
1575     *col = [new colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1576   unblock_input ();
1577   return new ? 0 : 1;
1582 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1583 /* --------------------------------------------------------------------------
1584      Convert a Lisp string object to a NS color
1585    -------------------------------------------------------------------------- */
1587   NSTRACE (ns_lisp_to_color);
1588   if (STRINGP (color))
1589     return ns_get_color (SSDATA (color), col);
1590   else if (SYMBOLP (color))
1591     return ns_get_color (SSDATA (SYMBOL_NAME (color)), col);
1592   return 1;
1596 Lisp_Object
1597 ns_color_to_lisp (NSColor *col)
1598 /* --------------------------------------------------------------------------
1599      Convert a color to a lisp string with the RGB equivalent
1600    -------------------------------------------------------------------------- */
1602   CGFloat red, green, blue, alpha, gray;
1603   char buf[1024];
1604   const char *str;
1605   NSTRACE (ns_color_to_lisp);
1607   block_input ();
1608   if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1610       if ((str =[[col colorNameComponent] UTF8String]))
1611         {
1612           unblock_input ();
1613           return build_string ((char *)str);
1614         }
1616     [[col colorUsingColorSpaceName: NSCalibratedRGBColorSpace]
1617         getRed: &red green: &green blue: &blue alpha: &alpha];
1618   if (red ==green && red ==blue)
1619     {
1620       [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1621             getWhite: &gray alpha: &alpha];
1622       snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1623                 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1624       unblock_input ();
1625       return build_string (buf);
1626     }
1628   snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1629             lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1631   unblock_input ();
1632   return build_string (buf);
1636 void
1637 ns_query_color(void *col, XColor *color_def, int setPixel)
1638 /* --------------------------------------------------------------------------
1639          Get ARGB values out of NSColor col and put them into color_def.
1640          If setPixel, set the pixel to a concatenated version.
1641          and set color_def pixel to the resulting index.
1642    -------------------------------------------------------------------------- */
1644   CGFloat r, g, b, a;
1646   [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1647   color_def->red   = r * 65535;
1648   color_def->green = g * 65535;
1649   color_def->blue  = b * 65535;
1651   if (setPixel == YES)
1652     color_def->pixel
1653       = ARGB_TO_ULONG((int)(a*255),
1654                       (int)(r*255), (int)(g*255), (int)(b*255));
1658 bool
1659 ns_defined_color (struct frame *f,
1660                   const char *name,
1661                   XColor *color_def,
1662                   bool alloc,
1663                   bool makeIndex)
1664 /* --------------------------------------------------------------------------
1665          Return true if named color found, and set color_def rgb accordingly.
1666          If makeIndex and alloc are nonzero put the color in the color_table,
1667          and set color_def pixel to the resulting index.
1668          If makeIndex is zero, set color_def pixel to ARGB.
1669          Return false if not found
1670    -------------------------------------------------------------------------- */
1672   NSColor *col;
1673   NSTRACE (ns_defined_color);
1675   block_input ();
1676   if (ns_get_color (name, &col) != 0) /* Color not found  */
1677     {
1678       unblock_input ();
1679       return 0;
1680     }
1681   if (makeIndex && alloc)
1682     color_def->pixel = ns_index_color (col, f);
1683   ns_query_color (col, color_def, !makeIndex);
1684   unblock_input ();
1685   return 1;
1689 unsigned long
1690 ns_get_rgb_color (struct frame *f, float r, float g, float b, float a)
1691 /* --------------------------------------------------------------------------
1692     return an autoreleased RGB color
1693    -------------------------------------------------------------------------- */
1695 /*static int c = 1; fprintf (stderr, "color request %d\n", c++); */
1696   if (r < 0.0) r = 0.0;
1697   else if (r > 1.0) r = 1.0;
1698   if (g < 0.0) g = 0.0;
1699   else if (g > 1.0) g = 1.0;
1700   if (b < 0.0) b = 0.0;
1701   else if (b > 1.0) b = 1.0;
1702   if (a < 0.0) a = 0.0;
1703   else if (a > 1.0) a = 1.0;
1704   return (unsigned long) ns_index_color(
1705     [NSColor colorWithCalibratedRed: r green: g blue: b alpha: a], f);
1709 void
1710 x_set_frame_alpha (struct frame *f)
1711 /* --------------------------------------------------------------------------
1712      change the entire-frame transparency
1713    -------------------------------------------------------------------------- */
1715   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1716   EmacsView *view = FRAME_NS_VIEW (f);
1717   double alpha = 1.0;
1718   double alpha_min = 1.0;
1720   if (dpyinfo->x_highlight_frame == f)
1721     alpha = f->alpha[0];
1722   else
1723     alpha = f->alpha[1];
1725   if (FLOATP (Vframe_alpha_lower_limit))
1726     alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1727   else if (INTEGERP (Vframe_alpha_lower_limit))
1728     alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1730   if (alpha < 0.0)
1731     return;
1732   else if (1.0 < alpha)
1733     alpha = 1.0;
1734   else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1735     alpha = alpha_min;
1737 #ifdef NS_IMPL_COCOA
1738   [[view window] setAlphaValue: alpha];
1739 #endif
1743 /* ==========================================================================
1745     Mouse handling
1747    ========================================================================== */
1750 void
1751 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1752 /* --------------------------------------------------------------------------
1753      Programmatically reposition mouse pointer in pixel coordinates
1754    -------------------------------------------------------------------------- */
1756   NSTRACE (x_set_mouse_pixel_position);
1757   ns_raise_frame (f);
1758 #if 0
1759   /* FIXME: this does not work, and what about GNUstep? */
1760 #ifdef NS_IMPL_COCOA
1761   [FRAME_NS_VIEW (f) lockFocus];
1762   PSsetmouse ((float)pix_x, (float)pix_y);
1763   [FRAME_NS_VIEW (f) unlockFocus];
1764 #endif
1765 #endif
1769 void
1770 x_set_mouse_position (struct frame *f, int h, int v)
1771 /* --------------------------------------------------------------------------
1772      Programmatically reposition mouse pointer in character coordinates
1773    -------------------------------------------------------------------------- */
1775   int pix_x, pix_y;
1777   pix_x = FRAME_COL_TO_PIXEL_X (f, h) + FRAME_COLUMN_WIDTH (f) / 2;
1778   pix_y = FRAME_LINE_TO_PIXEL_Y (f, v) + FRAME_LINE_HEIGHT (f) / 2;
1780   if (pix_x < 0) pix_x = 0;
1781   if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
1783   if (pix_y < 0) pix_y = 0;
1784   if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
1786   x_set_mouse_pixel_position (f, pix_x, pix_y);
1790 static int
1791 note_mouse_movement (struct frame *frame, float x, float y)
1792 /*   ------------------------------------------------------------------------
1793      Called by EmacsView on mouseMovement events.  Passes on
1794      to emacs mainstream code if we moved off of a rect of interest
1795      known as last_mouse_glyph.
1796      ------------------------------------------------------------------------ */
1798 //  NSTRACE (note_mouse_movement);
1800   XSETFRAME (last_mouse_motion_frame, frame);
1802   /* Note, this doesn't get called for enter/leave, since we don't have a
1803      position.  Those are taken care of in the corresponding NSView methods. */
1805   /* has movement gone beyond last rect we were tracking? */
1806   if (x < last_mouse_glyph.origin.x ||
1807       x >= (last_mouse_glyph.origin.x + last_mouse_glyph.size.width) ||
1808       y < last_mouse_glyph.origin.y ||
1809       y >= (last_mouse_glyph.origin.y + last_mouse_glyph.size.height))
1810     {
1811       ns_update_begin(frame);
1812       frame->mouse_moved = 1;
1813       note_mouse_highlight (frame, x, y);
1814       remember_mouse_glyph (frame, x, y, &last_mouse_glyph);
1815       ns_update_end(frame);
1816       return 1;
1817     }
1819   return 0;
1823 static void
1824 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1825                    enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1826                    Time *time)
1827 /* --------------------------------------------------------------------------
1828     External (hook): inform emacs about mouse position and hit parts.
1829     If a scrollbar is being dragged, set bar_window, part, x, y, time.
1830     x & y should be position in the scrollbar (the whole bar, not the handle)
1831     and length of scrollbar respectively
1832    -------------------------------------------------------------------------- */
1834   id view;
1835   NSPoint position;
1836   Lisp_Object frame, tail;
1837   struct frame *f;
1838   struct ns_display_info *dpyinfo;
1840   NSTRACE (ns_mouse_position);
1842   if (*fp == NULL)
1843     {
1844       fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1845       return;
1846     }
1848   dpyinfo = FRAME_NS_DISPLAY_INFO (*fp);
1850   block_input ();
1852   if (last_mouse_scroll_bar != nil && insist == 0)
1853     {
1854       /* TODO: we do not use this path at the moment because drag events will
1855            go directly to the EmacsScroller.  Leaving code in for now. */
1856       [last_mouse_scroll_bar getMouseMotionPart: (int *)part window: bar_window
1857                                               x: x y: y];
1858       if (time) *time = last_mouse_movement_time;
1859       last_mouse_scroll_bar = nil;
1860     }
1861   else
1862     {
1863       /* Clear the mouse-moved flag for every frame on this display.  */
1864       FOR_EACH_FRAME (tail, frame)
1865         if (FRAME_NS_P (XFRAME (frame))
1866             && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1867           XFRAME (frame)->mouse_moved = 0;
1869       last_mouse_scroll_bar = nil;
1870       if (last_mouse_frame && FRAME_LIVE_P (last_mouse_frame))
1871         f = last_mouse_frame;
1872       else
1873         f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame
1874                                     : SELECTED_FRAME ();
1876       if (f && f->output_data.ns)  /* TODO: 2nd check no longer needed? */
1877         {
1878           view = FRAME_NS_VIEW (*fp);
1880           position = [[view window] mouseLocationOutsideOfEventStream];
1881           position = [view convertPoint: position fromView: nil];
1882           remember_mouse_glyph (f, position.x, position.y, &last_mouse_glyph);
1883 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1885           if (bar_window) *bar_window = Qnil;
1886           if (part) *part = 0; /*scroll_bar_handle; */
1888           if (x) XSETINT (*x, lrint (position.x));
1889           if (y) XSETINT (*y, lrint (position.y));
1890           if (time) *time = last_mouse_movement_time;
1891           *fp = f;
1892         }
1893     }
1895   unblock_input ();
1899 static void
1900 ns_frame_up_to_date (struct frame *f)
1901 /* --------------------------------------------------------------------------
1902     External (hook): Fix up mouse highlighting right after a full update.
1903     Can't use FRAME_MOUSE_UPDATE due to ns_frame_begin and ns_frame_end calls.
1904    -------------------------------------------------------------------------- */
1906   NSTRACE (ns_frame_up_to_date);
1908   if (FRAME_NS_P (f))
1909     {
1910       Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1911       if (f == hlinfo->mouse_face_mouse_frame)
1912         {
1913           block_input ();
1914           ns_update_begin(f);
1915           if (hlinfo->mouse_face_mouse_frame)
1916             note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
1917                                   hlinfo->mouse_face_mouse_x,
1918                                   hlinfo->mouse_face_mouse_y);
1919           ns_update_end(f);
1920           unblock_input ();
1921         }
1922     }
1926 static void
1927 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1928 /* --------------------------------------------------------------------------
1929     External (RIF): set frame mouse pointer type.
1930    -------------------------------------------------------------------------- */
1932   NSTRACE (ns_define_frame_cursor);
1933   if (FRAME_POINTER_TYPE (f) != cursor)
1934     {
1935       EmacsView *view = FRAME_NS_VIEW (f);
1936       FRAME_POINTER_TYPE (f) = cursor;
1937       [[view window] invalidateCursorRectsForView: view];
1938       /* Redisplay assumes this function also draws the changed frame
1939          cursor, but this function doesn't, so do it explicitly.  */
1940       x_update_cursor (f, 1);
1941     }
1946 /* ==========================================================================
1948     Keyboard handling
1950    ========================================================================== */
1953 static unsigned
1954 ns_convert_key (unsigned code)
1955 /* --------------------------------------------------------------------------
1956     Internal call used by NSView-keyDown.
1957    -------------------------------------------------------------------------- */
1959   const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym)
1960                                 / sizeof (convert_ns_to_X_keysym[0]));
1961   unsigned keysym;
1962   /* An array would be faster, but less easy to read. */
1963   for (keysym = 0; keysym < last_keysym; keysym += 2)
1964     if (code == convert_ns_to_X_keysym[keysym])
1965       return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
1966   return 0;
1967 /* if decide to use keyCode and Carbon table, use this line:
1968      return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
1972 char *
1973 x_get_keysym_name (int keysym)
1974 /* --------------------------------------------------------------------------
1975     Called by keyboard.c.  Not sure if the return val is important, except
1976     that it be unique.
1977    -------------------------------------------------------------------------- */
1979   static char value[16];
1980   NSTRACE (x_get_keysym_name);
1981   sprintf (value, "%d", keysym);
1982   return value;
1987 /* ==========================================================================
1989     Block drawing operations
1991    ========================================================================== */
1994 static void
1995 ns_redraw_scroll_bars (struct frame *f)
1997   int i;
1998   id view;
1999   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
2000   NSTRACE (ns_redraw_scroll_bars);
2001   for (i =[subviews count]-1; i >= 0; i--)
2002     {
2003       view = [subviews objectAtIndex: i];
2004       if (![view isKindOfClass: [EmacsScroller class]]) continue;
2005       [view display];
2006     }
2010 void
2011 ns_clear_frame (struct frame *f)
2012 /* --------------------------------------------------------------------------
2013       External (hook): Erase the entire frame
2014    -------------------------------------------------------------------------- */
2016   NSView *view = FRAME_NS_VIEW (f);
2017   NSRect r;
2019   NSTRACE (ns_clear_frame);
2021  /* comes on initial frame because we have
2022     after-make-frame-functions = select-frame */
2023  if (!FRAME_DEFAULT_FACE (f))
2024    return;
2026   mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2028   output_cursor.hpos = output_cursor.vpos = 0;
2029   output_cursor.x = -1;
2031   r = [view bounds];
2033   block_input ();
2034   ns_focus (f, &r, 1);
2035   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
2036   NSRectFill (r);
2037   ns_unfocus (f);
2039   /* as of 2006/11 or so this is now needed */
2040   ns_redraw_scroll_bars (f);
2041   unblock_input ();
2045 static void
2046 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2047 /* --------------------------------------------------------------------------
2048     External (RIF):  Clear section of frame
2049    -------------------------------------------------------------------------- */
2051   NSRect r = NSMakeRect (x, y, width, height);
2052   NSView *view = FRAME_NS_VIEW (f);
2053   struct face *face = FRAME_DEFAULT_FACE (f);
2055   if (!view || !face)
2056     return;
2058   NSTRACE (ns_clear_frame_area);
2060   r = NSIntersectionRect (r, [view frame]);
2061   ns_focus (f, &r, 1);
2062   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2064   NSRectFill (r);
2066   ns_unfocus (f);
2067   return;
2071 static void
2072 ns_scroll_run (struct window *w, struct run *run)
2073 /* --------------------------------------------------------------------------
2074     External (RIF):  Insert or delete n lines at line vpos
2075    -------------------------------------------------------------------------- */
2077   struct frame *f = XFRAME (w->frame);
2078   int x, y, width, height, from_y, to_y, bottom_y;
2080   NSTRACE (ns_scroll_run);
2082   /* begin copy from other terms */
2083   /* Get frame-relative bounding box of the text display area of W,
2084      without mode lines.  Include in this box the left and right
2085      fringe of W.  */
2086   window_box (w, -1, &x, &y, &width, &height);
2088   from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2089   to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2090   bottom_y = y + height;
2092   if (to_y < from_y)
2093     {
2094       /* Scrolling up.  Make sure we don't copy part of the mode
2095          line at the bottom.  */
2096       if (from_y + run->height > bottom_y)
2097         height = bottom_y - from_y;
2098       else
2099         height = run->height;
2100     }
2101   else
2102     {
2103       /* Scrolling down.  Make sure we don't copy over the mode line.
2104          at the bottom.  */
2105       if (to_y + run->height > bottom_y)
2106         height = bottom_y - to_y;
2107       else
2108         height = run->height;
2109     }
2110   /* end copy from other terms */
2112   if (height == 0)
2113       return;
2115   block_input ();
2117   updated_window = w;
2118   x_clear_cursor (w);
2120   {
2121     NSRect srcRect = NSMakeRect (x, from_y, width, height);
2122     NSRect dstRect = NSMakeRect (x, to_y, width, height);
2123     NSPoint dstOrigin = NSMakePoint (x, to_y);
2125     ns_focus (f, &dstRect, 1);
2126     NSCopyBits (0, srcRect , dstOrigin);
2127     ns_unfocus (f);
2128   }
2130   unblock_input ();
2134 static void
2135 ns_after_update_window_line (struct glyph_row *desired_row)
2136 /* --------------------------------------------------------------------------
2137     External (RIF): preparatory to fringe update after text was updated
2138    -------------------------------------------------------------------------- */
2140   struct window *w = updated_window;
2141   struct frame *f;
2142   int width, height;
2144   NSTRACE (ns_after_update_window_line);
2146   /* begin copy from other terms */
2147   eassert (w);
2149   if (!desired_row->mode_line_p && !w->pseudo_window_p)
2150     desired_row->redraw_fringe_bitmaps_p = 1;
2152   /* When a window has disappeared, make sure that no rest of
2153      full-width rows stays visible in the internal border.  */
2154   if (windows_or_buffers_changed
2155       && desired_row->full_width_p
2156       && (f = XFRAME (w->frame),
2157           width = FRAME_INTERNAL_BORDER_WIDTH (f),
2158           width != 0)
2159       && (height = desired_row->visible_height,
2160           height > 0))
2161     {
2162       int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2164       block_input ();
2165       ns_clear_frame_area (f, 0, y, width, height);
2166       ns_clear_frame_area (f,
2167                            FRAME_PIXEL_WIDTH (f) - width,
2168                            y, width, height);
2169       unblock_input ();
2170     }
2174 static void
2175 ns_shift_glyphs_for_insert (struct frame *f,
2176                            int x, int y, int width, int height,
2177                            int shift_by)
2178 /* --------------------------------------------------------------------------
2179     External (RIF): copy an area horizontally, don't worry about clearing src
2180    -------------------------------------------------------------------------- */
2182   NSRect srcRect = NSMakeRect (x, y, width, height);
2183   NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2184   NSPoint dstOrigin = dstRect.origin;
2186   NSTRACE (ns_shift_glyphs_for_insert);
2188   ns_focus (f, &dstRect, 1);
2189   NSCopyBits (0, srcRect, dstOrigin);
2190   ns_unfocus (f);
2195 /* ==========================================================================
2197     Character encoding and metrics
2199    ========================================================================== */
2202 static void
2203 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2204 /* --------------------------------------------------------------------------
2205      External (RIF); compute left/right overhang of whole string and set in s
2206    -------------------------------------------------------------------------- */
2208   struct font *font = s->font;
2210   if (s->char2b)
2211     {
2212       struct font_metrics metrics;
2213       unsigned int codes[2];
2214       codes[0] = *(s->char2b);
2215       codes[1] = *(s->char2b + s->nchars - 1);
2217       font->driver->text_extents (font, codes, 2, &metrics);
2218       s->left_overhang = -metrics.lbearing;
2219       s->right_overhang
2220         = metrics.rbearing > metrics.width
2221         ? metrics.rbearing - metrics.width : 0;
2222     }
2223   else
2224     {
2225       s->left_overhang = 0;
2226       s->right_overhang = ((struct nsfont_info *)font)->ital ?
2227         FONT_HEIGHT (font) * 0.2 : 0;
2228     }
2233 /* ==========================================================================
2235     Fringe and cursor drawing
2237    ========================================================================== */
2240 extern int max_used_fringe_bitmap;
2241 static void
2242 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2243                       struct draw_fringe_bitmap_params *p)
2244 /* --------------------------------------------------------------------------
2245     External (RIF); fringe-related
2246    -------------------------------------------------------------------------- */
2248   struct frame *f = XFRAME (WINDOW_FRAME (w));
2249   struct face *face = p->face;
2250   int rowY;
2251   static EmacsImage **bimgs = NULL;
2252   static int nBimgs = 0;
2254   /* grow bimgs if needed */
2255   if (nBimgs < max_used_fringe_bitmap)
2256     {
2257       bimgs = xrealloc (bimgs, max_used_fringe_bitmap * sizeof *bimgs);
2258       memset (bimgs + nBimgs, 0,
2259               (max_used_fringe_bitmap - nBimgs) * sizeof *bimgs);
2260       nBimgs = max_used_fringe_bitmap;
2261     }
2263   /* Must clip because of partially visible lines.  */
2264   rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
2265   ns_clip_to_row (w, row, -1, YES);
2267   if (!p->overlay_p)
2268     {
2269       int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
2271       /* If the fringe is adjacent to the left (right) scroll bar of a
2272          leftmost (rightmost, respectively) window, then extend its
2273          background to the gap between the fringe and the bar.  */
2274       if ((WINDOW_LEFTMOST_P (w)
2275            && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
2276           || (WINDOW_RIGHTMOST_P (w)
2277               && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w)))
2278         {
2279           int sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
2281           if (sb_width > 0)
2282             {
2283               int bar_area_x = WINDOW_SCROLL_BAR_AREA_X (w);
2284               int bar_area_width = (WINDOW_CONFIG_SCROLL_BAR_COLS (w)
2285                                     * FRAME_COLUMN_WIDTH (f));
2287               if (bx < 0)
2288                 {
2289                   /* Bitmap fills the fringe.  */
2290                   if (bar_area_x + bar_area_width == p->x)
2291                     bx = bar_area_x + sb_width;
2292                   else if (p->x + p->wd == bar_area_x)
2293                     bx = bar_area_x;
2294                   if (bx >= 0)
2295                     {
2296                       int header_line_height = WINDOW_HEADER_LINE_HEIGHT (w);
2298                       nx = bar_area_width - sb_width;
2299                       by = WINDOW_TO_FRAME_PIXEL_Y (w, max (header_line_height,
2300                                                             row->y));
2301                       ny = row->visible_height;
2302                     }
2303                 }
2304               else
2305                 {
2306                   if (bar_area_x + bar_area_width == bx)
2307                     {
2308                       bx = bar_area_x + sb_width;
2309                       nx += bar_area_width - sb_width;
2310                     }
2311                   else if (bx + nx == bar_area_x)
2312                     nx += bar_area_width - sb_width;
2313                 }
2314             }
2315         }
2317       if (bx >= 0 && nx > 0)
2318         {
2319           NSRect r = NSMakeRect (bx, by, nx, ny);
2320           NSRectClip (r);
2321           [ns_lookup_indexed_color (face->background, f) set];
2322           NSRectFill (r);
2323         }
2324     }
2326   if (p->which)
2327     {
2328       NSRect r = NSMakeRect (p->x, p->y, p->wd, p->h);
2329       EmacsImage *img = bimgs[p->which - 1];
2331       if (!img)
2332         {
2333           unsigned short *bits = p->bits + p->dh;
2334           int len = p->h;
2335           int i;
2336           unsigned char *cbits = xmalloc (len);
2338           for (i = 0; i < len; i++)
2339             cbits[i] = ~(bits[i] & 0xff);
2340           img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2341                                            flip: NO];
2342           bimgs[p->which - 1] = img;
2343           xfree (cbits);
2344         }
2346       NSRectClip (r);
2347       /* Since we composite the bitmap instead of just blitting it, we need
2348          to erase the whole background. */
2349       [ns_lookup_indexed_color(face->background, f) set];
2350       NSRectFill (r);
2351       [img setXBMColor: ns_lookup_indexed_color(face->foreground, f)];
2352 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
2353       [img drawInRect: r
2354               fromRect: NSZeroRect
2355              operation: NSCompositeSourceOver
2356               fraction: 1.0
2357            respectFlipped: YES
2358                 hints: nil];
2359 #else
2360       {
2361         NSPoint pt = r.origin;
2362         pt.y += p->h;
2363         [img compositeToPoint: pt operation: NSCompositeSourceOver];
2364       }
2365 #endif
2366     }
2367   ns_unfocus (f);
2371 static void
2372 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2373                        int x, int y, int cursor_type, int cursor_width,
2374                        int on_p, int active_p)
2375 /* --------------------------------------------------------------------------
2376      External call (RIF): draw cursor.
2377      Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2378    -------------------------------------------------------------------------- */
2380   NSRect r, s;
2381   int fx, fy, h, cursor_height;
2382   struct frame *f = WINDOW_XFRAME (w);
2383   struct glyph *phys_cursor_glyph;
2384   int overspill;
2385   struct glyph *cursor_glyph;
2386   struct face *face;
2387   NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2389   /* If cursor is out of bounds, don't draw garbage.  This can happen
2390      in mini-buffer windows when switching between echo area glyphs
2391      and mini-buffer.  */
2393   NSTRACE (dumpcursor);
2395   if (!on_p)
2396     return;
2398   w->phys_cursor_type = cursor_type;
2399   w->phys_cursor_on_p = on_p;
2401   if (cursor_type == NO_CURSOR)
2402     {
2403       w->phys_cursor_width = 0;
2404       return;
2405     }
2407   if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2408     {
2409       if (glyph_row->exact_window_width_line_p
2410           && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2411         {
2412           glyph_row->cursor_in_fringe_p = 1;
2413           draw_fringe_bitmap (w, glyph_row, 0);
2414         }
2415       return;
2416     }
2418   /* We draw the cursor (with NSRectFill), then draw the glyph on top
2419      (other terminals do it the other way round).  We must set
2420      w->phys_cursor_width to the cursor width.  For bar cursors, that
2421      is CURSOR_WIDTH; for box cursors, it is the glyph width.  */
2422   get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2424   /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2425      to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2426   if (cursor_type == BAR_CURSOR)
2427     {
2428       if (cursor_width < 1)
2429         cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2430       w->phys_cursor_width = cursor_width;
2431     }
2432   /* If we have an HBAR, "cursor_width" MAY specify height. */
2433   else if (cursor_type == HBAR_CURSOR)
2434     {
2435       cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2436       fy += h - cursor_height;
2437       h = cursor_height;
2438     }
2440   r.origin.x = fx, r.origin.y = fy;
2441   r.size.height = h;
2442   r.size.width = w->phys_cursor_width;
2444   /* TODO: only needed in rare cases with last-resort font in HELLO..
2445      should we do this more efficiently? */
2446   ns_clip_to_row (w, glyph_row, -1, NO); /* do ns_focus(f, &r, 1); if remove */
2449   face = FACE_FROM_ID (f, phys_cursor_glyph->face_id);
2450   if (face && NS_FACE_BACKGROUND (face)
2451       == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2452     {
2453       [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2454       hollow_color = FRAME_CURSOR_COLOR (f);
2455     }
2456   else
2457     [FRAME_CURSOR_COLOR (f) set];
2459 #ifdef NS_IMPL_COCOA
2460   /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2461            atomic.  Cleaner ways of doing this should be investigated.
2462            One way would be to set a global variable DRAWING_CURSOR
2463            when making the call to draw_phys..(), don't focus in that
2464            case, then move the ns_unfocus() here after that call. */
2465   NSDisableScreenUpdates ();
2466 #endif
2468   switch (cursor_type)
2469     {
2470     case NO_CURSOR:
2471       break;
2472     case FILLED_BOX_CURSOR:
2473       NSRectFill (r);
2474       break;
2475     case HOLLOW_BOX_CURSOR:
2476       NSRectFill (r);
2477       [hollow_color set];
2478       NSRectFill (NSInsetRect (r, 1, 1));
2479       [FRAME_CURSOR_COLOR (f) set];
2480       break;
2481     case HBAR_CURSOR:
2482       NSRectFill (r);
2483       break;
2484     case BAR_CURSOR:
2485       s = r;
2486       /* If the character under cursor is R2L, draw the bar cursor
2487          on the right of its glyph, rather than on the left.  */
2488       cursor_glyph = get_phys_cursor_glyph (w);
2489       if ((cursor_glyph->resolved_level & 1) != 0)
2490         s.origin.x += cursor_glyph->pixel_width - s.size.width;
2492       NSRectFill (s);
2493       break;
2494     }
2495   ns_unfocus (f);
2497   /* draw the character under the cursor */
2498   if (cursor_type != NO_CURSOR)
2499     draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2501 #ifdef NS_IMPL_COCOA
2502   NSEnableScreenUpdates ();
2503 #endif
2508 static void
2509 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2510 /* --------------------------------------------------------------------------
2511      External (RIF): Draw a vertical line.
2512    -------------------------------------------------------------------------- */
2514   struct frame *f = XFRAME (WINDOW_FRAME (w));
2515   struct face *face;
2516   NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2518   NSTRACE (ns_draw_vertical_window_border);
2520   face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2521   if (face)
2522       [ns_lookup_indexed_color(face->foreground, f) set];
2524   ns_focus (f, &r, 1);
2525   NSRectFill(r);
2526   ns_unfocus (f);
2530 void
2531 show_hourglass (struct atimer *timer)
2533   if (hourglass_shown_p)
2534     return;
2536   block_input ();
2538   /* TODO: add NSProgressIndicator to selected frame (see macfns.c) */
2540   hourglass_shown_p = 1;
2541   unblock_input ();
2545 void
2546 hide_hourglass (void)
2548   if (!hourglass_shown_p)
2549     return;
2551   block_input ();
2553   /* TODO: remove NSProgressIndicator from all frames */
2555   hourglass_shown_p = 0;
2556   unblock_input ();
2561 /* ==========================================================================
2563     Glyph drawing operations
2565    ========================================================================== */
2567 static int
2568 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2569 /* --------------------------------------------------------------------------
2570     Wrapper utility to account for internal border width on full-width lines,
2571     and allow top full-width rows to hit the frame top.  nr should be pointer
2572     to two successive NSRects.  Number of rects actually used is returned.
2573    -------------------------------------------------------------------------- */
2575   int n = get_glyph_string_clip_rects (s, nr, 2);
2576   return n;
2579 /* --------------------------------------------------------------------
2580    Draw a wavy line under glyph string s. The wave fills wave_height
2581    pixels from y.
2583                     x          wave_length = 2
2584                                  --
2585                 y    *   *   *   *   *
2586                      |* * * * * * * * *
2587     wave_height = 3  | *   *   *   *
2588   --------------------------------------------------------------------- */
2590 static void
2591 ns_draw_underwave (struct glyph_string *s, CGFloat width, CGFloat x)
2593   int wave_height = 3, wave_length = 2;
2594   int y, dx, dy, odd, xmax;
2595   NSPoint a, b;
2596   NSRect waveClip;
2598   dx = wave_length;
2599   dy = wave_height - 1;
2600   y =  s->ybase - wave_height + 3;
2601   xmax = x + width;
2603   /* Find and set clipping rectangle */
2604   waveClip = NSMakeRect (x, y, width, wave_height);
2605   [[NSGraphicsContext currentContext] saveGraphicsState];
2606   NSRectClip (waveClip);
2608   /* Draw the waves */
2609   a.x = x - ((int)(x) % dx) + 0.5;
2610   b.x = a.x + dx;
2611   odd = (int)(a.x/dx) % 2;
2612   a.y = b.y = y + 0.5;
2614   if (odd)
2615     a.y += dy;
2616   else
2617     b.y += dy;
2619   while (a.x <= xmax)
2620     {
2621       [NSBezierPath strokeLineFromPoint:a toPoint:b];
2622       a.x = b.x, a.y = b.y;
2623       b.x += dx, b.y = y + 0.5 + odd*dy;
2624       odd = !odd;
2625     }
2627   /* Restore previous clipping rectangle(s) */
2628   [[NSGraphicsContext currentContext] restoreGraphicsState];
2633 void
2634 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
2635                          NSColor *defaultCol, CGFloat width, CGFloat x)
2636 /* --------------------------------------------------------------------------
2637    Draw underline, overline, and strike-through on glyph string s.
2638    -------------------------------------------------------------------------- */
2640   if (s->for_overlaps)
2641     return;
2643   /* Do underline. */
2644   if (face->underline_p)
2645     {
2646       if (s->face->underline_type == FACE_UNDER_WAVE)
2647         {
2648           if (face->underline_defaulted_p)
2649             [defaultCol set];
2650           else
2651             [ns_lookup_indexed_color (face->underline_color, s->f) set];
2653           ns_draw_underwave (s, width, x);
2654         }
2655       else if (s->face->underline_type == FACE_UNDER_LINE)
2656         {
2658           NSRect r;
2659           unsigned long thickness, position;
2661           /* If the prev was underlined, match its appearance. */
2662           if (s->prev && s->prev->face->underline_p
2663               && s->prev->face->underline_type == FACE_UNDER_LINE
2664               && s->prev->underline_thickness > 0)
2665             {
2666               thickness = s->prev->underline_thickness;
2667               position = s->prev->underline_position;
2668             }
2669           else
2670             {
2671               struct font *font;
2672               unsigned long descent;
2674               font=s->font;
2675               descent = s->y + s->height - s->ybase;
2677               /* Use underline thickness of font, defaulting to 1. */
2678               thickness = (font && font->underline_thickness > 0)
2679                 ? font->underline_thickness : 1;
2681               /* Determine the offset of underlining from the baseline. */
2682               if (x_underline_at_descent_line)
2683                 position = descent - thickness;
2684               else if (x_use_underline_position_properties
2685                        && font && font->underline_position >= 0)
2686                 position = font->underline_position;
2687               else if (font)
2688                 position = lround (font->descent / 2);
2689               else
2690                 position = underline_minimum_offset;
2692               position = max (position, underline_minimum_offset);
2694               /* Ensure underlining is not cropped. */
2695               if (descent <= position)
2696                 {
2697                   position = descent - 1;
2698                   thickness = 1;
2699                 }
2700               else if (descent < position + thickness)
2701                 thickness = 1;
2702             }
2704           s->underline_thickness = thickness;
2705           s->underline_position = position;
2707           r = NSMakeRect (x, s->ybase + position, width, thickness);
2709           if (face->underline_defaulted_p)
2710             [defaultCol set];
2711           else
2712             [ns_lookup_indexed_color (face->underline_color, s->f) set];
2713           NSRectFill (r);
2714         }
2715     }
2716   /* Do overline. We follow other terms in using a thickness of 1
2717      and ignoring overline_margin. */
2718   if (face->overline_p)
2719     {
2720       NSRect r;
2721       r = NSMakeRect (x, s->y, width, 1);
2723       if (face->overline_color_defaulted_p)
2724         [defaultCol set];
2725       else
2726         [ns_lookup_indexed_color (face->overline_color, s->f) set];
2727       NSRectFill (r);
2728     }
2730   /* Do strike-through.  We follow other terms for thickness and
2731      vertical position.*/
2732   if (face->strike_through_p)
2733     {
2734       NSRect r;
2735       unsigned long dy;
2737       dy = lrint ((s->height - 1) / 2);
2738       r = NSMakeRect (x, s->y + dy, width, 1);
2740       if (face->strike_through_color_defaulted_p)
2741         [defaultCol set];
2742       else
2743         [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
2744       NSRectFill (r);
2745     }
2748 static void
2749 ns_draw_box (NSRect r, float thickness, NSColor *col, char left_p, char right_p)
2750 /* --------------------------------------------------------------------------
2751     Draw an unfilled rect inside r, optionally leaving left and/or right open.
2752     Note we can't just use an NSDrawRect command, because of the possibility
2753     of some sides not being drawn, and because the rect will be filled.
2754    -------------------------------------------------------------------------- */
2756   NSRect s = r;
2757   [col set];
2759   /* top, bottom */
2760   s.size.height = thickness;
2761   NSRectFill (s);
2762   s.origin.y += r.size.height - thickness;
2763   NSRectFill (s);
2765   s.size.height = r.size.height;
2766   s.origin.y = r.origin.y;
2768   /* left, right (optional) */
2769   s.size.width = thickness;
2770   if (left_p)
2771     NSRectFill (s);
2772   if (right_p)
2773     {
2774       s.origin.x += r.size.width - thickness;
2775       NSRectFill (s);
2776     }
2780 static void
2781 ns_draw_relief (NSRect r, int thickness, char raised_p,
2782                char top_p, char bottom_p, char left_p, char right_p,
2783                struct glyph_string *s)
2784 /* --------------------------------------------------------------------------
2785     Draw a relief rect inside r, optionally leaving some sides open.
2786     Note we can't just use an NSDrawBezel command, because of the possibility
2787     of some sides not being drawn, and because the rect will be filled.
2788    -------------------------------------------------------------------------- */
2790   static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2791   NSColor *newBaseCol = nil;
2792   NSRect sr = r;
2794   NSTRACE (ns_draw_relief);
2796   /* set up colors */
2798   if (s->face->use_box_color_for_shadows_p)
2799     {
2800       newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2801     }
2802 /*     else if (s->first_glyph->type == IMAGE_GLYPH
2803            && s->img->pixmap
2804            && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2805        {
2806          newBaseCol = IMAGE_BACKGROUND  (s->img, s->f, 0);
2807        } */
2808   else
2809     {
2810       newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2811     }
2813   if (newBaseCol == nil)
2814     newBaseCol = [NSColor grayColor];
2816   if (newBaseCol != baseCol)  /* TODO: better check */
2817     {
2818       [baseCol release];
2819       baseCol = [newBaseCol retain];
2820       [lightCol release];
2821       lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2822       [darkCol release];
2823       darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2824     }
2826   [(raised_p ? lightCol : darkCol) set];
2828   /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2830   /* top */
2831   sr.size.height = thickness;
2832   if (top_p) NSRectFill (sr);
2834   /* left */
2835   sr.size.height = r.size.height;
2836   sr.size.width = thickness;
2837   if (left_p) NSRectFill (sr);
2839   [(raised_p ? darkCol : lightCol) set];
2841   /* bottom */
2842   sr.size.width = r.size.width;
2843   sr.size.height = thickness;
2844   sr.origin.y += r.size.height - thickness;
2845   if (bottom_p) NSRectFill (sr);
2847   /* right */
2848   sr.size.height = r.size.height;
2849   sr.origin.y = r.origin.y;
2850   sr.size.width = thickness;
2851   sr.origin.x += r.size.width - thickness;
2852   if (right_p) NSRectFill (sr);
2856 static void
2857 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2858 /* --------------------------------------------------------------------------
2859       Function modeled after x_draw_glyph_string_box ().
2860       Sets up parameters for drawing.
2861    -------------------------------------------------------------------------- */
2863   int right_x, last_x;
2864   char left_p, right_p;
2865   struct glyph *last_glyph;
2866   NSRect r;
2867   int thickness;
2868   struct face *face;
2870   if (s->hl == DRAW_MOUSE_FACE)
2871     {
2872       face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2873       if (!face)
2874         face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2875     }
2876   else
2877     face = s->face;
2879   thickness = face->box_line_width;
2881   NSTRACE (ns_dumpglyphs_box_or_relief);
2883   last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2884             ? WINDOW_RIGHT_EDGE_X (s->w)
2885             : window_box_right (s->w, s->area));
2886   last_glyph = (s->cmp || s->img
2887                 ? s->first_glyph : s->first_glyph + s->nchars-1);
2889   right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2890               ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2892   left_p = (s->first_glyph->left_box_line_p
2893             || (s->hl == DRAW_MOUSE_FACE
2894                 && (s->prev == NULL || s->prev->hl != s->hl)));
2895   right_p = (last_glyph->right_box_line_p
2896              || (s->hl == DRAW_MOUSE_FACE
2897                  && (s->next == NULL || s->next->hl != s->hl)));
2899   r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2901   /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
2902   if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
2903     {
2904       ns_draw_box (r, abs (thickness),
2905                    ns_lookup_indexed_color (face->box_color, s->f),
2906                   left_p, right_p);
2907     }
2908   else
2909     {
2910       ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2911                      1, 1, left_p, right_p, s);
2912     }
2916 static void
2917 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2918 /* --------------------------------------------------------------------------
2919       Modeled after x_draw_glyph_string_background, which draws BG in
2920       certain cases.  Others are left to the text rendering routine.
2921    -------------------------------------------------------------------------- */
2923   NSTRACE (ns_maybe_dumpglyphs_background);
2925   if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2926     {
2927       int box_line_width = max (s->face->box_line_width, 0);
2928       if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2929           || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2930         {
2931           struct face *face;
2932           if (s->hl == DRAW_MOUSE_FACE)
2933             {
2934               face = FACE_FROM_ID (s->f,
2935                                    MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2936               if (!face)
2937                 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2938             }
2939           else
2940             face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2941           if (!face->stipple)
2942             [(NS_FACE_BACKGROUND (face) != 0
2943               ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2944               : FRAME_BACKGROUND_COLOR (s->f)) set];
2945           else
2946             {
2947               struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (s->f);
2948               [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2949             }
2951           if (s->hl != DRAW_CURSOR)
2952             {
2953               NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2954                                     s->background_width,
2955                                     s->height-2*box_line_width);
2956               NSRectFill (r);
2957             }
2959           s->background_filled_p = 1;
2960         }
2961     }
2965 static void
2966 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2967 /* --------------------------------------------------------------------------
2968       Renders an image and associated borders.
2969    -------------------------------------------------------------------------- */
2971   EmacsImage *img = s->img->pixmap;
2972   int box_line_vwidth = max (s->face->box_line_width, 0);
2973   int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2974   int bg_x, bg_y, bg_height;
2975   int th;
2976   char raised_p;
2977   NSRect br;
2978   struct face *face;
2979   NSColor *tdCol;
2981   NSTRACE (ns_dumpglyphs_image);
2983   if (s->face->box != FACE_NO_BOX
2984       && s->first_glyph->left_box_line_p && s->slice.x == 0)
2985     x += abs (s->face->box_line_width);
2987   bg_x = x;
2988   bg_y =  s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2989   bg_height = s->height;
2990   /* other terms have this, but was causing problems w/tabbar mode */
2991   /* - 2 * box_line_vwidth; */
2993   if (s->slice.x == 0) x += s->img->hmargin;
2994   if (s->slice.y == 0) y += s->img->vmargin;
2996   /* Draw BG: if we need larger area than image itself cleared, do that,
2997      otherwise, since we composite the image under NS (instead of mucking
2998      with its background color), we must clear just the image area. */
2999   if (s->hl == DRAW_MOUSE_FACE)
3000     {
3001       face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3002       if (!face)
3003        face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3004     }
3005   else
3006     face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3008   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
3010   if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
3011       || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
3012     {
3013       br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
3014       s->background_filled_p = 1;
3015     }
3016   else
3017     {
3018       br = NSMakeRect (x, y, s->slice.width, s->slice.height);
3019     }
3021   NSRectFill (br);
3023   /* Draw the image.. do we need to draw placeholder if img ==nil? */
3024   if (img != nil)
3025     {
3026 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
3027       NSRect dr = NSMakeRect (x, y, s->slice.width, s->slice.height);
3028       NSRect ir = NSMakeRect (s->slice.x, s->slice.y,
3029                               s->slice.width, s->slice.height);
3030       [img drawInRect: dr
3031              fromRect: ir
3032              operation: NSCompositeSourceOver
3033               fraction: 1.0
3034            respectFlipped: YES
3035                 hints: nil];
3036 #else
3037       [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3038                   operation: NSCompositeSourceOver];
3039 #endif
3040     }
3042   if (s->hl == DRAW_CURSOR)
3043     {
3044     [FRAME_CURSOR_COLOR (s->f) set];
3045     if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3046       tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3047     else
3048       /* Currently on NS img->mask is always 0. Since
3049          get_window_cursor_type specifies a hollow box cursor when on
3050          a non-masked image we never reach this clause. But we put it
3051          in in anticipation of better support for image masks on
3052          NS. */
3053       tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3054     }
3055   else
3056     {
3057       tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3058     }
3060   /* Draw underline, overline, strike-through. */
3061   ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3063   /* Draw relief, if requested */
3064   if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3065     {
3066       if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3067         {
3068           th = tool_bar_button_relief >= 0 ?
3069             tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3070           raised_p = (s->hl == DRAW_IMAGE_RAISED);
3071         }
3072       else
3073         {
3074           th = abs (s->img->relief);
3075           raised_p = (s->img->relief > 0);
3076         }
3078       r.origin.x = x - th;
3079       r.origin.y = y - th;
3080       r.size.width = s->slice.width + 2*th-1;
3081       r.size.height = s->slice.height + 2*th-1;
3082       ns_draw_relief (r, th, raised_p,
3083                       s->slice.y == 0,
3084                       s->slice.y + s->slice.height == s->img->height,
3085                       s->slice.x == 0,
3086                       s->slice.x + s->slice.width == s->img->width, s);
3087     }
3089   /* If there is no mask, the background won't be seen,
3090      so draw a rectangle on the image for the cursor.
3091      Do this for all images, getting transparency right is not reliable.  */
3092   if (s->hl == DRAW_CURSOR)
3093     {
3094       int thickness = abs (s->img->relief);
3095       if (thickness == 0) thickness = 1;
3096       ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3097     }
3101 static void
3102 ns_dumpglyphs_stretch (struct glyph_string *s)
3104   NSRect r[2];
3105   int n, i;
3106   struct face *face;
3107   NSColor *fgCol, *bgCol;
3109   if (!s->background_filled_p)
3110     {
3111       n = ns_get_glyph_string_clip_rect (s, r);
3112       *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3114       ns_focus (s->f, r, n);
3116       if (s->hl == DRAW_MOUSE_FACE)
3117        {
3118          face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3119          if (!face)
3120            face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3121        }
3122       else
3123        face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3125       bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3126       fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3128       for (i = 0; i < n; ++i)
3129         {
3130           if (!s->row->full_width_p)
3131             {
3132               int overrun, leftoverrun;
3134               /* truncate to avoid overwriting fringe and/or scrollbar */
3135               overrun = max (0, (s->x + s->background_width)
3136                              - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3137                                 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3138               r[i].size.width -= overrun;
3140               /* truncate to avoid overwriting to left of the window box */
3141               leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3142                              + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3144               if (leftoverrun > 0)
3145                 {
3146                   r[i].origin.x += leftoverrun;
3147                   r[i].size.width -= leftoverrun;
3148                 }
3150               /* XXX: Try to work between problem where a stretch glyph on
3151                  a partially-visible bottom row will clear part of the
3152                  modeline, and another where list-buffers headers and similar
3153                  rows erroneously have visible_height set to 0.  Not sure
3154                  where this is coming from as other terms seem not to show. */
3155               r[i].size.height = min (s->height, s->row->visible_height);
3156             }
3158           [bgCol set];
3160           /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3161              overwriting cursor (usually when cursor on a tab) */
3162           if (s->hl == DRAW_CURSOR)
3163             {
3164               CGFloat x, width;
3166               x = r[i].origin.x;
3167               width = s->w->phys_cursor_width;
3168               r[i].size.width -= width;
3169               r[i].origin.x += width;
3171               NSRectFill (r[i]);
3173               /* Draw overlining, etc. on the cursor. */
3174               if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3175                 ns_draw_text_decoration (s, face, bgCol, width, x);
3176               else
3177                 ns_draw_text_decoration (s, face, fgCol, width, x);
3178             }
3179           else
3180             {
3181               NSRectFill (r[i]);
3182             }
3184           /* Draw overlining, etc. on the stretch glyph (or the part
3185              of the stretch glyph after the cursor). */
3186           ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3187                                    r[i].origin.x);
3188         }
3189       ns_unfocus (s->f);
3190       s->background_filled_p = 1;
3191     }
3195 static void
3196 ns_draw_glyph_string (struct glyph_string *s)
3197 /* --------------------------------------------------------------------------
3198       External (RIF): Main draw-text call.
3199    -------------------------------------------------------------------------- */
3201   /* TODO (optimize): focus for box and contents draw */
3202   NSRect r[2];
3203   int n;
3204   char box_drawn_p = 0;
3206   NSTRACE (ns_draw_glyph_string);
3208   if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3209     {
3210       int width;
3211       struct glyph_string *next;
3213       for (width = 0, next = s->next;
3214            next && width < s->right_overhang;
3215            width += next->width, next = next->next)
3216         if (next->first_glyph->type != IMAGE_GLYPH)
3217           {
3218             if (next->first_glyph->type != STRETCH_GLYPH)
3219               {
3220                 n = ns_get_glyph_string_clip_rect (s->next, r);
3221                 ns_focus (s->f, r, n);
3222                 ns_maybe_dumpglyphs_background (s->next, 1);
3223                 ns_unfocus (s->f);
3224               }
3225             else
3226               {
3227                 ns_dumpglyphs_stretch (s->next);
3228               }
3229             next->num_clips = 0;
3230           }
3231     }
3233   if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3234         && (s->first_glyph->type == CHAR_GLYPH
3235             || s->first_glyph->type == COMPOSITE_GLYPH))
3236     {
3237       n = ns_get_glyph_string_clip_rect (s, r);
3238       ns_focus (s->f, r, n);
3239       ns_maybe_dumpglyphs_background (s, 1);
3240       ns_dumpglyphs_box_or_relief (s);
3241       ns_unfocus (s->f);
3242       box_drawn_p = 1;
3243     }
3245   switch (s->first_glyph->type)
3246     {
3248     case IMAGE_GLYPH:
3249       n = ns_get_glyph_string_clip_rect (s, r);
3250       ns_focus (s->f, r, n);
3251       ns_dumpglyphs_image (s, r[0]);
3252       ns_unfocus (s->f);
3253       break;
3255     case STRETCH_GLYPH:
3256       ns_dumpglyphs_stretch (s);
3257       break;
3259     case CHAR_GLYPH:
3260     case COMPOSITE_GLYPH:
3261       n = ns_get_glyph_string_clip_rect (s, r);
3262       ns_focus (s->f, r, n);
3264       if (s->for_overlaps || (s->cmp_from > 0
3265                               && ! s->first_glyph->u.cmp.automatic))
3266         s->background_filled_p = 1;
3267       else
3268         ns_maybe_dumpglyphs_background
3269           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3271       ns_tmp_flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3272                     (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3273                      (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3274                       NS_DUMPGLYPH_NORMAL));
3275       ns_tmp_font = (struct nsfont_info *)s->face->font;
3276       if (ns_tmp_font == NULL)
3277           ns_tmp_font = (struct nsfont_info *)FRAME_FONT (s->f);
3279       if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3280         {
3281           unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3282           NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3283           NS_FACE_FOREGROUND (s->face) = tmp;
3284         }
3286       ns_tmp_font->font.driver->draw
3287         (s, 0, s->nchars, s->x, s->y,
3288          (ns_tmp_flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3289          || ns_tmp_flags == NS_DUMPGLYPH_MOUSEFACE);
3291       if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3292         {
3293           unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3294           NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3295           NS_FACE_FOREGROUND (s->face) = tmp;
3296         }
3298       ns_unfocus (s->f);
3299       break;
3301     case GLYPHLESS_GLYPH:
3302       n = ns_get_glyph_string_clip_rect (s, r);
3303       ns_focus (s->f, r, n);
3305       if (s->for_overlaps || (s->cmp_from > 0
3306                               && ! s->first_glyph->u.cmp.automatic))
3307         s->background_filled_p = 1;
3308       else
3309         ns_maybe_dumpglyphs_background
3310           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3311       /* ... */
3312       /* Not yet implemented.  */
3313       /* ... */
3314       ns_unfocus (s->f);
3315       break;
3317     default:
3318       emacs_abort ();
3319     }
3321   /* Draw box if not done already. */
3322   if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3323     {
3324       n = ns_get_glyph_string_clip_rect (s, r);
3325       ns_focus (s->f, r, n);
3326       ns_dumpglyphs_box_or_relief (s);
3327       ns_unfocus (s->f);
3328     }
3330   s->num_clips = 0;
3335 /* ==========================================================================
3337     Event loop
3339    ========================================================================== */
3342 static void
3343 ns_send_appdefined (int value)
3344 /* --------------------------------------------------------------------------
3345     Internal: post an appdefined event which EmacsApp-sendEvent will
3346               recognize and take as a command to halt the event loop.
3347    -------------------------------------------------------------------------- */
3349   /*NSTRACE (ns_send_appdefined); */
3351   /* Only post this event if we haven't already posted one.  This will end
3352        the [NXApp run] main loop after having processed all events queued at
3353        this moment.  */
3354   if (send_appdefined)
3355     {
3356       NSEvent *nxev;
3358       /* We only need one NX_APPDEFINED event to stop NXApp from running.  */
3359       send_appdefined = NO;
3361       /* Don't need wakeup timer any more */
3362       if (timed_entry)
3363         {
3364           [timed_entry invalidate];
3365           [timed_entry release];
3366           timed_entry = nil;
3367         }
3369       nxev = [NSEvent otherEventWithType: NSApplicationDefined
3370                                 location: NSMakePoint (0, 0)
3371                            modifierFlags: 0
3372                                timestamp: 0
3373                             windowNumber: [[NSApp mainWindow] windowNumber]
3374                                  context: [NSApp context]
3375                                  subtype: 0
3376                                    data1: value
3377                                    data2: 0];
3379       /* Post an application defined event on the event queue.  When this is
3380          received the [NXApp run] will return, thus having processed all
3381          events which are currently queued.  */
3382       [NSApp postEvent: nxev atStart: NO];
3383     }
3386 #ifdef HAVE_NATIVE_FS
3387 static void
3388 check_native_fs ()
3390   Lisp_Object frame, tail;
3392   if (ns_last_use_native_fullscreen == ns_use_native_fullscreen)
3393     return;
3395   ns_last_use_native_fullscreen = ns_use_native_fullscreen;
3397   /* Clear the mouse-moved flag for every frame on this display.  */
3398   FOR_EACH_FRAME (tail, frame)
3399     {
3400       struct frame *f = XFRAME (frame);
3401       if (FRAME_NS_P (f))
3402         {
3403           EmacsView *view = FRAME_NS_VIEW (f);
3404           [view updateCollectionBehaviour];
3405         }
3406     }
3408 #endif
3410 const char *
3411 ns_get_pending_menu_title ()
3413   return menu_pending_title;
3416 /* Check if menu open should be cancelled or continued as normal.  */
3417 void
3418 ns_check_menu_open (NSMenu *menu)
3420   /* GNUStep and OSX <= 10.4 does not have cancelTracking.  */
3421 #if defined(NS_IMPL_COCOA) && \
3422   MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
3424   /* Click in menu bar? */
3425   NSArray *a = [[NSApp mainMenu] itemArray];
3426   int i;
3427   BOOL found = NO;
3428   for (i = 0; ! found && i < [a count]; i++)
3429     found = menu == [[a objectAtIndex:i] submenu];
3430   if (found)
3431     {
3432       if (menu_will_open_state == MENU_NONE && emacs_event)
3433         {
3434           NSEvent *theEvent = [NSApp currentEvent];
3435           struct frame *emacsframe = SELECTED_FRAME ();
3437           [menu cancelTracking];
3438           menu_will_open_state = MENU_PENDING;
3439           emacs_event->kind = MENU_BAR_ACTIVATE_EVENT;
3440           EV_TRAILER (theEvent);
3442           CGEventRef ourEvent = CGEventCreate (NULL);
3443           menu_mouse_point = CGEventGetLocation (ourEvent);
3444           CFRelease (ourEvent);
3445           xfree (menu_pending_title);
3446           menu_pending_title = xstrdup ([[menu title] UTF8String]);
3447         }
3448       else if (menu_will_open_state == MENU_OPENING)
3449         {
3450           menu_will_open_state = MENU_NONE;
3451         }
3452     }
3453 #endif
3456 /* Redo saved menu click if state is MENU_PENDING.  */
3457 void
3458 ns_check_pending_open_menu ()
3460 #ifdef NS_IMPL_COCOA
3461   if (menu_will_open_state == MENU_PENDING)
3462     {
3463       CGEventSourceRef source
3464         = CGEventSourceCreate (kCGEventSourceStateHIDSystemState);
3466       CGEventRef event = CGEventCreateMouseEvent (source,
3467                                                   kCGEventLeftMouseDown,
3468                                                   menu_mouse_point,
3469                                                   kCGMouseButtonLeft);
3470       CGEventSetType (event, kCGEventLeftMouseDown);
3471       CGEventPost (kCGHIDEventTap, event);
3472       CFRelease (event);
3473       CFRelease (source);
3475       menu_will_open_state = MENU_OPENING;
3476     }
3477 #endif
3481 static int
3482 ns_read_socket (struct terminal *terminal, struct input_event *hold_quit)
3483 /* --------------------------------------------------------------------------
3484      External (hook): Post an event to ourself and keep reading events until
3485      we read it back again.  In effect process all events which were waiting.
3486      From 21+ we have to manage the event buffer ourselves.
3487    -------------------------------------------------------------------------- */
3489   struct input_event ev;
3490   int nevents;
3492 /* NSTRACE (ns_read_socket); */
3494 #ifdef HAVE_NATIVE_FS
3495   check_native_fs ();
3496 #endif
3498   if ([NSApp modalWindow] != nil)
3499     return -1;
3501   if (hold_event_q.nr > 0)
3502     {
3503       int i;
3504       for (i = 0; i < hold_event_q.nr; ++i)
3505         kbd_buffer_store_event_hold (&hold_event_q.q[i], hold_quit);
3506       hold_event_q.nr = 0;
3507       return i;
3508     }
3510   block_input ();
3511   n_emacs_events_pending = 0;
3512   EVENT_INIT (ev);
3513   emacs_event = &ev;
3514   q_event_ptr = hold_quit;
3516   /* we manage autorelease pools by allocate/reallocate each time around
3517      the loop; strict nesting is occasionally violated but seems not to
3518      matter.. earlier methods using full nesting caused major memory leaks */
3519   [outerpool release];
3520   outerpool = [[NSAutoreleasePool alloc] init];
3522   /* If have pending open-file requests, attend to the next one of those. */
3523   if (ns_pending_files && [ns_pending_files count] != 0
3524       && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3525     {
3526       [ns_pending_files removeObjectAtIndex: 0];
3527     }
3528   /* Deal with pending service requests. */
3529   else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3530     && [(EmacsApp *)
3531          NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3532                       withArg: [ns_pending_service_args objectAtIndex: 0]])
3533     {
3534       [ns_pending_service_names removeObjectAtIndex: 0];
3535       [ns_pending_service_args removeObjectAtIndex: 0];
3536     }
3537   else
3538     {
3539       /* Run and wait for events.  We must always send one NX_APPDEFINED event
3540          to ourself, otherwise [NXApp run] will never exit.  */
3541       send_appdefined = YES;
3542       ns_send_appdefined (-1);
3544       if (++apploopnr != 1)
3545         {
3546           emacs_abort ();
3547         }
3548       [NSApp run];
3549       --apploopnr;
3550     }
3552   nevents = n_emacs_events_pending;
3553   n_emacs_events_pending = 0;
3554   emacs_event = q_event_ptr = NULL;
3555   unblock_input ();
3557   return nevents;
3562 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3563            fd_set *exceptfds, EMACS_TIME *timeout, sigset_t *sigmask)
3564 /* --------------------------------------------------------------------------
3565      Replacement for select, checking for events
3566    -------------------------------------------------------------------------- */
3568   int result;
3569   int t, k, nr = 0;
3570   struct input_event event;
3571   char c;
3573 /*  NSTRACE (ns_select); */
3575 #ifdef HAVE_NATIVE_FS
3576   check_native_fs ();
3577 #endif
3579   if (hold_event_q.nr > 0)
3580     {
3581       /* We already have events pending. */
3582       raise (SIGIO);
3583       errno = EINTR;
3584       return -1;
3585     }
3587   for (k = 0; k < nfds+1; k++)
3588     {
3589       if (readfds && FD_ISSET(k, readfds)) ++nr;
3590       if (writefds && FD_ISSET(k, writefds)) ++nr;
3591     }
3593   if (NSApp == nil
3594       || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0))
3595     return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
3597   [outerpool release];
3598   outerpool = [[NSAutoreleasePool alloc] init];
3601   send_appdefined = YES;
3602   if (nr > 0)
3603     {
3604       pthread_mutex_lock (&select_mutex);
3605       select_nfds = nfds;
3606       select_valid = 0;
3607       if (readfds)
3608         {
3609           select_readfds = *readfds;
3610           select_valid += SELECT_HAVE_READ;
3611         }
3612       if (writefds)
3613         {
3614           select_writefds = *writefds;
3615           select_valid += SELECT_HAVE_WRITE;
3616         }
3618       if (timeout)
3619         {
3620           select_timeout = *timeout;
3621           select_valid += SELECT_HAVE_TMO;
3622         }
3624       pthread_mutex_unlock (&select_mutex);
3626       /* Inform fd_handler that select should be called */
3627       c = 'g';
3628       emacs_write (selfds[1], &c, 1);
3629     }
3630   else if (nr == 0 && timeout)
3631     {
3632       /* No file descriptor, just a timeout, no need to wake fd_handler  */
3633       double time = EMACS_TIME_TO_DOUBLE (*timeout);
3634       timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3635                                                       target: NSApp
3636                                                     selector:
3637                                   @selector (timeout_handler:)
3638                                                     userInfo: 0
3639                                                      repeats: NO]
3640                       retain];
3641     }
3642   else /* No timeout and no file descriptors, can this happen?  */
3643     {
3644       /* Send appdefined so we exit from the loop */
3645       ns_send_appdefined (-1);
3646     }
3648   EVENT_INIT (event);
3649   block_input ();
3650   emacs_event = &event;
3651   if (++apploopnr != 1)
3652     {
3653       emacs_abort ();
3654     }
3655   [NSApp run];
3656   --apploopnr;
3657   emacs_event = NULL;
3658   if (nr > 0 && readfds)
3659     {
3660       c = 's';
3661       emacs_write (selfds[1], &c, 1);
3662     }
3663   unblock_input ();
3665   t = last_appdefined_event_data;
3667   if (t != NO_APPDEFINED_DATA)
3668     {
3669       last_appdefined_event_data = NO_APPDEFINED_DATA;
3671       if (t == -2)
3672         {
3673           /* The NX_APPDEFINED event we received was a timeout. */
3674           result = 0;
3675         }
3676       else if (t == -1)
3677         {
3678           /* The NX_APPDEFINED event we received was the result of
3679              at least one real input event arriving.  */
3680           errno = EINTR;
3681           result = -1;
3682         }
3683       else
3684         {
3685           /* Received back from select () in fd_handler; copy the results */
3686           pthread_mutex_lock (&select_mutex);
3687           if (readfds) *readfds = select_readfds;
3688           if (writefds) *writefds = select_writefds;
3689           if (timeout) *timeout = select_timeout;
3690           pthread_mutex_unlock (&select_mutex);
3691           result = t;
3692         }
3693     }
3694   else
3695     {
3696       errno = EINTR;
3697       result = -1;
3698     }
3700   return result;
3705 /* ==========================================================================
3707     Scrollbar handling
3709    ========================================================================== */
3712 static void
3713 ns_set_vertical_scroll_bar (struct window *window,
3714                            int portion, int whole, int position)
3715 /* --------------------------------------------------------------------------
3716       External (hook): Update or add scrollbar
3717    -------------------------------------------------------------------------- */
3719   Lisp_Object win;
3720   NSRect r, v;
3721   struct frame *f = XFRAME (WINDOW_FRAME (window));
3722   EmacsView *view = FRAME_NS_VIEW (f);
3723   int window_y, window_height;
3724   int top, left, height, width, sb_width, sb_left;
3725   EmacsScroller *bar;
3726   BOOL fringe_extended_p;
3728   /* optimization; display engine sends WAY too many of these.. */
3729   if (!NILP (window->vertical_scroll_bar))
3730     {
3731       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3732       if ([bar checkSamePosition: position portion: portion whole: whole])
3733         {
3734           if (view->scrollbarsNeedingUpdate == 0)
3735             {
3736               if (!windows_or_buffers_changed)
3737                   return;
3738             }
3739           else
3740             view->scrollbarsNeedingUpdate--;
3741         }
3742     }
3744   NSTRACE (ns_set_vertical_scroll_bar);
3746   /* Get dimensions.  */
3747   window_box (window, -1, 0, &window_y, 0, &window_height);
3748   top = window_y;
3749   height = window_height;
3750   width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3751   left = WINDOW_SCROLL_BAR_AREA_X (window);
3753   /* allow for displaying a skinnier scrollbar than char area allotted */
3754   sb_width = (WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) > 0) ?
3755     WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) : width;
3756   sb_left = left;
3758   r = NSMakeRect (sb_left, top, sb_width, height);
3759   /* the parent view is flipped, so we need to flip y value */
3760   v = [view frame];
3761   r.origin.y = (v.size.height - r.size.height - r.origin.y);
3763   if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (window))
3764     fringe_extended_p = (WINDOW_LEFTMOST_P (window)
3765                          && WINDOW_LEFT_FRINGE_WIDTH (window)
3766                          && (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (window)
3767                              || WINDOW_LEFT_MARGIN_COLS (window) == 0));
3768   else
3769     fringe_extended_p = (WINDOW_RIGHTMOST_P (window)
3770                          && WINDOW_RIGHT_FRINGE_WIDTH (window)
3771                          && (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (window)
3772                              || WINDOW_RIGHT_MARGIN_COLS (window) == 0));
3774   XSETWINDOW (win, window);
3775   block_input ();
3777   /* we want at least 5 lines to display a scrollbar */
3778   if (WINDOW_TOTAL_LINES (window) < 5)
3779     {
3780       if (!NILP (window->vertical_scroll_bar))
3781         {
3782           bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3783           [bar removeFromSuperview];
3784           wset_vertical_scroll_bar (window, Qnil);
3785         }
3786       ns_clear_frame_area (f, sb_left, top, width, height);
3787       unblock_input ();
3788       return;
3789     }
3791   if (NILP (window->vertical_scroll_bar))
3792     {
3793       if (width > 0 && height > 0)
3794         {
3795           if (fringe_extended_p)
3796             ns_clear_frame_area (f, sb_left, top, sb_width, height);
3797           else
3798             ns_clear_frame_area (f, left, top, width, height);
3799         }
3801       bar = [[EmacsScroller alloc] initFrame: r window: win];
3802       wset_vertical_scroll_bar (window, make_save_pointer (bar));
3803     }
3804   else
3805     {
3806       NSRect oldRect;
3807       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3808       oldRect = [bar frame];
3809       r.size.width = oldRect.size.width;
3810       if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3811         {
3812           if (oldRect.origin.x != r.origin.x)
3813               ns_clear_frame_area (f, sb_left, top, width, height);
3814           [bar setFrame: r];
3815         }
3816     }
3818   [bar setPosition: position portion: portion whole: whole];
3819   unblock_input ();
3823 static void
3824 ns_condemn_scroll_bars (struct frame *f)
3825 /* --------------------------------------------------------------------------
3826      External (hook): arrange for all frame's scrollbars to be removed
3827      at next call to judge_scroll_bars, except for those redeemed.
3828    -------------------------------------------------------------------------- */
3830   int i;
3831   id view;
3832   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3834   NSTRACE (ns_condemn_scroll_bars);
3836   for (i =[subviews count]-1; i >= 0; i--)
3837     {
3838       view = [subviews objectAtIndex: i];
3839       if ([view isKindOfClass: [EmacsScroller class]])
3840         [view condemn];
3841     }
3845 static void
3846 ns_redeem_scroll_bar (struct window *window)
3847 /* --------------------------------------------------------------------------
3848      External (hook): arrange to spare this window's scrollbar
3849      at next call to judge_scroll_bars.
3850    -------------------------------------------------------------------------- */
3852   id bar;
3853   NSTRACE (ns_redeem_scroll_bar);
3854   if (!NILP (window->vertical_scroll_bar))
3855     {
3856       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3857       [bar reprieve];
3858     }
3862 static void
3863 ns_judge_scroll_bars (struct frame *f)
3864 /* --------------------------------------------------------------------------
3865      External (hook): destroy all scrollbars on frame that weren't
3866      redeemed after call to condemn_scroll_bars.
3867    -------------------------------------------------------------------------- */
3869   int i;
3870   id view;
3871   EmacsView *eview = FRAME_NS_VIEW (f);
3872   NSArray *subviews = [[eview superview] subviews];
3873   BOOL removed = NO;
3875   NSTRACE (ns_judge_scroll_bars);
3876   for (i = [subviews count]-1; i >= 0; --i)
3877     {
3878       view = [subviews objectAtIndex: i];
3879       if (![view isKindOfClass: [EmacsScroller class]]) continue;
3880       [view judge];
3881       removed = YES;
3882     }
3884   if (removed)
3885     [eview updateFrameSize: NO];
3889 void
3890 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
3892   /* XXX irrelevant under NS */
3897 /* ==========================================================================
3899     Initialization
3901    ========================================================================== */
3904 x_display_pixel_height (struct ns_display_info *dpyinfo)
3906   NSScreen *screen = [NSScreen mainScreen];
3907   return [screen frame].size.height;
3911 x_display_pixel_width (struct ns_display_info *dpyinfo)
3913   NSScreen *screen = [NSScreen mainScreen];
3914   return [screen frame].size.width;
3918 static Lisp_Object ns_string_to_lispmod (const char *s)
3919 /* --------------------------------------------------------------------------
3920      Convert modifier name to lisp symbol
3921    -------------------------------------------------------------------------- */
3923   if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
3924     return Qmeta;
3925   else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
3926     return Qsuper;
3927   else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
3928     return Qcontrol;
3929   else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
3930     return Qalt;
3931   else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
3932     return Qhyper;
3933   else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
3934     return Qnone;
3935   else
3936     return Qnil;
3940 static void
3941 ns_default (const char *parameter, Lisp_Object *result,
3942            Lisp_Object yesval, Lisp_Object noval,
3943            BOOL is_float, BOOL is_modstring)
3944 /* --------------------------------------------------------------------------
3945       Check a parameter value in user's preferences
3946    -------------------------------------------------------------------------- */
3948   const char *value = ns_get_defaults_value (parameter);
3950   if (value)
3951     {
3952       double f;
3953       char *pos;
3954       if (c_strcasecmp (value, "YES") == 0)
3955         *result = yesval;
3956       else if (c_strcasecmp (value, "NO") == 0)
3957         *result = noval;
3958       else if (is_float && (f = strtod (value, &pos), pos != value))
3959         *result = make_float (f);
3960       else if (is_modstring && value)
3961         *result = ns_string_to_lispmod (value);
3962       else fprintf (stderr,
3963                    "Bad value for default \"%s\": \"%s\"\n", parameter, value);
3964     }
3968 static void
3969 ns_initialize_display_info (struct ns_display_info *dpyinfo)
3970 /* --------------------------------------------------------------------------
3971       Initialize global info and storage for display.
3972    -------------------------------------------------------------------------- */
3974     NSScreen *screen = [NSScreen mainScreen];
3975     NSWindowDepth depth = [screen depth];
3976     Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
3978     dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
3979     dpyinfo->resy = 72.27;
3980     dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
3981                                                   NSColorSpaceFromDepth (depth)]
3982                 && ![NSCalibratedWhiteColorSpace isEqualToString:
3983                                                  NSColorSpaceFromDepth (depth)];
3984     dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
3985     dpyinfo->image_cache = make_image_cache ();
3986     dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
3987     dpyinfo->color_table->colors = NULL;
3988     dpyinfo->root_window = 42; /* a placeholder.. */
3990     hlinfo->mouse_face_mouse_frame = NULL;
3991     hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
3992     hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
3993     hlinfo->mouse_face_face_id = DEFAULT_FACE_ID;
3994     hlinfo->mouse_face_window = hlinfo->mouse_face_overlay = Qnil;
3995     hlinfo->mouse_face_hidden = 0;
3997     hlinfo->mouse_face_mouse_x = hlinfo->mouse_face_mouse_y = 0;
3998     hlinfo->mouse_face_defer = 0;
4000     dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
4002     dpyinfo->n_fonts = 0;
4003     dpyinfo->smallest_font_height = 1;
4004     dpyinfo->smallest_char_width = 1;
4008 /* This and next define (many of the) public functions in this file. */
4009 /* x_... are generic versions in xdisp.c that we, and other terms, get away
4010          with using despite presence in the "system dependent" redisplay
4011          interface.  In addition, many of the ns_ methods have code that is
4012          shared with all terms, indicating need for further refactoring. */
4013 extern frame_parm_handler ns_frame_parm_handlers[];
4014 static struct redisplay_interface ns_redisplay_interface =
4016   ns_frame_parm_handlers,
4017   x_produce_glyphs,
4018   x_write_glyphs,
4019   x_insert_glyphs,
4020   x_clear_end_of_line,
4021   ns_scroll_run,
4022   ns_after_update_window_line,
4023   ns_update_window_begin,
4024   ns_update_window_end,
4025   x_cursor_to,
4026   ns_flush,
4027   0, /* flush_display_optional */
4028   x_clear_window_mouse_face,
4029   x_get_glyph_overhangs,
4030   x_fix_overlapping_area,
4031   ns_draw_fringe_bitmap,
4032   0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
4033   0, /* destroy_fringe_bitmap */
4034   ns_compute_glyph_string_overhangs,
4035   ns_draw_glyph_string, /* interface to nsfont.m */
4036   ns_define_frame_cursor,
4037   ns_clear_frame_area,
4038   ns_draw_window_cursor,
4039   ns_draw_vertical_window_border,
4040   ns_shift_glyphs_for_insert
4044 static void
4045 ns_delete_display (struct ns_display_info *dpyinfo)
4047   /* TODO... */
4051 /* This function is called when the last frame on a display is deleted. */
4052 static void
4053 ns_delete_terminal (struct terminal *terminal)
4055   struct ns_display_info *dpyinfo = terminal->display_info.ns;
4057   /* Protect against recursive calls.  delete_frame in
4058      delete_terminal calls us back when it deletes our last frame.  */
4059   if (!terminal->name)
4060     return;
4062   block_input ();
4064   x_destroy_all_bitmaps (dpyinfo);
4065   ns_delete_display (dpyinfo);
4066   unblock_input ();
4070 static struct terminal *
4071 ns_create_terminal (struct ns_display_info *dpyinfo)
4072 /* --------------------------------------------------------------------------
4073       Set up use of NS before we make the first connection.
4074    -------------------------------------------------------------------------- */
4076   struct terminal *terminal;
4078   NSTRACE (ns_create_terminal);
4080   terminal = create_terminal ();
4082   terminal->type = output_ns;
4083   terminal->display_info.ns = dpyinfo;
4084   dpyinfo->terminal = terminal;
4086   terminal->rif = &ns_redisplay_interface;
4088   terminal->clear_frame_hook = ns_clear_frame;
4089   terminal->ins_del_lines_hook = 0; /* XXX vestigial? */
4090   terminal->delete_glyphs_hook = 0; /* XXX vestigial? */
4091   terminal->ring_bell_hook = ns_ring_bell;
4092   terminal->reset_terminal_modes_hook = ns_reset_terminal_modes;
4093   terminal->set_terminal_modes_hook = ns_set_terminal_modes;
4094   terminal->update_begin_hook = ns_update_begin;
4095   terminal->update_end_hook = ns_update_end;
4096   terminal->set_terminal_window_hook = NULL; /* XXX vestigial? */
4097   terminal->read_socket_hook = ns_read_socket;
4098   terminal->frame_up_to_date_hook = ns_frame_up_to_date;
4099   terminal->mouse_position_hook = ns_mouse_position;
4100   terminal->frame_rehighlight_hook = ns_frame_rehighlight;
4101   terminal->frame_raise_lower_hook = ns_frame_raise_lower;
4103   terminal->fullscreen_hook = ns_fullscreen_hook;
4105   terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
4106   terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
4107   terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
4108   terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
4110   terminal->delete_frame_hook = x_destroy_window;
4111   terminal->delete_terminal_hook = ns_delete_terminal;
4113   terminal->scroll_region_ok = 1;
4114   terminal->char_ins_del_ok = 1;
4115   terminal->line_ins_del_ok = 1;
4116   terminal->fast_clear_end_of_line = 1;
4117   terminal->memory_below_frame = 0;
4119   return terminal;
4123 struct ns_display_info *
4124 ns_term_init (Lisp_Object display_name)
4125 /* --------------------------------------------------------------------------
4126      Start the Application and get things rolling.
4127    -------------------------------------------------------------------------- */
4129   struct terminal *terminal;
4130   struct ns_display_info *dpyinfo;
4131   static int ns_initialized = 0;
4132   Lisp_Object tmp;
4134   if (ns_initialized) return x_display_list;
4135   ns_initialized = 1;
4137   NSTRACE (ns_term_init);
4139   [outerpool release];
4140   outerpool = [[NSAutoreleasePool alloc] init];
4142   /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4143   /*GSDebugAllocationActive (YES); */
4144   block_input ();
4146   baud_rate = 38400;
4147   Fset_input_interrupt_mode (Qnil);
4149   if (selfds[0] == -1)
4150     {
4151       if (pipe (selfds) == -1)
4152         {
4153           fprintf (stderr, "Failed to create pipe: %s\n",
4154                    emacs_strerror (errno));
4155           emacs_abort ();
4156         }
4158       fcntl (selfds[0], F_SETFL, O_NONBLOCK|fcntl (selfds[0], F_GETFL));
4159       FD_ZERO (&select_readfds);
4160       FD_ZERO (&select_writefds);
4161       pthread_mutex_init (&select_mutex, NULL);
4162     }
4164   ns_pending_files = [[NSMutableArray alloc] init];
4165   ns_pending_service_names = [[NSMutableArray alloc] init];
4166   ns_pending_service_args = [[NSMutableArray alloc] init];
4168 /* Start app and create the main menu, window, view.
4169      Needs to be here because ns_initialize_display_info () uses AppKit classes.
4170      The view will then ask the NSApp to stop and return to Emacs. */
4171   [EmacsApp sharedApplication];
4172   if (NSApp == nil)
4173     return NULL;
4174   [NSApp setDelegate: NSApp];
4176   /* Start the select thread.  */
4177   [NSThread detachNewThreadSelector:@selector (fd_handler:)
4178                            toTarget:NSApp
4179                          withObject:nil];
4181   /* debugging: log all notifications */
4182   /*   [[NSNotificationCenter defaultCenter] addObserver: NSApp
4183                                          selector: @selector (logNotification:)
4184                                              name: nil object: nil]; */
4186   dpyinfo = xzalloc (sizeof *dpyinfo);
4188   ns_initialize_display_info (dpyinfo);
4189   terminal = ns_create_terminal (dpyinfo);
4191   terminal->kboard = xmalloc (sizeof *terminal->kboard);
4192   init_kboard (terminal->kboard);
4193   kset_window_system (terminal->kboard, Qns);
4194   terminal->kboard->next_kboard = all_kboards;
4195   all_kboards = terminal->kboard;
4196   /* Don't let the initial kboard remain current longer than necessary.
4197      That would cause problems if a file loaded on startup tries to
4198      prompt in the mini-buffer.  */
4199   if (current_kboard == initial_kboard)
4200     current_kboard = terminal->kboard;
4201   terminal->kboard->reference_count++;
4203   dpyinfo->next = x_display_list;
4204   x_display_list = dpyinfo;
4206   /* Put it on ns_display_name_list */
4207   ns_display_name_list = Fcons (Fcons (display_name, Qnil),
4208                                 ns_display_name_list);
4209   dpyinfo->name_list_element = XCAR (ns_display_name_list);
4211   terminal->name = xstrdup (SSDATA (display_name));
4213   unblock_input ();
4215   if (!inhibit_x_resources)
4216     {
4217       ns_default ("GSFontAntiAlias", &ns_antialias_text,
4218                  Qt, Qnil, NO, NO);
4219       tmp = Qnil;
4220       /* this is a standard variable */
4221       ns_default ("AppleAntiAliasingThreshold", &tmp,
4222                  make_float (10.0), make_float (6.0), YES, NO);
4223       ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4224     }
4226   ns_selection_color = [[NSUserDefaults standardUserDefaults]
4227                          stringForKey: @"AppleHighlightColor"];
4228   if (ns_selection_color == nil)
4229     ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
4231   {
4232     NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4234     if ( cl == nil )
4235       {
4236         Lisp_Object color_file, color_map, color;
4237         unsigned long c;
4238         char *name;
4240         color_file = Fexpand_file_name (build_string ("rgb.txt"),
4241                          Fsymbol_value (intern ("data-directory")));
4243         color_map = Fx_load_color_file (color_file);
4244         if (NILP (color_map))
4245           fatal ("Could not read %s.\n", SDATA (color_file));
4247         cl = [[NSColorList alloc] initWithName: @"Emacs"];
4248         for ( ; CONSP (color_map); color_map = XCDR (color_map))
4249           {
4250             color = XCAR (color_map);
4251             name = SSDATA (XCAR (color));
4252             c = XINT (XCDR (color));
4253             [cl setColor:
4254                   [NSColor colorWithCalibratedRed: RED_FROM_ULONG (c) / 255.0
4255                                             green: GREEN_FROM_ULONG (c) / 255.0
4256                                              blue: BLUE_FROM_ULONG (c) / 255.0
4257                                             alpha: 1.0]
4258                   forKey: [NSString stringWithUTF8String: name]];
4259           }
4260         [cl writeToFile: nil];
4261       }
4262   }
4264   {
4265 #ifdef NS_IMPL_GNUSTEP
4266     Vwindow_system_version = build_string (gnustep_base_version);
4267 #else
4268     /*PSnextrelease (128, c); */
4269     char c[DBL_BUFSIZE_BOUND];
4270     int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4271     Vwindow_system_version = make_unibyte_string (c, len);
4272 #endif
4273   }
4275   delete_keyboard_wait_descriptor (0);
4277   ns_app_name = [[NSProcessInfo processInfo] processName];
4279 /* Set up OS X app menu */
4280 #ifdef NS_IMPL_COCOA
4281   {
4282     NSMenu *appMenu;
4283     NSMenuItem *item;
4284     /* set up the application menu */
4285     svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4286     [svcsMenu setAutoenablesItems: NO];
4287     appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4288     [appMenu setAutoenablesItems: NO];
4289     mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4290     dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4292     [appMenu insertItemWithTitle: @"About Emacs"
4293                           action: @selector (orderFrontStandardAboutPanel:)
4294                    keyEquivalent: @""
4295                          atIndex: 0];
4296     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4297     [appMenu insertItemWithTitle: @"Preferences..."
4298                           action: @selector (showPreferencesWindow:)
4299                    keyEquivalent: @","
4300                          atIndex: 2];
4301     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4302     item = [appMenu insertItemWithTitle: @"Services"
4303                                  action: @selector (menuDown:)
4304                           keyEquivalent: @""
4305                                 atIndex: 4];
4306     [appMenu setSubmenu: svcsMenu forItem: item];
4307     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4308     [appMenu insertItemWithTitle: @"Hide Emacs"
4309                           action: @selector (hide:)
4310                    keyEquivalent: @"h"
4311                          atIndex: 6];
4312     item =  [appMenu insertItemWithTitle: @"Hide Others"
4313                           action: @selector (hideOtherApplications:)
4314                    keyEquivalent: @"h"
4315                          atIndex: 7];
4316     [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4317     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4318     [appMenu insertItemWithTitle: @"Quit Emacs"
4319                           action: @selector (terminate:)
4320                    keyEquivalent: @"q"
4321                          atIndex: 9];
4323     item = [mainMenu insertItemWithTitle: ns_app_name
4324                                   action: @selector (menuDown:)
4325                            keyEquivalent: @""
4326                                  atIndex: 0];
4327     [mainMenu setSubmenu: appMenu forItem: item];
4328     [dockMenu insertItemWithTitle: @"New Frame"
4329                            action: @selector (newFrame:)
4330                     keyEquivalent: @""
4331                           atIndex: 0];
4333     [NSApp setMainMenu: mainMenu];
4334     [NSApp setAppleMenu: appMenu];
4335     [NSApp setServicesMenu: svcsMenu];
4336     /* Needed at least on Cocoa, to get dock menu to show windows */
4337     [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4339     [[NSNotificationCenter defaultCenter]
4340       addObserver: mainMenu
4341          selector: @selector (trackingNotification:)
4342              name: NSMenuDidBeginTrackingNotification object: mainMenu];
4343     [[NSNotificationCenter defaultCenter]
4344       addObserver: mainMenu
4345          selector: @selector (trackingNotification:)
4346              name: NSMenuDidEndTrackingNotification object: mainMenu];
4347   }
4348 #endif /* MAC OS X menu setup */
4350   /* Register our external input/output types, used for determining
4351      applicable services and also drag/drop eligibility. */
4352   ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
4353   ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
4354                       retain];
4355   ns_drag_types = [[NSArray arrayWithObjects:
4356                             NSStringPboardType,
4357                             NSTabularTextPboardType,
4358                             NSFilenamesPboardType,
4359                             NSURLPboardType,
4360                             NSColorPboardType,
4361                             NSFontPboardType, nil] retain];
4363   /* If fullscreen is in init/default-frame-alist, focus isn't set
4364      right for fullscreen windows, so set this.  */
4365   [NSApp activateIgnoringOtherApps:YES];
4367   [NSApp run];
4368   ns_do_open_file = YES;
4369   return dpyinfo;
4373 void
4374 ns_term_shutdown (int sig)
4376   [[NSUserDefaults standardUserDefaults] synchronize];
4378   /* code not reached in emacs.c after this is called by shut_down_emacs: */
4379   if (STRINGP (Vauto_save_list_file_name))
4380     unlink (SSDATA (Vauto_save_list_file_name));
4382   if (sig == 0 || sig == SIGTERM)
4383     {
4384       [NSApp terminate: NSApp];
4385     }
4386   else // force a stack trace to happen
4387     {
4388       emacs_abort ();
4389     }
4393 /* ==========================================================================
4395     EmacsApp implementation
4397    ========================================================================== */
4400 @implementation EmacsApp
4402 - (void)logNotification: (NSNotification *)notification
4404   const char *name = [[notification name] UTF8String];
4405   if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4406       && !strstr (name, "WindowNumber"))
4407     NSLog (@"notification: '%@'", [notification name]);
4411 - (void)sendEvent: (NSEvent *)theEvent
4412 /* --------------------------------------------------------------------------
4413      Called when NSApp is running for each event received.  Used to stop
4414      the loop when we choose, since there's no way to just run one iteration.
4415    -------------------------------------------------------------------------- */
4417   int type = [theEvent type];
4418   NSWindow *window = [theEvent window];
4419 /*  NSTRACE (sendEvent); */
4420 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4422 #ifdef NS_IMPL_COCOA
4423   if (type == NSApplicationDefined
4424       && [theEvent data2] == NSAPP_DATA2_RUNASSCRIPT)
4425     {
4426       ns_run_ascript ();
4427       [self stop: self];
4428       return;
4429     }
4430 #endif
4432   if (type == NSCursorUpdate && window == nil)
4433     {
4434       fprintf (stderr, "Dropping external cursor update event.\n");
4435       return;
4436     }
4438   if (type == NSApplicationDefined)
4439     {
4440       /* Events posted by ns_send_appdefined interrupt the run loop here.
4441          But, if a modal window is up, an appdefined can still come through,
4442          (e.g., from a makeKeyWindow event) but stopping self also stops the
4443          modal loop. Just defer it until later. */
4444       if ([NSApp modalWindow] == nil)
4445         {
4446           last_appdefined_event_data = [theEvent data1];
4447           [self stop: self];
4448         }
4449       else
4450         {
4451           send_appdefined = YES;
4452         }
4453     }
4455   [super sendEvent: theEvent];
4459 - (void)showPreferencesWindow: (id)sender
4461   struct frame *emacsframe = SELECTED_FRAME ();
4462   NSEvent *theEvent = [NSApp currentEvent];
4464   if (!emacs_event)
4465     return;
4466   emacs_event->kind = NS_NONKEY_EVENT;
4467   emacs_event->code = KEY_NS_SHOW_PREFS;
4468   emacs_event->modifiers = 0;
4469   EV_TRAILER (theEvent);
4473 - (void)newFrame: (id)sender
4475   struct frame *emacsframe = SELECTED_FRAME ();
4476   NSEvent *theEvent = [NSApp currentEvent];
4478   if (!emacs_event)
4479     return;
4480   emacs_event->kind = NS_NONKEY_EVENT;
4481   emacs_event->code = KEY_NS_NEW_FRAME;
4482   emacs_event->modifiers = 0;
4483   EV_TRAILER (theEvent);
4487 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4488 - (BOOL) openFile: (NSString *)fileName
4490   struct frame *emacsframe = SELECTED_FRAME ();
4491   NSEvent *theEvent = [NSApp currentEvent];
4493   if (!emacs_event)
4494     return NO;
4496   emacs_event->kind = NS_NONKEY_EVENT;
4497   emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4498   ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4499   ns_input_line = Qnil; /* can be start or cons start,end */
4500   emacs_event->modifiers =0;
4501   EV_TRAILER (theEvent);
4503   return YES;
4507 /* **************************************************************************
4509       EmacsApp delegate implementation
4511    ************************************************************************** */
4513 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4514 /* --------------------------------------------------------------------------
4515      When application is loaded, terminate event loop in ns_term_init
4516    -------------------------------------------------------------------------- */
4518   NSTRACE (applicationDidFinishLaunching);
4519   [NSApp setServicesProvider: NSApp];
4520   ns_send_appdefined (-2);
4524 /* Termination sequences:
4525     C-x C-c:
4526     Cmd-Q:
4527     MenuBar | File | Exit:
4528     Select Quit from App menubar:
4529         -terminate
4530         KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4531         ns_term_shutdown()
4533     Select Quit from Dock menu:
4534     Logout attempt:
4535         -appShouldTerminate
4536           Cancel -> Nothing else
4537           Accept ->
4539           -terminate
4540           KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4541           ns_term_shutdown()
4545 - (void) terminate: (id)sender
4547   struct frame *emacsframe = SELECTED_FRAME ();
4549   if (!emacs_event)
4550     return;
4552   emacs_event->kind = NS_NONKEY_EVENT;
4553   emacs_event->code = KEY_NS_POWER_OFF;
4554   emacs_event->arg = Qt; /* mark as non-key event */
4555   EV_TRAILER ((id)nil);
4559 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4561   int ret;
4563   if (NILP (ns_confirm_quit)) //   || ns_shutdown_properly  --> TO DO
4564     return NSTerminateNow;
4566     ret = NSRunAlertPanel(ns_app_name,
4567                           @"Exit requested.  Would you like to Save Buffers and Exit, or Cancel the request?",
4568                           @"Save Buffers and Exit", @"Cancel", nil);
4570     if (ret == NSAlertDefaultReturn)
4571         return NSTerminateNow;
4572     else if (ret == NSAlertAlternateReturn)
4573         return NSTerminateCancel;
4574     return NSTerminateNow;  /* just in case */
4577 static int
4578 not_in_argv (NSString *arg)
4580   int k;
4581   const char *a = [arg UTF8String];
4582   for (k = 1; k < initial_argc; ++k)
4583     if (strcmp (a, initial_argv[k]) == 0) return 0;
4584   return 1;
4587 /*   Notification from the Workspace to open a file */
4588 - (BOOL)application: sender openFile: (NSString *)file
4590   if (ns_do_open_file || not_in_argv (file))
4591     [ns_pending_files addObject: file];
4592   return YES;
4596 /*   Open a file as a temporary file */
4597 - (BOOL)application: sender openTempFile: (NSString *)file
4599   if (ns_do_open_file || not_in_argv (file))
4600     [ns_pending_files addObject: file];
4601   return YES;
4605 /*   Notification from the Workspace to open a file noninteractively (?) */
4606 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4608   if (ns_do_open_file || not_in_argv (file))
4609     [ns_pending_files addObject: file];
4610   return YES;
4613 /*   Notification from the Workspace to open multiple files */
4614 - (void)application: sender openFiles: (NSArray *)fileList
4616   NSEnumerator *files = [fileList objectEnumerator];
4617   NSString *file;
4618   /* Don't open files from the command line unconditionally,
4619      Cocoa parses the command line wrong, --option value tries to open value
4620      if --option is the last option.  */
4621   while ((file = [files nextObject]) != nil)
4622     if (ns_do_open_file || not_in_argv (file))
4623       [ns_pending_files addObject: file];
4625   [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4630 /* Handle dock menu requests.  */
4631 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4633   return dockMenu;
4637 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4638 - (void)applicationWillBecomeActive: (NSNotification *)notification
4640   //ns_app_active=YES;
4642 - (void)applicationDidBecomeActive: (NSNotification *)notification
4644   NSTRACE (applicationDidBecomeActive);
4646   //ns_app_active=YES;
4648   ns_update_auto_hide_menu_bar ();
4649   // No constraining takes place when the application is not active.
4650   ns_constrain_all_frames ();
4652 - (void)applicationDidResignActive: (NSNotification *)notification
4654   //ns_app_active=NO;
4655   ns_send_appdefined (-1);
4660 /* ==========================================================================
4662     EmacsApp aux handlers for managing event loop
4664    ========================================================================== */
4667 - (void)timeout_handler: (NSTimer *)timedEntry
4668 /* --------------------------------------------------------------------------
4669      The timeout specified to ns_select has passed.
4670    -------------------------------------------------------------------------- */
4672   /*NSTRACE (timeout_handler); */
4673   ns_send_appdefined (-2);
4676 - (void)fd_handler:(id)unused
4677 /* --------------------------------------------------------------------------
4678      Check data waiting on file descriptors and terminate if so
4679    -------------------------------------------------------------------------- */
4681   int result;
4682   int waiting = 1, nfds;
4683   char c;
4685   SELECT_TYPE readfds, writefds, *wfds;
4686   EMACS_TIME timeout, *tmo;
4687   NSAutoreleasePool *pool = nil;
4689   /* NSTRACE (fd_handler); */
4691   for (;;)
4692     {
4693       [pool release];
4694       pool = [[NSAutoreleasePool alloc] init];
4696       if (waiting)
4697         {
4698           SELECT_TYPE fds;
4699           FD_ZERO (&fds);
4700           FD_SET (selfds[0], &fds);
4701           result = select (selfds[0]+1, &fds, NULL, NULL, NULL);
4702           if (result > 0 && read (selfds[0], &c, 1) == 1 && c == 'g')
4703             waiting = 0;
4704         }
4705       else
4706         {
4707           pthread_mutex_lock (&select_mutex);
4708           nfds = select_nfds;
4710           if (select_valid & SELECT_HAVE_READ)
4711             readfds = select_readfds;
4712           else
4713             FD_ZERO (&readfds);
4715           if (select_valid & SELECT_HAVE_WRITE)
4716             {
4717               writefds = select_writefds;
4718               wfds = &writefds;
4719             }
4720           else
4721             wfds = NULL;
4722           if (select_valid & SELECT_HAVE_TMO)
4723             {
4724               timeout = select_timeout;
4725               tmo = &timeout;
4726             }
4727           else
4728             tmo = NULL;
4730           pthread_mutex_unlock (&select_mutex);
4732           FD_SET (selfds[0], &readfds);
4733           if (selfds[0] >= nfds) nfds = selfds[0]+1;
4735           result = pselect (nfds, &readfds, wfds, NULL, tmo, NULL);
4737           if (result == 0)
4738             ns_send_appdefined (-2);
4739           else if (result > 0)
4740             {
4741               if (FD_ISSET (selfds[0], &readfds))
4742                 {
4743                   if (read (selfds[0], &c, 1) == 1 && c == 's')
4744                     waiting = 1;
4745                 }
4746               else
4747                 {
4748                   pthread_mutex_lock (&select_mutex);
4749                   if (select_valid & SELECT_HAVE_READ)
4750                     select_readfds = readfds;
4751                   if (select_valid & SELECT_HAVE_WRITE)
4752                     select_writefds = writefds;
4753                   if (select_valid & SELECT_HAVE_TMO)
4754                     select_timeout = timeout;
4755                   pthread_mutex_unlock (&select_mutex);
4757                   ns_send_appdefined (result);
4758                 }
4759             }
4760           waiting = 1;
4761         }
4762     }
4767 /* ==========================================================================
4769     Service provision
4771    ========================================================================== */
4773 /* called from system: queue for next pass through event loop */
4774 - (void)requestService: (NSPasteboard *)pboard
4775               userData: (NSString *)userData
4776                  error: (NSString **)error
4778   [ns_pending_service_names addObject: userData];
4779   [ns_pending_service_args addObject: [NSString stringWithUTF8String:
4780       SSDATA (ns_string_from_pasteboard (pboard))]];
4784 /* called from ns_read_socket to clear queue */
4785 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
4787   struct frame *emacsframe = SELECTED_FRAME ();
4788   NSEvent *theEvent = [NSApp currentEvent];
4790   if (!emacs_event)
4791     return NO;
4793   emacs_event->kind = NS_NONKEY_EVENT;
4794   emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
4795   ns_input_spi_name = build_string ([name UTF8String]);
4796   ns_input_spi_arg = build_string ([arg UTF8String]);
4797   emacs_event->modifiers = EV_MODIFIERS (theEvent);
4798   EV_TRAILER (theEvent);
4800   return YES;
4804 @end  /* EmacsApp */
4808 /* ==========================================================================
4810     EmacsView implementation
4812    ========================================================================== */
4815 @implementation EmacsView
4817 /* needed to inform when window closed from LISP */
4818 - (void) setWindowClosing: (BOOL)closing
4820   windowClosing = closing;
4824 - (void)dealloc
4826   NSTRACE (EmacsView_dealloc);
4827   [toolbar release];
4828   if (fs_state == FULLSCREEN_BOTH)
4829     [nonfs_window release];
4830   [super dealloc];
4834 /* called on font panel selection */
4835 - (void)changeFont: (id)sender
4837   NSEvent *e =[[self window] currentEvent];
4838   struct face *face =FRAME_DEFAULT_FACE (emacsframe);
4839   id newFont;
4840   float size;
4842   NSTRACE (changeFont);
4843   if (!emacs_event)
4844     return;
4846   if ((newFont = [sender convertFont:
4847                            ((struct nsfont_info *)face->font)->nsfont]))
4848     {
4849       SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
4851       emacs_event->kind = NS_NONKEY_EVENT;
4852       emacs_event->modifiers = 0;
4853       emacs_event->code = KEY_NS_CHANGE_FONT;
4855       size = [newFont pointSize];
4856       ns_input_fontsize = make_number (lrint (size));
4857       ns_input_font = build_string ([[newFont familyName] UTF8String]);
4858       EV_TRAILER (e);
4859     }
4863 - (BOOL)acceptsFirstResponder
4865   NSTRACE (acceptsFirstResponder);
4866   return YES;
4870 - (void)resetCursorRects
4872   NSRect visible = [self visibleRect];
4873   NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
4874   NSTRACE (resetCursorRects);
4876   if (currentCursor == nil)
4877     currentCursor = [NSCursor arrowCursor];
4879   if (!NSIsEmptyRect (visible))
4880     [self addCursorRect: visible cursor: currentCursor];
4881   [currentCursor setOnMouseEntered: YES];
4886 /*****************************************************************************/
4887 /* Keyboard handling. */
4888 #define NS_KEYLOG 0
4890 - (void)keyDown: (NSEvent *)theEvent
4892   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
4893   int code;
4894   unsigned fnKeysym = 0;
4895   static NSMutableArray *nsEvArray;
4896 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
4897   static BOOL firstTime = YES;
4898 #endif
4899   int left_is_none;
4900   unsigned int flags = [theEvent modifierFlags];
4902   NSTRACE (keyDown);
4904   /* Rhapsody and OS X give up and down events for the arrow keys */
4905   if (ns_fake_keydown == YES)
4906     ns_fake_keydown = NO;
4907   else if ([theEvent type] != NSKeyDown)
4908     return;
4910   if (!emacs_event)
4911     return;
4913  if (![[self window] isKeyWindow]
4914      && [[theEvent window] isKindOfClass: [EmacsWindow class]]
4915      /* we must avoid an infinite loop here. */
4916      && (EmacsView *)[[theEvent window] delegate] != self)
4917    {
4918      /* XXX: There is an occasional condition in which, when Emacs display
4919          updates a different frame from the current one, and temporarily
4920          selects it, then processes some interrupt-driven input
4921          (dispnew.c:3878), OS will send the event to the correct NSWindow, but
4922          for some reason that window has its first responder set to the NSView
4923          most recently updated (I guess), which is not the correct one. */
4924      [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
4925      return;
4926    }
4928   if (nsEvArray == nil)
4929     nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
4931   [NSCursor setHiddenUntilMouseMoves: YES];
4933   if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
4934     {
4935       clear_mouse_face (hlinfo);
4936       hlinfo->mouse_face_hidden = 1;
4937     }
4939   if (!processingCompose)
4940     {
4941       /* When using screen sharing, no left or right information is sent,
4942          so use Left key in those cases.  */
4943       int is_left_key, is_right_key;
4945       code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
4946         0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
4948       /* (Carbon way: [theEvent keyCode]) */
4950       /* is it a "function key"? */
4951       fnKeysym = (code < 0x00ff && (flags&NSNumericPadKeyMask))
4952         ? ns_convert_key ([theEvent keyCode] | NSNumericPadKeyMask)
4953         : ns_convert_key (code);
4955       if (fnKeysym)
4956         {
4957           /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
4958              because Emacs treats Delete and KP-Delete same (in simple.el). */
4959           if (fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
4960             code = 0xFF08; /* backspace */
4961           else
4962             code = fnKeysym;
4963         }
4965       /* are there modifiers? */
4966       emacs_event->modifiers = 0;
4968       if (flags & NSHelpKeyMask)
4969           emacs_event->modifiers |= hyper_modifier;
4971       if (flags & NSShiftKeyMask)
4972         emacs_event->modifiers |= shift_modifier;
4974       is_right_key = (flags & NSRightCommandKeyMask) == NSRightCommandKeyMask;
4975       is_left_key = (flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask
4976         || (! is_right_key && (flags & NSCommandKeyMask) == NSCommandKeyMask);
4978       if (is_right_key)
4979         emacs_event->modifiers |= parse_solitary_modifier
4980           (EQ (ns_right_command_modifier, Qleft)
4981            ? ns_command_modifier
4982            : ns_right_command_modifier);
4984       if (is_left_key)
4985         {
4986           emacs_event->modifiers |= parse_solitary_modifier
4987             (ns_command_modifier);
4989           /* if super (default), take input manager's word so things like
4990              dvorak / qwerty layout work */
4991           if (EQ (ns_command_modifier, Qsuper)
4992               && !fnKeysym
4993               && [[theEvent characters] length] != 0)
4994             {
4995               /* XXX: the code we get will be unshifted, so if we have
4996                  a shift modifier, must convert ourselves */
4997               if (!(flags & NSShiftKeyMask))
4998                 code = [[theEvent characters] characterAtIndex: 0];
4999 #if 0
5000               /* this is ugly and also requires linking w/Carbon framework
5001                  (for LMGetKbdType) so for now leave this rare (?) case
5002                  undealt with.. in future look into CGEvent methods */
5003               else
5004                 {
5005                   long smv = GetScriptManagerVariable (smKeyScript);
5006                   Handle uchrHandle = GetResource
5007                     ('uchr', GetScriptVariable (smv, smScriptKeys));
5008                   UInt32 dummy = 0;
5009                   UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
5010                                  [[theEvent characters] characterAtIndex: 0],
5011                                  kUCKeyActionDisplay,
5012                                  (flags & ~NSCommandKeyMask) >> 8,
5013                                  LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
5014                                  &dummy, 1, &dummy, &code);
5015                   code &= 0xFF;
5016                 }
5017 #endif
5018             }
5019         }
5021       is_right_key = (flags & NSRightControlKeyMask) == NSRightControlKeyMask;
5022       is_left_key = (flags & NSLeftControlKeyMask) == NSLeftControlKeyMask
5023         || (! is_right_key && (flags & NSControlKeyMask) == NSControlKeyMask);
5025       if (is_right_key)
5026           emacs_event->modifiers |= parse_solitary_modifier
5027               (EQ (ns_right_control_modifier, Qleft)
5028                ? ns_control_modifier
5029                : ns_right_control_modifier);
5031       if (is_left_key)
5032         emacs_event->modifiers |= parse_solitary_modifier
5033           (ns_control_modifier);
5035       if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
5036           emacs_event->modifiers |=
5037             parse_solitary_modifier (ns_function_modifier);
5039       left_is_none = NILP (ns_alternate_modifier)
5040         || EQ (ns_alternate_modifier, Qnone);
5042       is_right_key = (flags & NSRightAlternateKeyMask)
5043         == NSRightAlternateKeyMask;
5044       is_left_key = (flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask
5045         || (! is_right_key
5046             && (flags & NSAlternateKeyMask) == NSAlternateKeyMask);
5048       if (is_right_key)
5049         {
5050           if ((NILP (ns_right_alternate_modifier)
5051                || EQ (ns_right_alternate_modifier, Qnone)
5052                || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
5053               && !fnKeysym)
5054             {   /* accept pre-interp alt comb */
5055               if ([[theEvent characters] length] > 0)
5056                 code = [[theEvent characters] characterAtIndex: 0];
5057               /*HACK: clear lone shift modifier to stop next if from firing */
5058               if (emacs_event->modifiers == shift_modifier)
5059                 emacs_event->modifiers = 0;
5060             }
5061           else
5062             emacs_event->modifiers |= parse_solitary_modifier
5063               (EQ (ns_right_alternate_modifier, Qleft)
5064                ? ns_alternate_modifier
5065                : ns_right_alternate_modifier);
5066         }
5068       if (is_left_key) /* default = meta */
5069         {
5070           if (left_is_none && !fnKeysym)
5071             {   /* accept pre-interp alt comb */
5072               if ([[theEvent characters] length] > 0)
5073                 code = [[theEvent characters] characterAtIndex: 0];
5074               /*HACK: clear lone shift modifier to stop next if from firing */
5075               if (emacs_event->modifiers == shift_modifier)
5076                 emacs_event->modifiers = 0;
5077             }
5078           else
5079               emacs_event->modifiers |=
5080                 parse_solitary_modifier (ns_alternate_modifier);
5081         }
5083   if (NS_KEYLOG)
5084     fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
5085              code, fnKeysym, flags, emacs_event->modifiers);
5087       /* if it was a function key or had modifiers, pass it directly to emacs */
5088       if (fnKeysym || (emacs_event->modifiers
5089                        && (emacs_event->modifiers != shift_modifier)
5090                        && [[theEvent charactersIgnoringModifiers] length] > 0))
5091 /*[[theEvent characters] length] */
5092         {
5093           emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5094           if (code < 0x20)
5095             code |= (1<<28)|(3<<16);
5096           else if (code == 0x7f)
5097             code |= (1<<28)|(3<<16);
5098           else if (!fnKeysym)
5099             emacs_event->kind = code > 0xFF
5100               ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5102           emacs_event->code = code;
5103           EV_TRAILER (theEvent);
5104           processingCompose = NO;
5105           return;
5106         }
5107     }
5110 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
5111   /* if we get here we should send the key for input manager processing */
5112   if (firstTime && [[NSInputManager currentInputManager]
5113                      wantsToDelayTextChangeNotifications] == NO)
5114     fprintf (stderr,
5115           "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
5116   firstTime = NO;
5117 #endif
5118   if (NS_KEYLOG && !processingCompose)
5119     fprintf (stderr, "keyDown: Begin compose sequence.\n");
5121   processingCompose = YES;
5122   [nsEvArray addObject: theEvent];
5123   [self interpretKeyEvents: nsEvArray];
5124   [nsEvArray removeObject: theEvent];
5128 #ifdef NS_IMPL_COCOA
5129 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
5130    decided not to send key-down for.
5131    See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
5132    This only applies on Tiger and earlier.
5133    If it matches one of these, send it on to keyDown. */
5134 -(void)keyUp: (NSEvent *)theEvent
5136   int flags = [theEvent modifierFlags];
5137   int code = [theEvent keyCode];
5138   if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
5139       code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
5140     {
5141       if (NS_KEYLOG)
5142         fprintf (stderr, "keyUp: passed test");
5143       ns_fake_keydown = YES;
5144       [self keyDown: theEvent];
5145     }
5147 #endif
5150 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
5153 /* <NSTextInput>: called when done composing;
5154    NOTE: also called when we delete over working text, followed immed.
5155          by doCommandBySelector: deleteBackward: */
5156 - (void)insertText: (id)aString
5158   int code;
5159   int len = [(NSString *)aString length];
5160   int i;
5162   if (NS_KEYLOG)
5163     NSLog (@"insertText '%@'\tlen = %d", aString, len);
5164   processingCompose = NO;
5166   if (!emacs_event)
5167     return;
5169   /* first, clear any working text */
5170   if (workingText != nil)
5171     [self deleteWorkingText];
5173   /* now insert the string as keystrokes */
5174   for (i =0; i<len; i++)
5175     {
5176       code = [aString characterAtIndex: i];
5177       /* TODO: still need this? */
5178       if (code == 0x2DC)
5179         code = '~'; /* 0x7E */
5180       if (code != 32) /* Space */
5181         emacs_event->modifiers = 0;
5182       emacs_event->kind
5183         = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5184       emacs_event->code = code;
5185       EV_TRAILER ((id)nil);
5186     }
5190 /* <NSTextInput>: inserts display of composing characters */
5191 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
5193   NSString *str = [aString respondsToSelector: @selector (string)] ?
5194     [aString string] : aString;
5195   if (NS_KEYLOG)
5196     NSLog (@"setMarkedText '%@' len =%d range %d from %d", str, [str length],
5197            selRange.length, selRange.location);
5199   if (workingText != nil)
5200     [self deleteWorkingText];
5201   if ([str length] == 0)
5202     return;
5204   if (!emacs_event)
5205     return;
5207   processingCompose = YES;
5208   workingText = [str copy];
5209   ns_working_text = build_string ([workingText UTF8String]);
5211   emacs_event->kind = NS_TEXT_EVENT;
5212   emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
5213   EV_TRAILER ((id)nil);
5217 /* delete display of composing characters [not in <NSTextInput>] */
5218 - (void)deleteWorkingText
5220   if (workingText == nil)
5221     return;
5222   if (NS_KEYLOG)
5223     NSLog(@"deleteWorkingText len =%d\n", [workingText length]);
5224   [workingText release];
5225   workingText = nil;
5226   processingCompose = NO;
5228   if (!emacs_event)
5229     return;
5231   emacs_event->kind = NS_TEXT_EVENT;
5232   emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
5233   EV_TRAILER ((id)nil);
5237 - (BOOL)hasMarkedText
5239   return workingText != nil;
5243 - (NSRange)markedRange
5245   NSRange rng = workingText != nil
5246     ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
5247   if (NS_KEYLOG)
5248     NSLog (@"markedRange request");
5249   return rng;
5253 - (void)unmarkText
5255   if (NS_KEYLOG)
5256     NSLog (@"unmark (accept) text");
5257   [self deleteWorkingText];
5258   processingCompose = NO;
5262 /* used to position char selection windows, etc. */
5263 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
5265   NSRect rect;
5266   NSPoint pt;
5267   struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
5268   if (NS_KEYLOG)
5269     NSLog (@"firstRectForCharRange request");
5271   rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
5272   rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
5273   pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
5274   pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
5275                                        +FRAME_LINE_HEIGHT (emacsframe));
5277   pt = [self convertPoint: pt toView: nil];
5278   pt = [[self window] convertBaseToScreen: pt];
5279   rect.origin = pt;
5280   return rect;
5284 - (NSInteger)conversationIdentifier
5286   return (NSInteger)self;
5290 - (void)doCommandBySelector: (SEL)aSelector
5292   if (NS_KEYLOG)
5293     NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
5295   processingCompose = NO;
5296   if (aSelector == @selector (deleteBackward:))
5297     {
5298       /* happens when user backspaces over an ongoing composition:
5299          throw a 'delete' into the event queue */
5300       if (!emacs_event)
5301         return;
5302       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5303       emacs_event->code = 0xFF08;
5304       EV_TRAILER ((id)nil);
5305     }
5308 - (NSArray *)validAttributesForMarkedText
5310   static NSArray *arr = nil;
5311   if (arr == nil) arr = [NSArray new];
5312  /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
5313   return arr;
5316 - (NSRange)selectedRange
5318   if (NS_KEYLOG)
5319     NSLog (@"selectedRange request");
5320   return NSMakeRange (NSNotFound, 0);
5323 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
5325   if (NS_KEYLOG)
5326     NSLog (@"characterIndexForPoint request");
5327   return 0;
5330 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
5332   static NSAttributedString *str = nil;
5333   if (str == nil) str = [NSAttributedString new];
5334   if (NS_KEYLOG)
5335     NSLog (@"attributedSubstringFromRange request");
5336   return str;
5339 /* End <NSTextInput> impl. */
5340 /*****************************************************************************/
5343 /* This is what happens when the user presses a mouse button.  */
5344 - (void)mouseDown: (NSEvent *)theEvent
5346   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5348   NSTRACE (mouseDown);
5350   [self deleteWorkingText];
5352   if (!emacs_event)
5353     return;
5355   last_mouse_frame = emacsframe;
5356   /* appears to be needed to prevent spurious movement events generated on
5357      button clicks */
5358   last_mouse_frame->mouse_moved = 0;
5360   if ([theEvent type] == NSScrollWheel)
5361     {
5362       float delta = [theEvent deltaY];
5363       /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
5364       if (delta == 0)
5365         return;
5366       emacs_event->kind = WHEEL_EVENT;
5367       emacs_event->code = 0;
5368       emacs_event->modifiers = EV_MODIFIERS (theEvent) |
5369         ((delta > 0) ? up_modifier : down_modifier);
5370     }
5371   else
5372     {
5373       emacs_event->kind = MOUSE_CLICK_EVENT;
5374       emacs_event->code = EV_BUTTON (theEvent);
5375       emacs_event->modifiers = EV_MODIFIERS (theEvent)
5376                              | EV_UDMODIFIERS (theEvent);
5377     }
5378   XSETINT (emacs_event->x, lrint (p.x));
5379   XSETINT (emacs_event->y, lrint (p.y));
5380   EV_TRAILER (theEvent);
5384 - (void)rightMouseDown: (NSEvent *)theEvent
5386   NSTRACE (rightMouseDown);
5387   [self mouseDown: theEvent];
5391 - (void)otherMouseDown: (NSEvent *)theEvent
5393   NSTRACE (otherMouseDown);
5394   [self mouseDown: theEvent];
5398 - (void)mouseUp: (NSEvent *)theEvent
5400   NSTRACE (mouseUp);
5401   [self mouseDown: theEvent];
5405 - (void)rightMouseUp: (NSEvent *)theEvent
5407   NSTRACE (rightMouseUp);
5408   [self mouseDown: theEvent];
5412 - (void)otherMouseUp: (NSEvent *)theEvent
5414   NSTRACE (otherMouseUp);
5415   [self mouseDown: theEvent];
5419 - (void) scrollWheel: (NSEvent *)theEvent
5421   NSTRACE (scrollWheel);
5422   [self mouseDown: theEvent];
5426 /* Tell emacs the mouse has moved. */
5427 - (void)mouseMoved: (NSEvent *)e
5429   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5430   Lisp_Object frame;
5432 //  NSTRACE (mouseMoved);
5434   last_mouse_movement_time = EV_TIMESTAMP (e);
5435   last_mouse_motion_position
5436     = [self convertPoint: [e locationInWindow] fromView: nil];
5438   /* update any mouse face */
5439   if (hlinfo->mouse_face_hidden)
5440     {
5441       hlinfo->mouse_face_hidden = 0;
5442       clear_mouse_face (hlinfo);
5443     }
5445   /* tooltip handling */
5446   previous_help_echo_string = help_echo_string;
5447   help_echo_string = Qnil;
5449   if (!note_mouse_movement (emacsframe, last_mouse_motion_position.x,
5450                             last_mouse_motion_position.y))
5451     help_echo_string = previous_help_echo_string;
5453   XSETFRAME (frame, emacsframe);
5454   if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
5455     {
5456       /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
5457          (note_mouse_highlight), which is called through the
5458          note_mouse_movement () call above */
5459       gen_help_event (help_echo_string, frame, help_echo_window,
5460                       help_echo_object, help_echo_pos);
5461     }
5462   else
5463     {
5464       help_echo_string = Qnil;
5465       gen_help_event (Qnil, frame, Qnil, Qnil, 0);
5466     }
5468   if (emacsframe->mouse_moved && send_appdefined)
5469     ns_send_appdefined (-1);
5473 - (void)mouseDragged: (NSEvent *)e
5475   NSTRACE (mouseDragged);
5476   [self mouseMoved: e];
5480 - (void)rightMouseDragged: (NSEvent *)e
5482   NSTRACE (rightMouseDragged);
5483   [self mouseMoved: e];
5487 - (void)otherMouseDragged: (NSEvent *)e
5489   NSTRACE (otherMouseDragged);
5490   [self mouseMoved: e];
5494 - (BOOL)windowShouldClose: (id)sender
5496   NSEvent *e =[[self window] currentEvent];
5498   NSTRACE (windowShouldClose);
5499   windowClosing = YES;
5500   if (!emacs_event)
5501     return NO;
5502   emacs_event->kind = DELETE_WINDOW_EVENT;
5503   emacs_event->modifiers = 0;
5504   emacs_event->code = 0;
5505   EV_TRAILER (e);
5506   /* Don't close this window, let this be done from lisp code.  */
5507   return NO;
5510 - (void) updateFrameSize: (BOOL) delay;
5512   NSWindow *window = [self window];
5513   NSRect wr = [window frame];
5514   int extra = 0;
5515   int gsextra = 0;
5516 #ifdef NS_IMPL_GNUSTEP
5517   gsextra = 3;
5518 #endif
5520   int oldc = cols, oldr = rows;
5521   int oldw = FRAME_PIXEL_WIDTH (emacsframe),
5522     oldh = FRAME_PIXEL_HEIGHT (emacsframe);
5523   int neww, newh;
5525   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, wr.size.width + gsextra);
5527   if (cols < MINWIDTH)
5528     cols = MINWIDTH;
5530   if (! [self isFullscreen])
5531     {
5532       extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5533         + FRAME_TOOLBAR_HEIGHT (emacsframe) - gsextra;
5534     }
5536   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, wr.size.height - extra);
5538   if (rows < MINHEIGHT)
5539     rows = MINHEIGHT;
5541   neww = (int)wr.size.width - emacsframe->border_width;
5542   newh = (int)wr.size.height - extra;
5544   if (oldr != rows || oldc != cols || neww != oldw || newh != oldh)
5545     {
5546       struct frame *f = emacsframe;
5547       NSView *view = FRAME_NS_VIEW (emacsframe);
5548       NSWindow *win = [view window];
5549       NSSize sz = [win resizeIncrements];
5551       FRAME_PIXEL_WIDTH (emacsframe) = neww;
5552       FRAME_PIXEL_HEIGHT (emacsframe) = newh;
5553       change_frame_size (emacsframe, rows, cols, 0, delay, 0);
5554       SET_FRAME_GARBAGED (emacsframe);
5555       cancel_mouse_face (emacsframe);
5557       // Did resize increments change because of a font change?
5558       if (sz.width != FRAME_COLUMN_WIDTH (emacsframe) ||
5559           sz.height != FRAME_LINE_HEIGHT (emacsframe))
5560         {
5561           sz.width = FRAME_COLUMN_WIDTH (emacsframe);
5562           sz.height = FRAME_LINE_HEIGHT (emacsframe);
5563           [win setResizeIncrements: sz];
5564         }
5566       [view setFrame: NSMakeRect (0, 0, neww, newh)];
5567       [self windowDidMove:nil];   // Update top/left.
5568     }
5571 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
5572 /* normalize frame to gridded text size */
5574   int extra = 0;
5575   int gsextra = 0;
5576 #ifdef NS_IMPL_GNUSTEP
5577   gsextra = 3;
5578 #endif
5579   
5580   NSTRACE (windowWillResize);
5581 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
5583   if (fs_state == FULLSCREEN_MAXIMIZED
5584       && (maximized_width != (int)frameSize.width
5585           || maximized_height != (int)frameSize.height))
5586     [self setFSValue: FULLSCREEN_NONE];
5587   else if (fs_state == FULLSCREEN_WIDTH
5588            && maximized_width != (int)frameSize.width)
5589     [self setFSValue: FULLSCREEN_NONE];
5590   else if (fs_state == FULLSCREEN_HEIGHT
5591            && maximized_height != (int)frameSize.height)
5592     [self setFSValue: FULLSCREEN_NONE];
5593   if (fs_state == FULLSCREEN_NONE)
5594     maximized_width = maximized_height = -1;
5596   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe,
5597                                          frameSize.width + gsextra);
5598   if (cols < MINWIDTH)
5599     cols = MINWIDTH;
5601   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe,
5602                                            frameSize.height - extra);
5603   if (rows < MINHEIGHT)
5604     rows = MINHEIGHT;
5605 #ifdef NS_IMPL_COCOA
5606   {
5607     /* this sets window title to have size in it; the wm does this under GS */
5608     NSRect r = [[self window] frame];
5609     if (r.size.height == frameSize.height && r.size.width == frameSize.width)
5610       {
5611         if (old_title != 0)
5612           {
5613             xfree (old_title);
5614             old_title = 0;
5615           }
5616       }
5617     else
5618       {
5619         char *size_title;
5620         NSWindow *window = [self window];
5621         if (old_title == 0)
5622           {
5623             const char *t = [[[self window] title] UTF8String];
5624             char *pos = strstr (t, "  â€”  ");
5625             if (pos)
5626               *pos = '\0';
5627             old_title = xstrdup (t);
5628           }
5629         size_title = xmalloc (strlen (old_title) + 40);
5630         esprintf (size_title, "%s  â€”  (%d x %d)", old_title, cols, rows);
5631         [window setTitle: [NSString stringWithUTF8String: size_title]];
5632         [window display];
5633         xfree (size_title);
5634       }
5635   }
5636 #endif /* NS_IMPL_COCOA */
5637 /*fprintf (stderr,"    ...size became %.0f x %.0f  (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
5639   return frameSize;
5643 - (void)windowDidResize: (NSNotification *)notification
5645   if (! [self fsIsNative]) 
5646     {
5647       NSWindow *theWindow = [notification object];
5648       /* We can get notification on the non-FS window when in
5649          fullscreen mode.  */
5650       if ([self window] != theWindow) return;
5651     }
5653 #ifdef NS_IMPL_GNUSTEP
5654   NSWindow *theWindow = [notification object];
5656    /* In GNUstep, at least currently, it's possible to get a didResize
5657       without getting a willResize.. therefore we need to act as if we got
5658       the willResize now */
5659   NSSize sz = [theWindow frame].size;
5660   sz = [self windowWillResize: theWindow toSize: sz];
5661 #endif /* NS_IMPL_GNUSTEP */
5663   NSTRACE (windowDidResize);
5664 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
5666 #ifdef NS_IMPL_COCOA
5667   if (old_title != 0)
5668     {
5669       xfree (old_title);
5670       old_title = 0;
5671     }
5672 #endif /* NS_IMPL_COCOA */
5674   if (cols > 0 && rows > 0)
5675     {
5676       [self updateFrameSize: YES];
5677     }
5679   ns_send_appdefined (-1);
5683 - (void)windowDidBecomeKey: (NSNotification *)notification
5684 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5686   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5687   struct frame *old_focus = dpyinfo->x_focus_frame;
5689   NSTRACE (windowDidBecomeKey);
5691   if (emacsframe != old_focus)
5692     dpyinfo->x_focus_frame = emacsframe;
5694   ns_frame_rehighlight (emacsframe);
5696   if (emacs_event)
5697     {
5698       emacs_event->kind = FOCUS_IN_EVENT;
5699       EV_TRAILER ((id)nil);
5700     }
5704 - (void)windowDidResignKey: (NSNotification *)notification
5705 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5707   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5708   NSTRACE (windowDidResignKey);
5710   if (dpyinfo->x_focus_frame == emacsframe)
5711     dpyinfo->x_focus_frame = 0;
5713   ns_frame_rehighlight (emacsframe);
5715   /* FIXME: for some reason needed on second and subsequent clicks away
5716             from sole-frame Emacs to get hollow box to show */
5717   if (!windowClosing && [[self window] isVisible] == YES)
5718     {
5719       x_update_cursor (emacsframe, 1);
5720       x_set_frame_alpha (emacsframe);
5721     }
5723   if (emacs_event)
5724     {
5725       [self deleteWorkingText];
5726       emacs_event->kind = FOCUS_IN_EVENT;
5727       EV_TRAILER ((id)nil);
5728     }
5732 - (void)windowWillMiniaturize: sender
5734   NSTRACE (windowWillMiniaturize);
5738 - (BOOL)isFlipped
5740   return YES;
5744 - (BOOL)isOpaque
5746   return NO;
5750 - initFrameFromEmacs: (struct frame *)f
5752   NSRect r, wr;
5753   Lisp_Object tem;
5754   NSWindow *win;
5755   NSButton *toggleButton;
5756   NSSize sz;
5757   NSColor *col;
5758   NSString *name;
5760   NSTRACE (initFrameFromEmacs);
5762   windowClosing = NO;
5763   processingCompose = NO;
5764   scrollbarsNeedingUpdate = 0;
5765   fs_state = FULLSCREEN_NONE;
5766   fs_before_fs = next_maximized = -1;
5767 #ifdef HAVE_NATIVE_FS
5768   fs_is_native = ns_use_native_fullscreen;
5769 #else
5770   fs_is_native = NO;
5771 #endif
5772   maximized_width = maximized_height = -1;
5773   nonfs_window = nil;
5775 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
5777   ns_userRect = NSMakeRect (0, 0, 0, 0);
5778   r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
5779                  FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
5780   [self initWithFrame: r];
5781   [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
5783   FRAME_NS_VIEW (f) = self;
5784   emacsframe = f;
5785   old_title = 0;
5787   win = [[EmacsWindow alloc]
5788             initWithContentRect: r
5789                       styleMask: (NSResizableWindowMask |
5790 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
5791                                   NSTitledWindowMask |
5792 #endif
5793                                   NSMiniaturizableWindowMask |
5794                                   NSClosableWindowMask)
5795                         backing: NSBackingStoreBuffered
5796                           defer: YES];
5798 #ifdef HAVE_NATIVE_FS
5799     [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
5800 #endif
5802   wr = [win frame];
5803   bwidth = f->border_width = wr.size.width - r.size.width;
5804   tibar_height = FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
5806   [win setAcceptsMouseMovedEvents: YES];
5807   [win setDelegate: self];
5808   [win useOptimizedDrawing: YES];
5810   sz.width = FRAME_COLUMN_WIDTH (f);
5811   sz.height = FRAME_LINE_HEIGHT (f);
5812   [win setResizeIncrements: sz];
5814   [[win contentView] addSubview: self];
5816   if (ns_drag_types)
5817     [self registerForDraggedTypes: ns_drag_types];
5819   tem = f->name;
5820   name = [NSString stringWithUTF8String:
5821                    NILP (tem) ? "Emacs" : SSDATA (tem)];
5822   [win setTitle: name];
5824   /* toolbar support */
5825   toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
5826                          [NSString stringWithFormat: @"Emacs Frame %d",
5827                                    ns_window_num]];
5828   [win setToolbar: toolbar];
5829   [toolbar setVisible: NO];
5830 #ifdef NS_IMPL_COCOA
5831   toggleButton = [win standardWindowButton: NSWindowToolbarButton];
5832   [toggleButton setTarget: self];
5833   [toggleButton setAction: @selector (toggleToolbar: )];
5834 #endif
5835   FRAME_TOOLBAR_HEIGHT (f) = 0;
5837   tem = f->icon_name;
5838   if (!NILP (tem))
5839     [win setMiniwindowTitle:
5840            [NSString stringWithUTF8String: SSDATA (tem)]];
5842   {
5843     NSScreen *screen = [win screen];
5845     if (screen != 0)
5846       [win setFrameTopLeftPoint: NSMakePoint
5847            (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
5848             IN_BOUND (-SCREENMAX,
5849                      [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
5850   }
5852   [win makeFirstResponder: self];
5854   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5855                                   (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
5856   [win setBackgroundColor: col];
5857   if ([col alphaComponent] != 1.0)
5858     [win setOpaque: NO];
5860   [self allocateGState];
5862   [NSApp registerServicesMenuSendTypes: ns_send_types
5863                            returnTypes: nil];
5865   ns_window_num++;
5866   return self;
5870 - (void)windowDidMove: sender
5872   NSWindow *win = [self window];
5873   NSRect r = [win frame];
5874   NSArray *screens = [NSScreen screens];
5875   NSScreen *screen = [screens objectAtIndex: 0];
5877   NSTRACE (windowDidMove);
5879   if (!emacsframe->output_data.ns)
5880     return;
5881   if (screen != nil)
5882     {
5883       emacsframe->left_pos = r.origin.x;
5884       emacsframe->top_pos =
5885         [screen frame].size.height - (r.origin.y + r.size.height);
5886     }
5890 /* Called AFTER method below, but before our windowWillResize call there leads
5891    to windowDidResize -> x_set_window_size.  Update emacs' notion of frame
5892    location so set_window_size moves the frame. */
5893 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
5895   emacsframe->output_data.ns->zooming = 1;
5896   return YES;
5900 /* Override to do something slightly nonstandard, but nice.  First click on
5901    zoom button will zoom vertically.  Second will zoom completely.  Third
5902    returns to original. */
5903 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
5904                         defaultFrame:(NSRect)defaultFrame
5906   NSRect result = [sender frame];
5908   NSTRACE (windowWillUseStandardFrame);
5910   if (fs_before_fs != -1) /* Entering fullscreen */
5911       {
5912         result = defaultFrame;
5913       }
5914   else if (next_maximized == FULLSCREEN_HEIGHT
5915       || (next_maximized == -1
5916           && abs (defaultFrame.size.height - result.size.height)
5917           > FRAME_LINE_HEIGHT (emacsframe)))
5918     {
5919       /* first click */
5920       ns_userRect = result;
5921       maximized_height = result.size.height = defaultFrame.size.height;
5922       maximized_width = -1;
5923       result.origin.y = defaultFrame.origin.y;
5924       [self setFSValue: FULLSCREEN_HEIGHT];
5925     }
5926   else if (next_maximized == FULLSCREEN_WIDTH)
5927     {
5928       ns_userRect = result;
5929       maximized_width = result.size.width = defaultFrame.size.width;
5930       maximized_height = -1;
5931       result.origin.x = defaultFrame.origin.x;
5932       [self setFSValue: FULLSCREEN_WIDTH];
5933     }
5934   else if (next_maximized == FULLSCREEN_MAXIMIZED
5935            || (next_maximized == -1
5936                && abs (defaultFrame.size.width - result.size.width)
5937                > FRAME_COLUMN_WIDTH (emacsframe)))
5938     {
5939       result = defaultFrame;  /* second click */
5940       maximized_width = result.size.width;
5941       maximized_height = result.size.height;
5942       [self setFSValue: FULLSCREEN_MAXIMIZED];
5943     }
5944   else
5945     {
5946       /* restore */
5947       result = ns_userRect.size.height ? ns_userRect : result;
5948       ns_userRect = NSMakeRect (0, 0, 0, 0);
5949       [self setFSValue: FULLSCREEN_NONE];
5950       maximized_width = maximized_width = -1;
5951     }
5953   if (fs_before_fs == -1) next_maximized = -1;
5954   [self windowWillResize: sender toSize: result.size];
5955   return result;
5959 - (void)windowDidDeminiaturize: sender
5961   NSTRACE (windowDidDeminiaturize);
5962   if (!emacsframe->output_data.ns)
5963     return;
5965   SET_FRAME_ICONIFIED (emacsframe, 0);
5966   SET_FRAME_VISIBLE (emacsframe, 1);
5967   windows_or_buffers_changed++;
5969   if (emacs_event)
5970     {
5971       emacs_event->kind = DEICONIFY_EVENT;
5972       EV_TRAILER ((id)nil);
5973     }
5977 - (void)windowDidExpose: sender
5979   NSTRACE (windowDidExpose);
5980   if (!emacsframe->output_data.ns)
5981     return;
5983   SET_FRAME_VISIBLE (emacsframe, 1);
5984   SET_FRAME_GARBAGED (emacsframe);
5986   if (send_appdefined)
5987     ns_send_appdefined (-1);
5991 - (void)windowDidMiniaturize: sender
5993   NSTRACE (windowDidMiniaturize);
5994   if (!emacsframe->output_data.ns)
5995     return;
5997   SET_FRAME_ICONIFIED (emacsframe, 1);
5998   SET_FRAME_VISIBLE (emacsframe, 0);
6000   if (emacs_event)
6001     {
6002       emacs_event->kind = ICONIFY_EVENT;
6003       EV_TRAILER ((id)nil);
6004     }
6007 #ifdef HAVE_NATIVE_FS
6008 - (NSApplicationPresentationOptions)window:(NSWindow *)window
6009       willUseFullScreenPresentationOptions:
6010   (NSApplicationPresentationOptions)proposedOptions
6012   return proposedOptions|NSApplicationPresentationAutoHideToolbar;
6014 #endif
6016 - (void)windowWillEnterFullScreen:(NSNotification *)notification
6018   fs_before_fs = fs_state;
6021 - (void)windowDidEnterFullScreen:(NSNotification *)notification
6023   [self setFSValue: FULLSCREEN_BOTH];
6024   if (! [self fsIsNative])
6025     {
6026       [self windowDidBecomeKey:notification];
6027       [nonfs_window orderOut:self];
6028     }
6029   else if (! FRAME_EXTERNAL_TOOL_BAR (emacsframe))
6030     [toolbar setVisible:NO];
6033 - (void)windowWillExitFullScreen:(NSNotification *)notification
6035   if (next_maximized != -1)
6036     fs_before_fs = next_maximized;
6039 - (void)windowDidExitFullScreen:(NSNotification *)notification
6041   [self setFSValue: fs_before_fs];
6042   fs_before_fs = -1;
6043   [self updateCollectionBehaviour];
6044   if (FRAME_EXTERNAL_TOOL_BAR (emacsframe))
6045     {
6046       [toolbar setVisible:YES];
6047       update_frame_tool_bar (emacsframe);
6048       [self updateFrameSize:YES];
6049       [[self window] display];
6050     }
6051   else
6052     [toolbar setVisible:NO];
6054   if (next_maximized != -1)
6055     [[self window] performZoom:self];
6058 - (BOOL)fsIsNative
6060   return fs_is_native;
6063 - (BOOL)isFullscreen
6065   if (! fs_is_native) return nonfs_window != nil;
6066 #ifdef HAVE_NATIVE_FS
6067   return ([[self window] styleMask] & NSFullScreenWindowMask) != 0;
6068 #else
6069   return NO;
6070 #endif
6073 #ifdef HAVE_NATIVE_FS
6074 - (void)updateCollectionBehaviour
6076   if (! [self isFullscreen])
6077     {
6078       NSWindow *win = [self window];
6079       NSWindowCollectionBehavior b = [win collectionBehavior];
6080       if (ns_use_native_fullscreen)
6081         b |= NSWindowCollectionBehaviorFullScreenPrimary;
6082       else
6083         b &= ~NSWindowCollectionBehaviorFullScreenPrimary;
6085       [win setCollectionBehavior: b];
6086       fs_is_native = ns_use_native_fullscreen;
6087     }
6089 #endif
6091 - (void)toggleFullScreen: (id)sender
6093   NSWindow *w, *fw;
6094   BOOL onFirstScreen;
6095   struct frame *f;
6096   NSSize sz;
6097   NSRect r, wr;
6098   NSColor *col;
6100   if (fs_is_native)
6101     {
6102       [[self window] toggleFullScreen:sender];
6103       return;
6104     }
6106   w = [self window];
6107   onFirstScreen = [[w screen] isEqual:[[NSScreen screens] objectAtIndex:0]];
6108   f = emacsframe;
6109   wr = [w frame];
6110   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6111                                  (FRAME_DEFAULT_FACE (f)),
6112                                  f);
6114   sz.width = FRAME_COLUMN_WIDTH (f);
6115   sz.height = FRAME_LINE_HEIGHT (f);
6117   if (fs_state != FULLSCREEN_BOTH)
6118     {
6119       /* Hide dock and menubar if we are on the primary screen.  */
6120       if (onFirstScreen)
6121         {
6122 #if defined (NS_IMPL_COCOA) && \
6123   MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
6124           NSApplicationPresentationOptions options
6125             = NSApplicationPresentationAutoHideDock
6126             | NSApplicationPresentationAutoHideMenuBar;
6128           [NSApp setPresentationOptions: options];
6129 #else
6130           [NSMenu setMenuBarVisible:NO];
6131 #endif
6132         }
6134       fw = [[EmacsFSWindow alloc]
6135                        initWithContentRect:[w contentRectForFrameRect:wr]
6136                                  styleMask:NSBorderlessWindowMask
6137                                    backing:NSBackingStoreBuffered
6138                                      defer:YES
6139                                     screen:[w screen]];
6141       [fw setContentView:[w contentView]];
6142       [fw setTitle:[w title]];
6143       [fw setDelegate:self];
6144       [fw setAcceptsMouseMovedEvents: YES];
6145       [fw useOptimizedDrawing: YES];
6146       [fw setResizeIncrements: sz];
6147       [fw setBackgroundColor: col];
6148       if ([col alphaComponent] != 1.0)
6149         [fw setOpaque: NO];
6151       f->border_width = 0;
6152       FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
6153       tobar_height = FRAME_TOOLBAR_HEIGHT (f);
6154       FRAME_TOOLBAR_HEIGHT (f) = 0;
6156       nonfs_window = w;
6158       [self windowWillEnterFullScreen:nil];
6159       [fw makeKeyAndOrderFront:NSApp];
6160       [fw makeFirstResponder:self];
6161       [w orderOut:self];
6162       r = [fw frameRectForContentRect:[[fw screen] frame]];
6163       [fw setFrame: r display:YES animate:YES];
6164       [self windowDidEnterFullScreen:nil];
6165       [fw display];
6166     }
6167   else
6168     {
6169       fw = w;
6170       w = nonfs_window;
6171       nonfs_window = nil;
6173       if (onFirstScreen)
6174         {
6175 #if defined (NS_IMPL_COCOA) && \
6176   MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
6177           [NSApp setPresentationOptions: NSApplicationPresentationDefault];
6178 #else
6179           [NSMenu setMenuBarVisible:YES];
6180 #endif
6181         }
6183       [w setContentView:[fw contentView]];
6184       [w setResizeIncrements: sz];
6185       [w setBackgroundColor: col];
6186       if ([col alphaComponent] != 1.0)
6187         [w setOpaque: NO];
6189       f->border_width = bwidth;
6190       FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
6191       if (FRAME_EXTERNAL_TOOL_BAR (f))
6192         FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
6194       [self windowWillExitFullScreen:nil];
6195       [fw setFrame: [w frame] display:YES animate:YES];
6196       [fw close];
6197       [w makeKeyAndOrderFront:NSApp];
6198       [self windowDidExitFullScreen:nil];
6199       [self updateFrameSize:YES];
6200     }
6203 - (void)handleFS
6205   if (fs_state != emacsframe->want_fullscreen)
6206     {
6207       if (fs_state == FULLSCREEN_BOTH)
6208         {
6209           [self toggleFullScreen:self];
6210         }
6212       switch (emacsframe->want_fullscreen)
6213         {
6214         case FULLSCREEN_BOTH:
6215           [self toggleFullScreen:self];
6216           break;
6217         case FULLSCREEN_WIDTH:
6218           next_maximized = FULLSCREEN_WIDTH;
6219           if (fs_state != FULLSCREEN_BOTH)
6220             [[self window] performZoom:self];
6221           break;
6222         case FULLSCREEN_HEIGHT:
6223           next_maximized = FULLSCREEN_HEIGHT;
6224           if (fs_state != FULLSCREEN_BOTH)
6225             [[self window] performZoom:self];
6226           break;
6227         case FULLSCREEN_MAXIMIZED:
6228           next_maximized = FULLSCREEN_MAXIMIZED;
6229           if (fs_state != FULLSCREEN_BOTH)
6230             [[self window] performZoom:self];
6231           break;
6232         case FULLSCREEN_NONE:
6233           if (fs_state != FULLSCREEN_BOTH)
6234             {
6235               next_maximized = FULLSCREEN_NONE;
6236               [[self window] performZoom:self];
6237             }
6238           break;
6239         }
6241       emacsframe->want_fullscreen = FULLSCREEN_NONE;
6242     }
6246 - (void) setFSValue: (int)value
6248   Lisp_Object lval = Qnil;
6249   switch (value)
6250     {
6251     case FULLSCREEN_BOTH:
6252       lval = Qfullboth;
6253       break;
6254     case FULLSCREEN_WIDTH:
6255       lval = Qfullwidth;
6256       break;
6257     case FULLSCREEN_HEIGHT:
6258       lval = Qfullheight;
6259       break;
6260     case FULLSCREEN_MAXIMIZED:
6261       lval = Qmaximized;
6262       break;
6263     }
6264   store_frame_param (emacsframe, Qfullscreen, lval);
6265   fs_state = value;
6268 - (void)mouseEntered: (NSEvent *)theEvent
6270   NSTRACE (mouseEntered);
6271   last_mouse_movement_time = EV_TIMESTAMP (theEvent);
6275 - (void)mouseExited: (NSEvent *)theEvent
6277   Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
6279   NSTRACE (mouseExited);
6281   if (!hlinfo)
6282     return;
6284   last_mouse_movement_time = EV_TIMESTAMP (theEvent);
6286   if (emacsframe == hlinfo->mouse_face_mouse_frame)
6287     {
6288       clear_mouse_face (hlinfo);
6289       hlinfo->mouse_face_mouse_frame = 0;
6290     }
6294 - menuDown: sender
6296   NSTRACE (menuDown);
6297   if (context_menu_value == -1)
6298     context_menu_value = [sender tag];
6299   else
6300     {
6301       NSInteger tag = [sender tag];
6302       find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
6303                                     emacsframe->menu_bar_vector,
6304                                     (void *)tag);
6305     }
6307   ns_send_appdefined (-1);
6308   return self;
6312 - (EmacsToolbar *)toolbar
6314   return toolbar;
6318 /* this gets called on toolbar button click */
6319 - toolbarClicked: (id)item
6321   NSEvent *theEvent;
6322   int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
6324   NSTRACE (toolbarClicked);
6326   if (!emacs_event)
6327     return self;
6329   /* send first event (for some reason two needed) */
6330   theEvent = [[self window] currentEvent];
6331   emacs_event->kind = TOOL_BAR_EVENT;
6332   XSETFRAME (emacs_event->arg, emacsframe);
6333   EV_TRAILER (theEvent);
6335   emacs_event->kind = TOOL_BAR_EVENT;
6336 /*   XSETINT (emacs_event->code, 0); */
6337   emacs_event->arg = AREF (emacsframe->tool_bar_items,
6338                            idx + TOOL_BAR_ITEM_KEY);
6339   emacs_event->modifiers = EV_MODIFIERS (theEvent);
6340   EV_TRAILER (theEvent);
6341   return self;
6345 - toggleToolbar: (id)sender
6347   if (!emacs_event)
6348     return self;
6350   emacs_event->kind = NS_NONKEY_EVENT;
6351   emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
6352   EV_TRAILER ((id)nil);
6353   return self;
6357 - (void)drawRect: (NSRect)rect
6359   int x = NSMinX (rect), y = NSMinY (rect);
6360   int width = NSWidth (rect), height = NSHeight (rect);
6362   NSTRACE (drawRect);
6364   if (!emacsframe || !emacsframe->output_data.ns)
6365     return;
6367   ns_clear_frame_area (emacsframe, x, y, width, height);
6368   expose_frame (emacsframe, x, y, width, height);
6370   /*
6371     drawRect: may be called (at least in OS X 10.5) for invisible
6372     views as well for some reason.  Thus, do not infer visibility
6373     here.
6375     emacsframe->async_visible = 1;
6376     emacsframe->async_iconified = 0;
6377   */
6381 /* NSDraggingDestination protocol methods.  Actually this is not really a
6382    protocol, but a category of Object.  O well...  */
6384 -(NSUInteger) draggingEntered: (id <NSDraggingInfo>) sender
6386   NSTRACE (draggingEntered);
6387   return NSDragOperationGeneric;
6391 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
6393   return YES;
6397 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
6399   id pb;
6400   int x, y;
6401   NSString *type;
6402   NSEvent *theEvent = [[self window] currentEvent];
6403   NSPoint position;
6405   NSTRACE (performDragOperation);
6407   if (!emacs_event)
6408     return NO;
6410   position = [self convertPoint: [sender draggingLocation] fromView: nil];
6411   x = lrint (position.x);  y = lrint (position.y);
6413   pb = [sender draggingPasteboard];
6414   type = [pb availableTypeFromArray: ns_drag_types];
6415   if (type == 0)
6416     {
6417       return NO;
6418     }
6419   else if ([type isEqualToString: NSFilenamesPboardType])
6420     {
6421       NSArray *files;
6422       NSEnumerator *fenum;
6423       NSString *file;
6425       if (!(files = [pb propertyListForType: type]))
6426         return NO;
6428       fenum = [files objectEnumerator];
6429       while ( (file = [fenum nextObject]) )
6430         {
6431           emacs_event->kind = NS_NONKEY_EVENT;
6432           emacs_event->code = KEY_NS_DRAG_FILE;
6433           XSETINT (emacs_event->x, x);
6434           XSETINT (emacs_event->y, y);
6435           ns_input_file = append2 (ns_input_file,
6436                                    build_string ([file UTF8String]));
6437           emacs_event->modifiers = EV_MODIFIERS (theEvent);
6438           EV_TRAILER (theEvent);
6439         }
6440       return YES;
6441     }
6442   else if ([type isEqualToString: NSURLPboardType])
6443     {
6444       NSString *file;
6445       NSURL *fileURL;
6447       if (!(fileURL = [NSURL URLFromPasteboard: pb]) ||
6448           [fileURL isFileURL] == NO)
6449         return NO;
6451       file = [fileURL path];
6452       emacs_event->kind = NS_NONKEY_EVENT;
6453       emacs_event->code = KEY_NS_DRAG_FILE;
6454       XSETINT (emacs_event->x, x);
6455       XSETINT (emacs_event->y, y);
6456       ns_input_file = append2 (ns_input_file, build_string ([file UTF8String]));
6457       emacs_event->modifiers = EV_MODIFIERS (theEvent);
6458       EV_TRAILER (theEvent);
6459       return YES;
6460     }
6461   else if ([type isEqualToString: NSStringPboardType]
6462            || [type isEqualToString: NSTabularTextPboardType])
6463     {
6464       NSString *data;
6466       if (! (data = [pb stringForType: type]))
6467         return NO;
6469       emacs_event->kind = NS_NONKEY_EVENT;
6470       emacs_event->code = KEY_NS_DRAG_TEXT;
6471       XSETINT (emacs_event->x, x);
6472       XSETINT (emacs_event->y, y);
6473       ns_input_text = build_string ([data UTF8String]);
6474       emacs_event->modifiers = EV_MODIFIERS (theEvent);
6475       EV_TRAILER (theEvent);
6476       return YES;
6477     }
6478   else if ([type isEqualToString: NSColorPboardType])
6479     {
6480       NSColor *c = [NSColor colorFromPasteboard: pb];
6481       emacs_event->kind = NS_NONKEY_EVENT;
6482       emacs_event->code = KEY_NS_DRAG_COLOR;
6483       XSETINT (emacs_event->x, x);
6484       XSETINT (emacs_event->y, y);
6485       ns_input_color = ns_color_to_lisp (c);
6486       emacs_event->modifiers = EV_MODIFIERS (theEvent);
6487       EV_TRAILER (theEvent);
6488       return YES;
6489     }
6490   else if ([type isEqualToString: NSFontPboardType])
6491     {
6492       /* impl based on GNUstep NSTextView.m */
6493       NSData *data = [pb dataForType: NSFontPboardType];
6494       NSDictionary *dict = [NSUnarchiver unarchiveObjectWithData: data];
6495       NSFont *font = [dict objectForKey: NSFontAttributeName];
6496       char fontSize[10];
6498       if (font == nil)
6499         return NO;
6501       emacs_event->kind = NS_NONKEY_EVENT;
6502       emacs_event->code = KEY_NS_CHANGE_FONT;
6503       XSETINT (emacs_event->x, x);
6504       XSETINT (emacs_event->y, y);
6505       ns_input_font = build_string ([[font fontName] UTF8String]);
6506       snprintf (fontSize, 10, "%f", [font pointSize]);
6507       ns_input_fontsize = build_string (fontSize);
6508       emacs_event->modifiers = EV_MODIFIERS (theEvent);
6509       EV_TRAILER (theEvent);
6510       return YES;
6511     }
6512   else
6513     {
6514       error ("Invalid data type in dragging pasteboard.");
6515       return NO;
6516     }
6520 - (id) validRequestorForSendType: (NSString *)typeSent
6521                       returnType: (NSString *)typeReturned
6523   NSTRACE (validRequestorForSendType);
6524   if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
6525       && typeReturned == nil)
6526     {
6527       if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
6528         return self;
6529     }
6531   return [super validRequestorForSendType: typeSent
6532                                returnType: typeReturned];
6536 /* The next two methods are part of NSServicesRequests informal protocol,
6537    supposedly called when a services menu item is chosen from this app.
6538    But this should not happen because we override the services menu with our
6539    own entries which call ns-perform-service.
6540    Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
6541    So let's at least stub them out until further investigation can be done. */
6543 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
6545   /* we could call ns_string_from_pasteboard(pboard) here but then it should
6546      be written into the buffer in place of the existing selection..
6547      ordinary service calls go through functions defined in ns-win.el */
6548   return NO;
6551 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
6553   NSArray *typesDeclared;
6554   Lisp_Object val;
6556   /* We only support NSStringPboardType */
6557   if ([types containsObject:NSStringPboardType] == NO) {
6558     return NO;
6559   }
6561   val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
6562   if (CONSP (val) && SYMBOLP (XCAR (val)))
6563     {
6564       val = XCDR (val);
6565       if (CONSP (val) && NILP (XCDR (val)))
6566         val = XCAR (val);
6567     }
6568   if (! STRINGP (val))
6569     return NO;
6571   typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
6572   [pb declareTypes:typesDeclared owner:nil];
6573   ns_string_to_pasteboard (pb, val);
6574   return YES;
6578 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
6579    (gives a miniaturized version of the window); currently we use the latter for
6580    frames whose active buffer doesn't correspond to any file
6581    (e.g., '*scratch*') */
6582 - setMiniwindowImage: (BOOL) setMini
6584   id image = [[self window] miniwindowImage];
6585   NSTRACE (setMiniwindowImage);
6587   /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
6588      about "AppleDockIconEnabled" notwithstanding, however the set message
6589      below has its effect nonetheless. */
6590   if (image != emacsframe->output_data.ns->miniimage)
6591     {
6592       if (image && [image isKindOfClass: [EmacsImage class]])
6593         [image release];
6594       [[self window] setMiniwindowImage:
6595                        setMini ? emacsframe->output_data.ns->miniimage : nil];
6596     }
6598   return self;
6602 - (void) setRows: (int) r andColumns: (int) c
6604   rows = r;
6605   cols = c;
6608 @end  /* EmacsView */
6612 /* ==========================================================================
6614     EmacsWindow implementation
6616    ========================================================================== */
6618 @implementation EmacsWindow
6620 #ifdef NS_IMPL_COCOA
6621 - (id)accessibilityAttributeValue:(NSString *)attribute
6623   Lisp_Object str = Qnil;
6624   struct frame *f = SELECTED_FRAME ();
6625   struct buffer *curbuf = XBUFFER (XWINDOW (f->selected_window)->contents);
6627   if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
6628     return NSAccessibilityTextFieldRole;
6630   if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]
6631       && curbuf && ! NILP (BVAR (curbuf, mark_active)))
6632     {
6633       str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
6634     }
6635   else if (curbuf && [attribute isEqualToString:NSAccessibilityValueAttribute])
6636     {
6637       if (! NILP (BVAR (curbuf, mark_active)))
6638           str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
6640       if (NILP (str))
6641         {
6642           ptrdiff_t start_byte = BUF_BEGV_BYTE (curbuf);
6643           ptrdiff_t byte_range = BUF_ZV_BYTE (curbuf) - start_byte;
6644           ptrdiff_t range = BUF_ZV (curbuf) - BUF_BEGV (curbuf);
6646           if (! NILP (BVAR (curbuf, enable_multibyte_characters)))
6647             str = make_uninit_multibyte_string (range, byte_range);
6648           else
6649             str = make_uninit_string (range);
6650           /* To check: This returns emacs-utf-8, which is a superset of utf-8.
6651              Is this a problem?  */
6652           memcpy (SDATA (str), BYTE_POS_ADDR (start_byte), byte_range);
6653         }
6654     }
6657   if (! NILP (str))
6658     {
6659       if (CONSP (str) && SYMBOLP (XCAR (str)))
6660         {
6661           str = XCDR (str);
6662           if (CONSP (str) && NILP (XCDR (str)))
6663             str = XCAR (str);
6664         }
6665       if (STRINGP (str))
6666         {
6667           const char *utfStr = SSDATA (str);
6668           NSString *nsStr = [NSString stringWithUTF8String: utfStr];
6669           return nsStr;
6670         }
6671     }
6673   return [super accessibilityAttributeValue:attribute];
6675 #endif /* NS_IMPL_COCOA */
6677 /* If we have multiple monitors, one above the other, we don't want to
6678    restrict the height to just one monitor.  So we override this.  */
6679 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
6681   /* When making the frame visible for the first time or if there is just
6682      one screen, we want to constrain.  Other times not.  */
6683   NSUInteger nr_screens = [[NSScreen screens] count];
6684   struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
6685   NSTRACE (constrainFrameRect);
6687   if (nr_screens == 1)
6688     {
6689       NSRect r = [super constrainFrameRect:frameRect toScreen:screen];
6690       return r;
6691     }
6693   if (f->output_data.ns->dont_constrain
6694       || ns_menu_bar_should_be_hidden ())
6695     return frameRect;
6697   f->output_data.ns->dont_constrain = 1;
6698   return [super constrainFrameRect:frameRect toScreen:screen];
6701 @end /* EmacsWindow */
6704 @implementation EmacsFSWindow
6706 - (BOOL)canBecomeKeyWindow
6708   return YES;
6711 - (BOOL)canBecomeMainWindow
6713   return YES;
6716 @end
6718 /* ==========================================================================
6720     EmacsScroller implementation
6722    ========================================================================== */
6725 @implementation EmacsScroller
6727 /* for repeat button push */
6728 #define SCROLL_BAR_FIRST_DELAY 0.5
6729 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
6731 + (CGFloat) scrollerWidth
6733   /* TODO: if we want to allow variable widths, this is the place to do it,
6734            however neither GNUstep nor Cocoa support it very well */
6735   return [NSScroller scrollerWidth];
6739 - initFrame: (NSRect )r window: (Lisp_Object)nwin
6741   NSTRACE (EmacsScroller_initFrame);
6743   r.size.width = [EmacsScroller scrollerWidth];
6744   [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
6745   [self setContinuous: YES];
6746   [self setEnabled: YES];
6748   /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
6749      locked against the top and bottom edges, and right edge on OS X, where
6750      scrollers are on right. */
6751 #ifdef NS_IMPL_GNUSTEP
6752   [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
6753 #else
6754   [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
6755 #endif
6757   win = nwin;
6758   condemned = NO;
6759   pixel_height = NSHeight (r);
6760   if (pixel_height == 0) pixel_height = 1;
6761   min_portion = 20 / pixel_height;
6763   frame = XFRAME (XWINDOW (win)->frame);
6764   if (FRAME_LIVE_P (frame))
6765     {
6766       int i;
6767       EmacsView *view = FRAME_NS_VIEW (frame);
6768       NSView *sview = [[view window] contentView];
6769       NSArray *subs = [sview subviews];
6771       /* disable optimization stopping redraw of other scrollbars */
6772       view->scrollbarsNeedingUpdate = 0;
6773       for (i =[subs count]-1; i >= 0; i--)
6774         if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
6775           view->scrollbarsNeedingUpdate++;
6776       [sview addSubview: self];
6777     }
6779 /*  [self setFrame: r]; */
6781   return self;
6785 - (void)setFrame: (NSRect)newRect
6787   NSTRACE (EmacsScroller_setFrame);
6788 /*  block_input (); */
6789   pixel_height = NSHeight (newRect);
6790   if (pixel_height == 0) pixel_height = 1;
6791   min_portion = 20 / pixel_height;
6792   [super setFrame: newRect];
6793   [self display];
6794 /*  unblock_input (); */
6798 - (void)dealloc
6800   NSTRACE (EmacsScroller_dealloc);
6801   if (!NILP (win))
6802     wset_vertical_scroll_bar (XWINDOW (win), Qnil);
6803   [super dealloc];
6807 - condemn
6809   NSTRACE (condemn);
6810   condemned =YES;
6811   return self;
6815 - reprieve
6817   NSTRACE (reprieve);
6818   condemned =NO;
6819   return self;
6823 - judge
6825   NSTRACE (judge);
6826   if (condemned)
6827     {
6828       EmacsView *view;
6829       block_input ();
6830       /* ensure other scrollbar updates after deletion */
6831       view = (EmacsView *)FRAME_NS_VIEW (frame);
6832       if (view != nil)
6833         view->scrollbarsNeedingUpdate++;
6834       [self removeFromSuperview];
6835       [self release];
6836       unblock_input ();
6837     }
6838   return self;
6842 - (void)resetCursorRects
6844   NSRect visible = [self visibleRect];
6845   NSTRACE (resetCursorRects);
6847   if (!NSIsEmptyRect (visible))
6848     [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
6849   [[NSCursor arrowCursor] setOnMouseEntered: YES];
6853 - (int) checkSamePosition: (int) position portion: (int) portion
6854                     whole: (int) whole
6856   return em_position ==position && em_portion ==portion && em_whole ==whole
6857     && portion != whole; /* needed for resize empty buf */
6861 - setPosition: (int)position portion: (int)portion whole: (int)whole
6863   NSTRACE (setPosition);
6865   em_position = position;
6866   em_portion = portion;
6867   em_whole = whole;
6869   if (portion >= whole)
6870     {
6871 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
6872       [self setKnobProportion: 1.0];
6873       [self setDoubleValue: 1.0];
6874 #else
6875       [self setFloatValue: 0.0 knobProportion: 1.0];
6876 #endif
6877     }
6878   else
6879     {
6880       float pos, por;
6881       portion = max ((float)whole*min_portion/pixel_height, portion);
6882       pos = (float)position / (whole - portion);
6883       por = (float)portion/whole;
6884 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
6885       [self setKnobProportion: por];
6886       [self setDoubleValue: pos];
6887 #else
6888       [self setFloatValue: pos knobProportion: por];
6889 #endif
6890     }
6892   /* Events may come here even if the event loop is not running.
6893      If we don't enter the event loop, the scroll bar will not update.
6894      So send SIGIO to ourselves.  */
6895   if (apploopnr == 0) raise (SIGIO);
6897   return self;
6900 /* FIXME: unused at moment (see ns_mouse_position) at the moment because
6901      drag events will go directly to the EmacsScroller.  Leaving in for now. */
6902 -(void)getMouseMotionPart: (int *)part window: (Lisp_Object *)window
6903                         x: (Lisp_Object *)x y: ( Lisp_Object *)y
6905   *part = last_hit_part;
6906   *window = win;
6907   XSETINT (*y, pixel_height);
6908   if ([self floatValue] > 0.999)
6909     XSETINT (*x, pixel_height);
6910   else
6911     XSETINT (*x, pixel_height * [self floatValue]);
6915 /* set up emacs_event */
6916 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
6918   if (!emacs_event)
6919     return;
6921   emacs_event->part = last_hit_part;
6922   emacs_event->code = 0;
6923   emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
6924   emacs_event->frame_or_window = win;
6925   emacs_event->timestamp = EV_TIMESTAMP (e);
6926   emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
6927   emacs_event->arg = Qnil;
6928   XSETINT (emacs_event->x, loc * pixel_height);
6929   XSETINT (emacs_event->y, pixel_height-20);
6931   if (q_event_ptr)
6932     {
6933       n_emacs_events_pending++;
6934       kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
6935     }
6936   else
6937     hold_event (emacs_event);
6938   EVENT_INIT (*emacs_event);
6939   ns_send_appdefined (-1);
6943 /* called manually thru timer to implement repeated button action w/hold-down */
6944 - repeatScroll: (NSTimer *)scrollEntry
6946   NSEvent *e = [[self window] currentEvent];
6947   NSPoint p =  [[self window] mouseLocationOutsideOfEventStream];
6948   BOOL inKnob = [self testPart: p] == NSScrollerKnob;
6950   /* clear timer if need be */
6951   if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
6952     {
6953         [scroll_repeat_entry invalidate];
6954         [scroll_repeat_entry release];
6955         scroll_repeat_entry = nil;
6957         if (inKnob)
6958           return self;
6960         scroll_repeat_entry
6961           = [[NSTimer scheduledTimerWithTimeInterval:
6962                         SCROLL_BAR_CONTINUOUS_DELAY
6963                                             target: self
6964                                           selector: @selector (repeatScroll:)
6965                                           userInfo: 0
6966                                            repeats: YES]
6967               retain];
6968     }
6970   [self sendScrollEventAtLoc: 0 fromEvent: e];
6971   return self;
6975 /* Asynchronous mouse tracking for scroller.  This allows us to dispatch
6976    mouseDragged events without going into a modal loop. */
6977 - (void)mouseDown: (NSEvent *)e
6979   NSRect sr, kr;
6980   /* hitPart is only updated AFTER event is passed on */
6981   NSScrollerPart part = [self testPart: [e locationInWindow]];
6982   double inc = 0.0, loc, kloc, pos;
6983   int edge = 0;
6985   NSTRACE (EmacsScroller_mouseDown);
6987   switch (part)
6988     {
6989     case NSScrollerDecrementPage:
6990         last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
6991     case NSScrollerIncrementPage:
6992         last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
6993     case NSScrollerDecrementLine:
6994       last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
6995     case NSScrollerIncrementLine:
6996       last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
6997     case NSScrollerKnob:
6998       last_hit_part = scroll_bar_handle; break;
6999     case NSScrollerKnobSlot:  /* GNUstep-only */
7000       last_hit_part = scroll_bar_move_ratio; break;
7001     default:  /* NSScrollerNoPart? */
7002       fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
7003                (long) part);
7004       return;
7005     }
7007   if (inc != 0.0)
7008     {
7009       pos = 0;      /* ignored */
7011       /* set a timer to repeat, as we can't let superclass do this modally */
7012       scroll_repeat_entry
7013         = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
7014                                             target: self
7015                                           selector: @selector (repeatScroll:)
7016                                           userInfo: 0
7017                                            repeats: YES]
7018             retain];
7019     }
7020   else
7021     {
7022       /* handle, or on GNUstep possibly slot */
7023       NSEvent *fake_event;
7025       /* compute float loc in slot and mouse offset on knob */
7026       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
7027                       toView: nil];
7028       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
7029       if (loc <= 0.0)
7030         {
7031           loc = 0.0;
7032           edge = -1;
7033         }
7034       else if (loc >= NSHeight (sr))
7035         {
7036           loc = NSHeight (sr);
7037           edge = 1;
7038         }
7040       if (edge)
7041         kloc = 0.5 * edge;
7042       else
7043         {
7044           kr = [self convertRect: [self rectForPart: NSScrollerKnob]
7045                           toView: nil];
7046           kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
7047         }
7048       last_mouse_offset = kloc;
7050       /* if knob, tell emacs a location offset by knob pos
7051          (to indicate top of handle) */
7052       if (part == NSScrollerKnob)
7053           pos = (loc - last_mouse_offset) / NSHeight (sr);
7054       else
7055         /* else this is a slot click on GNUstep: go straight there */
7056         pos = loc / NSHeight (sr);
7058       /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
7059       fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
7060                                       location: [e locationInWindow]
7061                                  modifierFlags: [e modifierFlags]
7062                                      timestamp: [e timestamp]
7063                                   windowNumber: [e windowNumber]
7064                                        context: [e context]
7065                                    eventNumber: [e eventNumber]
7066                                     clickCount: [e clickCount]
7067                                       pressure: [e pressure]];
7068       [super mouseUp: fake_event];
7069     }
7071   if (part != NSScrollerKnob)
7072     [self sendScrollEventAtLoc: pos fromEvent: e];
7076 /* Called as we manually track scroller drags, rather than superclass. */
7077 - (void)mouseDragged: (NSEvent *)e
7079     NSRect sr;
7080     double loc, pos;
7081     int edge = 0;
7083     NSTRACE (EmacsScroller_mouseDragged);
7085       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
7086                       toView: nil];
7087       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
7089       if (loc <= 0.0)
7090         {
7091           loc = 0.0;
7092           edge = -1;
7093         }
7094       else if (loc >= NSHeight (sr) + last_mouse_offset)
7095         {
7096           loc = NSHeight (sr) + last_mouse_offset;
7097           edge = 1;
7098         }
7100       pos = /*(edge ? loc :*/ (loc - last_mouse_offset) / NSHeight (sr);
7101       [self sendScrollEventAtLoc: pos fromEvent: e];
7105 - (void)mouseUp: (NSEvent *)e
7107   if (scroll_repeat_entry)
7108     {
7109       [scroll_repeat_entry invalidate];
7110       [scroll_repeat_entry release];
7111       scroll_repeat_entry = nil;
7112     }
7113   last_hit_part = 0;
7117 /* treat scrollwheel events in the bar as though they were in the main window */
7118 - (void) scrollWheel: (NSEvent *)theEvent
7120   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
7121   [view mouseDown: theEvent];
7124 @end  /* EmacsScroller */
7129 /* ==========================================================================
7131    Font-related functions; these used to be in nsfaces.m
7133    ========================================================================== */
7136 Lisp_Object
7137 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
7139   struct font *font = XFONT_OBJECT (font_object);
7141   if (fontset < 0)
7142     fontset = fontset_from_font (font_object);
7143   FRAME_FONTSET (f) = fontset;
7145   if (FRAME_FONT (f) == font)
7146     /* This font is already set in frame F.  There's nothing more to
7147        do.  */
7148     return font_object;
7150   FRAME_FONT (f) = font;
7152   FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
7153   FRAME_COLUMN_WIDTH (f) = font->average_width;
7154   FRAME_LINE_HEIGHT (f) = font->height;
7156   compute_fringe_widths (f, 1);
7158   /* Compute the scroll bar width in character columns.  */
7159   if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
7160     {
7161       int wid = FRAME_COLUMN_WIDTH (f);
7162       FRAME_CONFIG_SCROLL_BAR_COLS (f)
7163         = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
7164     }
7165   else
7166     {
7167       int wid = FRAME_COLUMN_WIDTH (f);
7168       FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
7169     }
7171   /* Now make the frame display the given font.  */
7172   if (FRAME_NS_WINDOW (f) != 0)
7173         x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
7175   return font_object;
7179 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
7180 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
7181          in 1.43. */
7183 const char *
7184 ns_xlfd_to_fontname (const char *xlfd)
7185 /* --------------------------------------------------------------------------
7186     Convert an X font name (XLFD) to an NS font name.
7187     Only family is used.
7188     The string returned is temporarily allocated.
7189    -------------------------------------------------------------------------- */
7191   char *name = xmalloc (180);
7192   int i, len;
7193   const char *ret;
7195   if (!strncmp (xlfd, "--", 2))
7196     sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
7197   else
7198     sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
7200   /* stopgap for malformed XLFD input */
7201   if (strlen (name) == 0)
7202     strcpy (name, "Monaco");
7204   /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
7205      also uppercase after '-' or ' ' */
7206   name[0] = c_toupper (name[0]);
7207   for (len =strlen (name), i =0; i<len; i++)
7208     {
7209       if (name[i] == '$')
7210         {
7211           name[i] = '-';
7212           if (i+1<len)
7213             name[i+1] = c_toupper (name[i+1]);
7214         }
7215       else if (name[i] == '_')
7216         {
7217           name[i] = ' ';
7218           if (i+1<len)
7219             name[i+1] = c_toupper (name[i+1]);
7220         }
7221     }
7222 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name);  */
7223   ret = [[NSString stringWithUTF8String: name] UTF8String];
7224   xfree (name);
7225   return ret;
7229 void
7230 syms_of_nsterm (void)
7232   NSTRACE (syms_of_nsterm);
7234   ns_antialias_threshold = 10.0;
7236   /* from 23+ we need to tell emacs what modifiers there are.. */
7237   DEFSYM (Qmodifier_value, "modifier-value");
7238   DEFSYM (Qalt, "alt");
7239   DEFSYM (Qhyper, "hyper");
7240   DEFSYM (Qmeta, "meta");
7241   DEFSYM (Qsuper, "super");
7242   DEFSYM (Qcontrol, "control");
7243   DEFSYM (QUTF8_STRING, "UTF8_STRING");
7245   Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
7246   Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
7247   Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
7248   Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
7249   Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
7251   DEFVAR_LISP ("ns-input-file", ns_input_file,
7252               "The file specified in the last NS event.");
7253   ns_input_file =Qnil;
7255   DEFVAR_LISP ("ns-input-text", ns_input_text,
7256               "The data received in the last NS text drag event.");
7257   ns_input_text =Qnil;
7259   DEFVAR_LISP ("ns-working-text", ns_working_text,
7260               "String for visualizing working composition sequence.");
7261   ns_working_text =Qnil;
7263   DEFVAR_LISP ("ns-input-font", ns_input_font,
7264               "The font specified in the last NS event.");
7265   ns_input_font =Qnil;
7267   DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
7268               "The fontsize specified in the last NS event.");
7269   ns_input_fontsize =Qnil;
7271   DEFVAR_LISP ("ns-input-line", ns_input_line,
7272                "The line specified in the last NS event.");
7273   ns_input_line =Qnil;
7275   DEFVAR_LISP ("ns-input-color", ns_input_color,
7276                "The color specified in the last NS event.");
7277   ns_input_color =Qnil;
7279   DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
7280                "The service name specified in the last NS event.");
7281   ns_input_spi_name =Qnil;
7283   DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
7284                "The service argument specified in the last NS event.");
7285   ns_input_spi_arg =Qnil;
7287   DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
7288                "This variable describes the behavior of the alternate or option key.\n\
7289 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7290 Set to none means that the alternate / option key is not interpreted by Emacs\n\
7291 at all, allowing it to be used at a lower level for accented character entry.");
7292   ns_alternate_modifier = Qmeta;
7294   DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
7295                "This variable describes the behavior of the right alternate or option key.\n\
7296 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7297 Set to left means be the same key as `ns-alternate-modifier'.\n\
7298 Set to none means that the alternate / option key is not interpreted by Emacs\n\
7299 at all, allowing it to be used at a lower level for accented character entry.");
7300   ns_right_alternate_modifier = Qleft;
7302   DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
7303                "This variable describes the behavior of the command key.\n\
7304 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
7305   ns_command_modifier = Qsuper;
7307   DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
7308                "This variable describes the behavior of the right command key.\n\
7309 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7310 Set to left means be the same key as `ns-command-modifier'.\n\
7311 Set to none means that the command / option key is not interpreted by Emacs\n\
7312 at all, allowing it to be used at a lower level for accented character entry.");
7313   ns_right_command_modifier = Qleft;
7315   DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
7316                "This variable describes the behavior of the control key.\n\
7317 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
7318   ns_control_modifier = Qcontrol;
7320   DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
7321                "This variable describes the behavior of the right control key.\n\
7322 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7323 Set to left means be the same key as `ns-control-modifier'.\n\
7324 Set to none means that the control / option key is not interpreted by Emacs\n\
7325 at all, allowing it to be used at a lower level for accented character entry.");
7326   ns_right_control_modifier = Qleft;
7328   DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
7329                "This variable describes the behavior of the function key (on laptops).\n\
7330 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7331 Set to none means that the function key is not interpreted by Emacs at all,\n\
7332 allowing it to be used at a lower level for accented character entry.");
7333   ns_function_modifier = Qnone;
7335   DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
7336                "Non-nil (the default) means to render text antialiased.");
7337   ns_antialias_text = Qt;
7339   DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
7340                "Whether to confirm application quit using dialog.");
7341   ns_confirm_quit = Qnil;
7343   staticpro (&ns_display_name_list);
7344   ns_display_name_list = Qnil;
7346   staticpro (&last_mouse_motion_frame);
7347   last_mouse_motion_frame = Qnil;
7349   DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
7350                doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
7351 Only works on OSX 10.6 or later.  */);
7352   ns_auto_hide_menu_bar = Qnil;
7354   DEFVAR_BOOL ("ns-use-native-fullscreen", ns_use_native_fullscreen,
7355      doc: /*Non-nil means to use native fullscreen on OSX >= 10.7.
7356 Nil means use fullscreen the old (< 10.7) way.  The old way works better with
7357 multiple monitors, but lacks tool bar.  This variable is ignored on OSX < 10.7.
7358 Default is t for OSX >= 10.7, nil otherwise. */);
7359 #ifdef HAVE_NATIVE_FS
7360   ns_use_native_fullscreen = YES;
7361 #else
7362   ns_use_native_fullscreen = NO;
7363 #endif
7364   ns_last_use_native_fullscreen = ns_use_native_fullscreen;
7366   /* TODO: move to common code */
7367   DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
7368                doc: /* Which toolkit scroll bars Emacs uses, if any.
7369 A value of nil means Emacs doesn't use toolkit scroll bars.
7370 With the X Window system, the value is a symbol describing the
7371 X toolkit.  Possible values are: gtk, motif, xaw, or xaw3d.
7372 With MS Windows or Nextstep, the value is t.  */);
7373   Vx_toolkit_scroll_bars = Qt;
7375   DEFVAR_BOOL ("x-use-underline-position-properties",
7376                x_use_underline_position_properties,
7377      doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
7378 A value of nil means ignore them.  If you encounter fonts with bogus
7379 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
7380 to 4.1, set this to nil. */);
7381   x_use_underline_position_properties = 0;
7383   DEFVAR_BOOL ("x-underline-at-descent-line",
7384                x_underline_at_descent_line,
7385      doc: /* Non-nil means to draw the underline at the same place as the descent line.
7386 A value of nil means to draw the underline according to the value of the
7387 variable `x-use-underline-position-properties', which is usually at the
7388 baseline level.  The default value is nil.  */);
7389   x_underline_at_descent_line = 0;
7391   /* Tell emacs about this window system. */
7392   Fprovide (intern ("ns"), Qnil);