Introduce ns-auto-hide-menu-bar to hide menubar for Emacs frames.
[emacs.git] / src / nsterm.m
blobebfa875ae0e690232745a950eb36ca83fcf5dd01
1 /* NeXT/Open/GNUstep / MacOSX communication module.
2    Copyright (C) 1989, 1993-1994, 2005-2006, 2008-2011
3      Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.  */
21 Originally by Carl Edman
22 Updated by Christian Limpach (chris@nice.ch)
23 OpenStep/Rhapsody port by Scott Bender (sbender@harmony-ds.com)
24 MacOSX/Aqua port by Christophe de Dinechin (descubes@earthlink.net)
25 GNUstep port and post-20 update by Adrian Robert (arobert@cogsci.ucsd.edu)
28 /* This should be the first include, as it may set up #defines affecting
29    interpretation of even the system includes. */
30 #include <config.h>
32 #include <math.h>
33 #include <sys/types.h>
34 #include <time.h>
35 #include <signal.h>
36 #include <unistd.h>
37 #include <setjmp.h>
39 #include "lisp.h"
40 #include "blockinput.h"
41 #include "sysselect.h"
42 #include "nsterm.h"
43 #include "systime.h"
44 #include "character.h"
45 #include "fontset.h"
46 #include "composite.h"
47 #include "ccl.h"
49 #include "termhooks.h"
50 #include "termopts.h"
51 #include "termchar.h"
53 #include "window.h"
54 #include "keyboard.h"
56 #include "font.h"
58 /* call tracing */
59 #if 0
60 int term_trace_num = 0;
61 #define NSTRACE(x)        fprintf (stderr, "%s:%d: [%d] " #x "\n",         \
62                                 __FILE__, __LINE__, ++term_trace_num)
63 #else
64 #define NSTRACE(x)
65 #endif
68 /* ==========================================================================
70     Local declarations
72    ========================================================================== */
74 /* Convert a symbol indexed with an NSxxx value to a value as defined
75    in keyboard.c (lispy_function_key). I hope this is a correct way
76    of doing things... */
77 static unsigned convert_ns_to_X_keysym[] =
79   NSHomeFunctionKey,            0x50,
80   NSLeftArrowFunctionKey,       0x51,
81   NSUpArrowFunctionKey,         0x52,
82   NSRightArrowFunctionKey,      0x53,
83   NSDownArrowFunctionKey,       0x54,
84   NSPageUpFunctionKey,          0x55,
85   NSPageDownFunctionKey,        0x56,
86   NSEndFunctionKey,             0x57,
87   NSBeginFunctionKey,           0x58,
88   NSSelectFunctionKey,          0x60,
89   NSPrintFunctionKey,           0x61,
90   NSExecuteFunctionKey,         0x62,
91   NSInsertFunctionKey,          0x63,
92   NSUndoFunctionKey,            0x65,
93   NSRedoFunctionKey,            0x66,
94   NSMenuFunctionKey,            0x67,
95   NSFindFunctionKey,            0x68,
96   NSHelpFunctionKey,            0x6A,
97   NSBreakFunctionKey,           0x6B,
99   NSF1FunctionKey,              0xBE,
100   NSF2FunctionKey,              0xBF,
101   NSF3FunctionKey,              0xC0,
102   NSF4FunctionKey,              0xC1,
103   NSF5FunctionKey,              0xC2,
104   NSF6FunctionKey,              0xC3,
105   NSF7FunctionKey,              0xC4,
106   NSF8FunctionKey,              0xC5,
107   NSF9FunctionKey,              0xC6,
108   NSF10FunctionKey,             0xC7,
109   NSF11FunctionKey,             0xC8,
110   NSF12FunctionKey,             0xC9,
111   NSF13FunctionKey,             0xCA,
112   NSF14FunctionKey,             0xCB,
113   NSF15FunctionKey,             0xCC,
114   NSF16FunctionKey,             0xCD,
115   NSF17FunctionKey,             0xCE,
116   NSF18FunctionKey,             0xCF,
117   NSF19FunctionKey,             0xD0,
118   NSF20FunctionKey,             0xD1,
119   NSF21FunctionKey,             0xD2,
120   NSF22FunctionKey,             0xD3,
121   NSF23FunctionKey,             0xD4,
122   NSF24FunctionKey,             0xD5,
124   NSBackspaceCharacter,         0x08,  /* 8: Not on some KBs. */
125   NSDeleteCharacter,            0xFF,  /* 127: Big 'delete' key upper right. */
126   NSDeleteFunctionKey,          0x9F,  /* 63272: Del forw key off main array. */
128   NSTabCharacter,               0x09,
129   0x19,                         0x09,  /* left tab->regular since pass shift */
130   NSCarriageReturnCharacter,    0x0D,
131   NSNewlineCharacter,           0x0D,
132   NSEnterCharacter,             0x8D,
134   0x1B,                         0x1B   /* escape */
138 static Lisp_Object Qmodifier_value;
139 Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper, Qnone;
140 extern Lisp_Object Qcursor_color, Qcursor_type, Qns, Qleft;
142 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
143    the maximum font size to NOT antialias.  On GNUstep there is currently
144    no way to control this behavior. */
145 float ns_antialias_threshold;
147 /* Used to pick up AppleHighlightColor on OS X */
148 NSString *ns_selection_color;
150 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
151 NSString *ns_app_name = @"Emacs";  /* default changed later */
153 /* Display variables */
154 struct ns_display_info *x_display_list; /* Chain of existing displays */
155 Lisp_Object ns_display_name_list;
156 long context_menu_value = 0;
158 /* display update */
159 NSPoint last_mouse_motion_position;
160 static NSRect last_mouse_glyph;
161 static unsigned long last_mouse_movement_time = 0;
162 static Lisp_Object last_mouse_motion_frame;
163 static EmacsScroller *last_mouse_scroll_bar = nil;
164 static struct frame *ns_updating_frame;
165 static NSView *focus_view = NULL;
166 static int ns_window_num =0;
167 static NSRect uRect;
168 static BOOL gsaved = NO;
169 BOOL ns_in_resize = NO;
170 static BOOL ns_fake_keydown = NO;
171 int ns_tmp_flags; /* FIXME */
172 struct nsfont_info *ns_tmp_font; /* FIXME */
173 static BOOL ns_menu_bar_is_hidden = NO;
174 /*static int debug_lock = 0; */
176 /* event loop */
177 static BOOL send_appdefined = YES;
178 static NSEvent *last_appdefined_event = 0;
179 static NSTimer *timed_entry = 0;
180 static NSTimer *fd_entry = nil;
181 static NSTimer *scroll_repeat_entry = nil;
182 static fd_set select_readfds, t_readfds;
183 static struct timeval select_timeout;
184 static int select_nfds;
185 static NSAutoreleasePool *outerpool;
186 static struct input_event *emacs_event = NULL;
187 static struct input_event *q_event_ptr = NULL;
188 static int n_emacs_events_pending = 0;
189 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
190   *ns_pending_service_args;
191 static BOOL inNsSelect = 0;
193 /* Convert modifiers in a NeXTstep event to emacs style modifiers.  */
194 #define NS_FUNCTION_KEY_MASK 0x800000
195 #define NSLeftControlKeyMask    (0x000001 | NSControlKeyMask)
196 #define NSRightControlKeyMask   (0x002000 | NSControlKeyMask)
197 #define NSLeftCommandKeyMask    (0x000008 | NSCommandKeyMask)
198 #define NSRightCommandKeyMask   (0x000010 | NSCommandKeyMask)
199 #define NSLeftAlternateKeyMask  (0x000020 | NSAlternateKeyMask)
200 #define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
201 #define EV_MODIFIERS(e)                               \
202     ((([e modifierFlags] & NSHelpKeyMask) ?           \
203            hyper_modifier : 0)                        \
204      | (!EQ (ns_right_alternate_modifier, Qleft) && \
205         (([e modifierFlags] & NSRightAlternateKeyMask) \
206          == NSRightAlternateKeyMask) ? \
207            parse_solitary_modifier (ns_right_alternate_modifier) : 0) \
208      | (([e modifierFlags] & NSAlternateKeyMask) ?                 \
209            parse_solitary_modifier (ns_alternate_modifier) : 0)   \
210      | (([e modifierFlags] & NSShiftKeyMask) ?     \
211            shift_modifier : 0)                        \
212      | (!EQ (ns_right_control_modifier, Qleft) && \
213         (([e modifierFlags] & NSRightControlKeyMask) \
214          == NSRightControlKeyMask) ? \
215            parse_solitary_modifier (ns_right_control_modifier) : 0) \
216      | (([e modifierFlags] & NSControlKeyMask) ?      \
217            parse_solitary_modifier (ns_control_modifier) : 0)     \
218      | (([e modifierFlags] & NS_FUNCTION_KEY_MASK) ?  \
219            parse_solitary_modifier (ns_function_modifier) : 0)    \
220      | (!EQ (ns_right_command_modifier, Qleft) && \
221         (([e modifierFlags] & NSRightCommandKeyMask) \
222          == NSRightCommandKeyMask) ? \
223            parse_solitary_modifier (ns_right_command_modifier) : 0) \
224      | (([e modifierFlags] & NSCommandKeyMask) ?      \
225            parse_solitary_modifier (ns_command_modifier):0))
227 #define EV_UDMODIFIERS(e)                                      \
228     ((([e type] == NSLeftMouseDown) ? down_modifier : 0)       \
229      | (([e type] == NSRightMouseDown) ? down_modifier : 0)    \
230      | (([e type] == NSOtherMouseDown) ? down_modifier : 0)    \
231      | (([e type] == NSLeftMouseDragged) ? down_modifier : 0)  \
232      | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
233      | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
234      | (([e type] == NSLeftMouseUp)   ? up_modifier   : 0)     \
235      | (([e type] == NSRightMouseUp)   ? up_modifier   : 0)    \
236      | (([e type] == NSOtherMouseUp)   ? up_modifier   : 0))
238 #define EV_BUTTON(e)                                                         \
239     ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 :    \
240       (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
241      [e buttonNumber] - 1)
243 /* Convert the time field to a timestamp in milliseconds. */
244 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
246 /* This is a piece of code which is common to all the event handling
247    methods.  Maybe it should even be a function.  */
248 #define EV_TRAILER(e)                                         \
249   {                                                           \
250   XSETFRAME (emacs_event->frame_or_window, emacsframe);       \
251   if (e) emacs_event->timestamp = EV_TIMESTAMP (e);           \
252   n_emacs_events_pending++;                                   \
253   kbd_buffer_store_event_hold (emacs_event, q_event_ptr);     \
254   EVENT_INIT (*emacs_event);                                  \
255   ns_send_appdefined (-1);                                    \
256   }
258 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
260 /* TODO: get rid of need for these forward declarations */
261 static void ns_condemn_scroll_bars (struct frame *f);
262 static void ns_judge_scroll_bars (struct frame *f);
263 void x_set_frame_alpha (struct frame *f);
265 /* FIXME: figure out what to do with underline_minimum_offset. */
268 /* ==========================================================================
270     Utilities
272    ========================================================================== */
275 static Lisp_Object
276 append2 (Lisp_Object list, Lisp_Object item)
277 /* --------------------------------------------------------------------------
278    Utility to append to a list
279    -------------------------------------------------------------------------- */
281   Lisp_Object array[2];
282   array[0] = list;
283   array[1] = Fcons (item, Qnil);
284   return Fnconc (2, &array[0]);
288 void
289 ns_init_paths (void)
290 /* --------------------------------------------------------------------------
291    Used to allow emacs to find its resources under Emacs.app
292    Called from emacs.c at startup.
293    -------------------------------------------------------------------------- */
295   NSBundle *bundle = [NSBundle mainBundle];
296   NSString *binDir = [bundle bundlePath], *resourceDir = [bundle resourcePath];
297   NSString *resourcePath, *resourcePaths;
298   NSRange range;
299   BOOL onWindows = NO; /* how do I determine this? */
300   NSString *pathSeparator = onWindows ? @";" : @":";
301   NSFileManager *fileManager = [NSFileManager defaultManager];
302   BOOL isDir;
303 /*NSLog (@"ns_init_paths: '%@'\n%@\n", [[NSBundle mainBundle] bundlePath], [[NSBundle mainBundle] resourcePath]); */
305   /* get bindir from base */
306   range = [resourceDir rangeOfString: @"Contents"];
307   if (range.location != NSNotFound)
308     {
309       binDir = [binDir stringByAppendingPathComponent: @"Contents"];
310 #ifdef NS_IMPL_COCOA
311       binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
312 #endif
313     }
315   /* the following based on Andrew Choi's init_mac_osx_environment () */
316   if (!getenv ("EMACSLOADPATH"))
317     {
318       NSArray *paths = [resourceDir stringsByAppendingPaths:
319                                   [NSArray arrayWithObjects:
320                                          @"site-lisp", @"lisp", @"leim", nil]];
321       NSEnumerator *pathEnum = [paths objectEnumerator];
322       resourcePaths = @"";
323       while (resourcePath = [pathEnum nextObject])
324         {
325           if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
326             if (isDir)
327               {
328                 if ([resourcePaths length] > 0)
329                   resourcePaths
330                     = [resourcePaths stringByAppendingString: pathSeparator];
331                 resourcePaths
332                   = [resourcePaths stringByAppendingString: resourcePath];
333               }
334         }
335       if ([resourcePaths length] > 0)
336         setenv ("EMACSLOADPATH", [resourcePaths UTF8String], 1);
337 /*NSLog (@"loadPath: '%@'\n", resourcePaths); */
338     }
340   if (!getenv ("EMACSPATH"))
341     {
342       NSArray *paths = [binDir stringsByAppendingPaths:
343                                   [NSArray arrayWithObjects: @"bin",
344                                                              @"lib-exec", nil]];
345       NSEnumerator *pathEnum = [paths objectEnumerator];
346       resourcePaths = @"";
347       while (resourcePath = [pathEnum nextObject])
348         {
349           if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
350             if (isDir)
351               {
352                 if ([resourcePaths length] > 0)
353                   resourcePaths
354                     = [resourcePaths stringByAppendingString: pathSeparator];
355                 resourcePaths
356                   = [resourcePaths stringByAppendingString: resourcePath];
357               }
358         }
359       if ([resourcePaths length] > 0)
360         setenv ("EMACSPATH", [resourcePaths UTF8String], 1);
361     }
363   resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
364   if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
365     {
366       if (isDir)
367         {
368           if (!getenv ("EMACSDATA"))
369             setenv ("EMACSDATA", [resourcePath UTF8String], 1);
370           if (!getenv ("EMACSDOC"))
371             setenv ("EMACSDOC", [resourcePath UTF8String], 1);
372         }
373     }
375   if (!getenv ("INFOPATH"))
376     {
377       resourcePath = [resourceDir stringByAppendingPathComponent: @"info"];
378       if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
379         if (isDir)
380           setenv ("INFOPATH", [[resourcePath stringByAppendingString: @":"]
381                                              UTF8String], 1);
382       /* Note, extra colon needed to cause merge w/later user additions. */
383     }
387 static int
388 timeval_subtract (struct timeval *result, struct timeval x, struct timeval y)
389 /* --------------------------------------------------------------------------
390    Subtract the `struct timeval' values X and Y, storing the result in RESULT.
391    Return 1 if the difference is negative, otherwise 0.
392    -------------------------------------------------------------------------- */
394   /* Perform the carry for the later subtraction by updating y.
395      This is safer because on some systems
396      the tv_sec member is unsigned.  */
397   if (x.tv_usec < y.tv_usec)
398     {
399       int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
400       y.tv_usec -= 1000000 * nsec;
401       y.tv_sec += nsec;
402     }
403   if (x.tv_usec - y.tv_usec > 1000000)
404     {
405       int nsec = (y.tv_usec - x.tv_usec) / 1000000;
406       y.tv_usec += 1000000 * nsec;
407       y.tv_sec -= nsec;
408     }
410   /* Compute the time remaining to wait.  tv_usec is certainly positive.  */
411   result->tv_sec = x.tv_sec - y.tv_sec;
412   result->tv_usec = x.tv_usec - y.tv_usec;
414   /* Return indication of whether the result should be considered negative.  */
415   return x.tv_sec < y.tv_sec;
418 static void
419 ns_timeout (int usecs)
420 /* --------------------------------------------------------------------------
421      Blocking timer utility used by ns_ring_bell
422    -------------------------------------------------------------------------- */
424   struct timeval wakeup;
426   EMACS_GET_TIME (wakeup);
428   /* Compute time to wait until, propagating carry from usecs.  */
429   wakeup.tv_usec += usecs;
430   wakeup.tv_sec += (wakeup.tv_usec / 1000000);
431   wakeup.tv_usec %= 1000000;
433   /* Keep waiting until past the time wakeup.  */
434   while (1)
435     {
436       struct timeval timeout;
438       EMACS_GET_TIME (timeout);
440       /* In effect, timeout = wakeup - timeout.
441          Break if result would be negative.  */
442       if (timeval_subtract (&timeout, wakeup, timeout))
443         break;
445       /* Try to wait that long--but we might wake up sooner.  */
446       select (0, NULL, NULL, NULL, &timeout);
447     }
451 void
452 ns_release_object (void *obj)
453 /* --------------------------------------------------------------------------
454     Release an object (callable from C)
455    -------------------------------------------------------------------------- */
457     [(id)obj release];
461 void
462 ns_retain_object (void *obj)
463 /* --------------------------------------------------------------------------
464     Retain an object (callable from C)
465    -------------------------------------------------------------------------- */
467     [(id)obj retain];
471 void *
472 ns_alloc_autorelease_pool (void)
473 /* --------------------------------------------------------------------------
474      Allocate a pool for temporary objects (callable from C)
475    -------------------------------------------------------------------------- */
477   return [[NSAutoreleasePool alloc] init];
481 void
482 ns_release_autorelease_pool (void *pool)
483 /* --------------------------------------------------------------------------
484      Free a pool and temporary objects it refers to (callable from C)
485    -------------------------------------------------------------------------- */
487   ns_release_object (pool);
492 /* ==========================================================================
494     Focus (clipping) and screen update
496    ========================================================================== */
498 static NSRect
499 ns_resize_handle_rect (NSWindow *window)
501   NSRect r = [window frame];
502   r.origin.x = r.size.width - RESIZE_HANDLE_SIZE;
503   r.origin.y = 0;
504   r.size.width = r.size.height = RESIZE_HANDLE_SIZE;
505   return r;
510 // Window constraining
511 // -------------------
513 // To ensure that the windows are not placed under the menu bar, they
514 // are typically moved by the call-back constrainFrameRect. However,
515 // by overriding it, it's possible to inhibit this, leaving the window
516 // in it's original position.
518 // It's possible to hide the menu bar. However, technically, it's only
519 // possible to hide it when the application is active. To ensure that
520 // this work properly, the menu bar and window constraining are
521 // deferred until the application becomes active.
523 // Even though it's not possible to manually move a window above the
524 // top of the screen, it is allowed if it's done programmatically,
525 // when the menu is hidden. This allows the editable area to cover the
526 // full screen height.
528 // Test cases
529 // ----------
531 // Use the following extra files:
533 //    init.el:
534 //       ;; Hide menu and place frame slightly above the top of the screen.
535 //       (setq ns-auto-hide-menu-bar t)
536 //       (set-frame-position (selected-frame) 0 -20)
538 // Test 1:
540 //    emacs -Q -l init.el
542 //    Result: No menu bar, and the title bar should be above the screen.
544 // Test 2:
546 //    emacs -Q
548 //    Result: Menu bar visible, frame placed immediately below the menu.
551 static void
552 ns_constrain_all_frames (void)
554   Lisp_Object tail, frame;
556   FOR_EACH_FRAME (tail, frame)
557     {
558       struct frame *f = XFRAME (frame);
559       if (FRAME_NS_P (f))
560         {
561           NSView *view = FRAME_NS_VIEW (f);
562           /* This no-op will trigger the default window placing
563            * constriant system. */
564           f->output_data.ns->dont_constrain = 0;
565           [[view window] setFrameOrigin:[[view window] frame].origin];
566         }
567     }
571 /* True, if the menu bar should be hidden.  */
573 static BOOL
574 ns_menu_bar_should_be_hidden (void)
576   return !NILP (ns_auto_hide_menu_bar)
577     && [NSApp respondsToSelector:@selector(setPresentationOptions:)];
581 /* Show or hide the menu bar, based on user setting.  */
583 static void
584 ns_update_auto_hide_menu_bar (void)
586   BLOCK_INPUT;
588   NSTRACE (ns_update_auto_hide_menu_bar);
590   if (NSApp != nil
591       && [NSApp isActive]
592       && [NSApp respondsToSelector:@selector(setPresentationOptions:)])
593     {
594       // Note, "setPresentationOptions" triggers an error unless the
595       // application is active.
596       BOOL menu_bar_should_be_hidden = ns_menu_bar_should_be_hidden ();
598       if (menu_bar_should_be_hidden != ns_menu_bar_is_hidden)
599         {
600           NSApplicationPresentationOptions options
601             = NSApplicationPresentationAutoHideDock;
603           if (menu_bar_should_be_hidden)
604             options |= NSApplicationPresentationAutoHideMenuBar;
606           [NSApp setPresentationOptions: options];
608           ns_menu_bar_is_hidden = menu_bar_should_be_hidden;
610           if (!ns_menu_bar_is_hidden)
611             {
612               ns_constrain_all_frames ();
613             }
614         }
615     }
617   UNBLOCK_INPUT;
621 static void
622 ns_update_begin (struct frame *f)
623 /* --------------------------------------------------------------------------
624    Prepare for a grouped sequence of drawing calls
625    external (RIF) call; whole frame, called before update_window_begin
626    -------------------------------------------------------------------------- */
628   NSView *view = FRAME_NS_VIEW (f);
629   NSTRACE (ns_update_begin);
631   ns_update_auto_hide_menu_bar ();
633   ns_updating_frame = f;
634   [view lockFocus];
636 #ifdef NS_IMPL_GNUSTEP
637   uRect = NSMakeRect (0, 0, 0, 0);
638 #endif
642 static void
643 ns_update_window_begin (struct window *w)
644 /* --------------------------------------------------------------------------
645    Prepare for a grouped sequence of drawing calls
646    external (RIF) call; for one window, called after update_begin
647    -------------------------------------------------------------------------- */
649   struct frame *f = XFRAME (WINDOW_FRAME (w));
650  Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
651   NSTRACE (ns_update_window_begin);
653   updated_window = w;
654   set_output_cursor (&w->cursor);
656   BLOCK_INPUT;
658   if (f == hlinfo->mouse_face_mouse_frame)
659     {
660       /* Don't do highlighting for mouse motion during the update.  */
661       hlinfo->mouse_face_defer = 1;
663         /* If the frame needs to be redrawn,
664            simply forget about any prior mouse highlighting.  */
665       if (FRAME_GARBAGED_P (f))
666         hlinfo->mouse_face_window = Qnil;
668       /* (further code for mouse faces ifdef'd out in other terms elided) */
669     }
671   UNBLOCK_INPUT;
675 static void
676 ns_update_window_end (struct window *w, int cursor_on_p,
677                       int mouse_face_overwritten_p)
678 /* --------------------------------------------------------------------------
679    Finished a grouped sequence of drawing calls
680    external (RIF) call; for one window called before update_end
681    -------------------------------------------------------------------------- */
683   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (XFRAME (w->frame));
685   /* note: this fn is nearly identical in all terms */
686   if (!w->pseudo_window_p)
687     {
688       BLOCK_INPUT;
690       if (cursor_on_p)
691         display_and_set_cursor (w, 1,
692                                 output_cursor.hpos, output_cursor.vpos,
693                                 output_cursor.x, output_cursor.y);
695       if (draw_window_fringes (w, 1))
696         x_draw_vertical_border (w);
698       UNBLOCK_INPUT;
699     }
701   /* If a row with mouse-face was overwritten, arrange for
702      frame_up_to_date to redisplay the mouse highlight.  */
703   if (mouse_face_overwritten_p)
704     {
705       hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
706       hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
707       hlinfo->mouse_face_window = Qnil;
708     }
710   updated_window = NULL;
711   NSTRACE (update_window_end);
715 static void
716 ns_update_end (struct frame *f)
717 /* --------------------------------------------------------------------------
718    Finished a grouped sequence of drawing calls
719    external (RIF) call; for whole frame, called after update_window_end
720    -------------------------------------------------------------------------- */
722   NSView *view = FRAME_NS_VIEW (f);
724 /*   if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
725     MOUSE_HL_INFO (f)->mouse_face_defer = 0;
727   BLOCK_INPUT;
729 #ifdef NS_IMPL_GNUSTEP
730   /* trigger flush only in the rectangle we tracked as being drawn */
731   [view unlockFocusNeedsFlush: NO];
732 /*fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", uRect.origin.x, uRect.origin.y, uRect.size.width, uRect.size.height); */
733   [view lockFocusInRect: uRect];
734 #endif
736   [view unlockFocus];
737   [[view window] flushWindow];
739   UNBLOCK_INPUT;
740   ns_updating_frame = NULL;
741   NSTRACE (ns_update_end);
745 static void
746 ns_flush (struct frame *f)
747 /* --------------------------------------------------------------------------
748    external (RIF) call
749    NS impl is no-op since currently we flush in ns_update_end and elsewhere
750    -------------------------------------------------------------------------- */
752     NSTRACE (ns_flush);
756 static void
757 ns_focus (struct frame *f, NSRect *r, int n)
758 /* --------------------------------------------------------------------------
759    Internal: Focus on given frame.  During small local updates this is used to
760      draw, however during large updates, ns_update_begin and ns_update_end are
761      called to wrap the whole thing, in which case these calls are stubbed out.
762      Except, on GNUstep, we accumulate the rectangle being drawn into, because
763      the back end won't do this automatically, and will just end up flushing
764      the entire window.
765    -------------------------------------------------------------------------- */
767 //  NSTRACE (ns_focus);
768 #ifdef NS_IMPL_GNUSTEP
769   NSRect u;
770     if (n == 2)
771       u = NSUnionRect (r[0], r[1]);
772     else if (r)
773       u = *r;
774 #endif
775 /* static int c =0;
776    fprintf (stderr, "focus: %d", c++);
777    if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
778    fprintf (stderr, "\n"); */
780   if (f != ns_updating_frame)
781     {
782       NSView *view = FRAME_NS_VIEW (f);
783       if (view != focus_view)
784         {
785           if (focus_view != NULL)
786             {
787               [focus_view unlockFocus];
788               [[focus_view window] flushWindow];
789 /*debug_lock--; */
790             }
792           if (view)
793 #ifdef NS_IMPL_GNUSTEP
794             r ? [view lockFocusInRect: u] : [view lockFocus];
795 #else
796             [view lockFocus];
797 #endif
798           focus_view = view;
799 /*if (view) debug_lock++; */
800         }
801 #ifdef NS_IMPL_GNUSTEP
802       else
803         {
804           /* more than one rect being drawn into */
805           if (view && r)
806             {
807               [view unlockFocus]; /* add prev rect to redraw list */
808               [view lockFocusInRect: u]; /* focus for draw in new rect */
809             }
810         }
811 #endif
812     }
813 #ifdef NS_IMPL_GNUSTEP
814   else
815     {
816       /* in batch mode, but in GNUstep must still track rectangles explicitly */
817       uRect = (r ? NSUnionRect (uRect, u) : [FRAME_NS_VIEW (f) visibleRect]);
818     }
819 #endif
821   /* clipping */
822   if (r)
823     {
824       [[NSGraphicsContext currentContext] saveGraphicsState];
825       if (n == 2)
826         NSRectClipList (r, 2);
827       else
828         NSRectClip (*r);
829       gsaved = YES;
830     }
834 static void
835 ns_unfocus (struct frame *f)
836 /* --------------------------------------------------------------------------
837      Internal: Remove focus on given frame
838    -------------------------------------------------------------------------- */
840 //  NSTRACE (ns_unfocus);
842   if (gsaved)
843     {
844       [[NSGraphicsContext currentContext] restoreGraphicsState];
845       gsaved = NO;
846     }
848   if (f != ns_updating_frame)
849     {
850       if (focus_view != NULL)
851         {
852           [focus_view unlockFocus];
853           [[focus_view window] flushWindow];
854           focus_view = NULL;
855 /*debug_lock--; */
856         }
857     }
861 static void
862 ns_clip_to_row (struct window *w, struct glyph_row *row, int area, BOOL gc)
863 /* --------------------------------------------------------------------------
864      Internal (but parallels other terms): Focus drawing on given row
865    -------------------------------------------------------------------------- */
867   struct frame *f = XFRAME (WINDOW_FRAME (w));
868   NSRect clip_rect;
869   int window_x, window_y, window_width;
871   window_box (w, area, &window_x, &window_y, &window_width, 0);
873   clip_rect.origin.x = window_x - FRAME_INTERNAL_BORDER_WIDTH (f);
874   clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
875   clip_rect.origin.y = max (clip_rect.origin.y, window_y);
876   clip_rect.size.width = window_width + 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
877   clip_rect.size.height = row->visible_height;
879   /* allow a full-height row at the top when requested
880      (used to draw fringe all the way through internal border area) */
881   if (gc && clip_rect.origin.y < 5)
882     {
883       clip_rect.origin.y -= FRAME_INTERNAL_BORDER_WIDTH (f);
884       clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
885     }
887   /* likewise at bottom */
888   if (gc &&
889       FRAME_PIXEL_HEIGHT (f) - (clip_rect.origin.y + clip_rect.size.height) < 5)
890     clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
892   ns_focus (f, &clip_rect, 1);
896 static void
897 ns_ring_bell (struct frame *f)
898 /* --------------------------------------------------------------------------
899      "Beep" routine
900    -------------------------------------------------------------------------- */
902   NSTRACE (ns_ring_bell);
903   if (visible_bell)
904     {
905       NSAutoreleasePool *pool;
906       struct frame *frame = SELECTED_FRAME ();
907       NSView *view;
909       BLOCK_INPUT;
910       pool = [[NSAutoreleasePool alloc] init];
912       view = FRAME_NS_VIEW (frame);
913       if (view != nil)
914         {
915           NSRect r, surr;
916           NSPoint dim = NSMakePoint (128, 128);
918           r = [view bounds];
919           r.origin.x += (r.size.width - dim.x) / 2;
920           r.origin.y += (r.size.height - dim.y) / 2;
921           r.size.width = dim.x;
922           r.size.height = dim.y;
923           surr = NSInsetRect (r, -2, -2);
924           ns_focus (frame, &surr, 1);
925           [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
926           [ns_lookup_indexed_color (NS_FACE_FOREGROUND
927                                       (FRAME_DEFAULT_FACE (frame)), frame) set];
928           NSRectFill (r);
929           [[view window] flushWindow];
930           ns_timeout (150000);
931           [[view window] restoreCachedImage];
932           [[view window] flushWindow];
933           ns_unfocus (frame);
934         }
935       [pool release];
936       UNBLOCK_INPUT;
937     }
938   else
939     {
940       NSBeep ();
941     }
945 static void
946 ns_reset_terminal_modes (struct terminal *terminal)
947 /*  Externally called as hook */
949   NSTRACE (ns_reset_terminal_modes);
953 static void
954 ns_set_terminal_modes (struct terminal *terminal)
955 /*  Externally called as hook */
957   NSTRACE (ns_set_terminal_modes);
962 /* ==========================================================================
964     Frame / window manager related functions
966    ========================================================================== */
969 static void
970 ns_raise_frame (struct frame *f)
971 /* --------------------------------------------------------------------------
972      Bring window to foreground and make it active
973    -------------------------------------------------------------------------- */
975   NSView *view = FRAME_NS_VIEW (f);
976   check_ns ();
977   BLOCK_INPUT;
978   FRAME_SAMPLE_VISIBILITY (f);
979   if (FRAME_VISIBLE_P (f))
980     {
981       [[view window] makeKeyAndOrderFront: NSApp];
982     }
983   UNBLOCK_INPUT;
987 static void
988 ns_lower_frame (struct frame *f)
989 /* --------------------------------------------------------------------------
990      Send window to back
991    -------------------------------------------------------------------------- */
993   NSView *view = FRAME_NS_VIEW (f);
994   check_ns ();
995   BLOCK_INPUT;
996   [[view window] orderBack: NSApp];
997   UNBLOCK_INPUT;
1001 static void
1002 ns_frame_raise_lower (struct frame *f, int raise)
1003 /* --------------------------------------------------------------------------
1004      External (hook)
1005    -------------------------------------------------------------------------- */
1007   NSTRACE (ns_frame_raise_lower);
1009   if (raise)
1010     ns_raise_frame (f);
1011   else
1012     ns_lower_frame (f);
1016 static void
1017 ns_frame_rehighlight (struct frame *frame)
1018 /* --------------------------------------------------------------------------
1019      External (hook): called on things like window switching within frame
1020    -------------------------------------------------------------------------- */
1022   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
1023   struct frame *old_highlight = dpyinfo->x_highlight_frame;
1025   NSTRACE (ns_frame_rehighlight);
1026   if (dpyinfo->x_focus_frame)
1027     {
1028       dpyinfo->x_highlight_frame
1029         = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1030            ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1031            : dpyinfo->x_focus_frame);
1032       if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
1033         {
1034           FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
1035           dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
1036         }
1037     }
1038   else
1039       dpyinfo->x_highlight_frame = 0;
1041   if (dpyinfo->x_highlight_frame &&
1042          dpyinfo->x_highlight_frame != old_highlight)
1043     {
1044       if (old_highlight)
1045         {
1046           x_update_cursor (old_highlight, 1);
1047           x_set_frame_alpha (old_highlight);
1048         }
1049       if (dpyinfo->x_highlight_frame)
1050         {
1051           x_update_cursor (dpyinfo->x_highlight_frame, 1);
1052           x_set_frame_alpha (dpyinfo->x_highlight_frame);
1053         }
1054     }
1058 void
1059 x_make_frame_visible (struct frame *f)
1060 /* --------------------------------------------------------------------------
1061      External: Show the window (X11 semantics)
1062    -------------------------------------------------------------------------- */
1064   NSTRACE (x_make_frame_visible);
1065   /* XXX: at some points in past this was not needed, as the only place that
1066      called this (frame.c:Fraise_frame ()) also called raise_lower;
1067      if this ends up the case again, comment this out again. */
1068   if (!FRAME_VISIBLE_P (f))
1069     {
1070       f->async_visible = 1;
1071       ns_raise_frame (f);
1072     }
1076 void
1077 x_make_frame_invisible (struct frame *f)
1078 /* --------------------------------------------------------------------------
1079      External: Hide the window (X11 semantics)
1080    -------------------------------------------------------------------------- */
1082   NSView * view = FRAME_NS_VIEW (f);
1083   NSTRACE (x_make_frame_invisible);
1084   check_ns ();
1085   [[view window] orderOut: NSApp];
1086   f->async_visible = 0;
1087   f->async_iconified = 0;
1091 void
1092 x_iconify_frame (struct frame *f)
1093 /* --------------------------------------------------------------------------
1094      External: Iconify window
1095    -------------------------------------------------------------------------- */
1097   NSView * view = FRAME_NS_VIEW (f);
1098   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1099   NSTRACE (x_iconify_frame);
1100   check_ns ();
1102   if (dpyinfo->x_highlight_frame == f)
1103     dpyinfo->x_highlight_frame = 0;
1105   if ([[view window] windowNumber] <= 0)
1106     {
1107       /* the window is still deferred.  Make it very small, bring it
1108          on screen and order it out. */
1109       NSRect s = { { 100, 100}, {0, 0} };
1110       NSRect t;
1111       t = [[view window] frame];
1112       [[view window] setFrame: s display: NO];
1113       [[view window] orderBack: NSApp];
1114       [[view window] orderOut: NSApp];
1115       [[view window] setFrame: t display: NO];
1116     }
1117   [[view window] miniaturize: NSApp];
1121 void
1122 x_destroy_window (struct frame *f)
1123 /* --------------------------------------------------------------------------
1124      External: Delete the window
1125    -------------------------------------------------------------------------- */
1127   NSView *view = FRAME_NS_VIEW (f);
1128   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1129   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1130   NSTRACE (x_destroy_window);
1131   check_ns ();
1133   [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1135   BLOCK_INPUT;
1137   free_frame_menubar (f);
1139   if (FRAME_FACE_CACHE (f))
1140     free_frame_faces (f);
1142   if (f == dpyinfo->x_focus_frame)
1143     dpyinfo->x_focus_frame = 0;
1144   if (f == dpyinfo->x_highlight_frame)
1145     dpyinfo->x_highlight_frame = 0;
1146   if (f == hlinfo->mouse_face_mouse_frame)
1147     {
1148       hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
1149       hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
1150       hlinfo->mouse_face_window = Qnil;
1151       hlinfo->mouse_face_deferred_gc = 0;
1152       hlinfo->mouse_face_mouse_frame = 0;
1153     }
1155   xfree (f->output_data.ns);
1157   [[view window] close];
1158   [view release];
1160   ns_window_num--;
1161   UNBLOCK_INPUT;
1165 void
1166 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1167 /* --------------------------------------------------------------------------
1168      External: Position the window
1169    -------------------------------------------------------------------------- */
1171   NSView *view = FRAME_NS_VIEW (f);
1172   NSArray *screens = [NSScreen screens];
1173   NSScreen *fscreen = [screens objectAtIndex: 0];
1174   NSScreen *screen = [[view window] screen];
1176   NSTRACE (x_set_offset);
1178   BLOCK_INPUT;
1180   f->left_pos = xoff;
1181   f->top_pos = yoff;
1183   if (view != nil && screen && fscreen)
1184     {
1185       f->left_pos = f->size_hint_flags & XNegative
1186         ? [screen visibleFrame].size.width + f->left_pos - FRAME_PIXEL_WIDTH (f)
1187         : f->left_pos;
1188       /* We use visibleFrame here to take menu bar into account.
1189          Ideally we should also adjust left/top with visibleFrame.origin.  */
1191       f->top_pos = f->size_hint_flags & YNegative
1192         ? ([screen visibleFrame].size.height + f->top_pos
1193            - FRAME_PIXEL_HEIGHT (f) - FRAME_NS_TITLEBAR_HEIGHT (f)
1194            - FRAME_TOOLBAR_HEIGHT (f))
1195         : f->top_pos;
1196 #ifdef NS_IMPL_GNUSTEP
1197       if (f->left_pos < 100)
1198         f->left_pos = 100;  /* don't overlap menu */
1199 #endif
1200       /* Constrain the setFrameTopLeftPoint so we don't move behind the
1201          menu bar.  */
1202       f->output_data.ns->dont_constrain = 0;
1203       [[view window] setFrameTopLeftPoint:
1204                        NSMakePoint (SCREENMAXBOUND (f->left_pos),
1205                                     SCREENMAXBOUND ([fscreen frame].size.height
1206                                                     - NS_TOP_POS (f)))];
1207       f->size_hint_flags &= ~(XNegative|YNegative);
1208     }
1210   UNBLOCK_INPUT;
1214 void
1215 x_set_window_size (struct frame *f, int change_grav, int cols, int rows)
1216 /* --------------------------------------------------------------------------
1217      Adjust window pixel size based on given character grid size
1218      Impl is a bit more complex than other terms, need to do some
1219      internal clipping.
1220    -------------------------------------------------------------------------- */
1222   EmacsView *view = FRAME_NS_VIEW (f);
1223   EmacsToolbar *toolbar = [view toolbar];
1224   NSWindow *window = [view window];
1225   NSRect wr = [window frame];
1226   int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1227   int pixelwidth, pixelheight;
1228   static int oldRows, oldCols, oldFontWidth, oldFontHeight;
1229   static int oldTB;
1230   static struct frame *oldF;
1232   NSTRACE (x_set_window_size);
1234   if (view == nil ||
1235       (f == oldF
1236        && rows == oldRows && cols == oldCols
1237        && oldFontWidth == FRAME_COLUMN_WIDTH (f)
1238        && oldFontHeight == FRAME_LINE_HEIGHT (f)
1239        && oldTB == tb))
1240     return;
1242 /*fprintf (stderr, "\tsetWindowSize: %d x %d, font size %d x %d\n", cols, rows, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f)); */
1244   BLOCK_INPUT;
1246   check_frame_size (f, &rows, &cols);
1247   oldF = f;
1248   oldRows = rows;
1249   oldCols = cols;
1250   oldFontWidth = FRAME_COLUMN_WIDTH (f);
1251   oldFontHeight = FRAME_LINE_HEIGHT (f);
1252   oldTB = tb;
1254   f->scroll_bar_actual_width = NS_SCROLL_BAR_WIDTH (f);
1255   compute_fringe_widths (f, 0);
1257   pixelwidth =  FRAME_TEXT_COLS_TO_PIXEL_WIDTH   (f, cols);
1258   pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
1260   /* If we have a toolbar, take its height into account. */
1261   if (tb)
1262     /* NOTE: previously this would generate wrong result if toolbar not
1263              yet displayed and fixing toolbar_height=32 helped, but
1264              now (200903) seems no longer needed */
1265     FRAME_TOOLBAR_HEIGHT (f) =
1266       NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1267         - FRAME_NS_TITLEBAR_HEIGHT (f);
1268   else
1269     FRAME_TOOLBAR_HEIGHT (f) = 0;
1271   wr.size.width = pixelwidth + f->border_width;
1272   wr.size.height = pixelheight + FRAME_NS_TITLEBAR_HEIGHT (f)
1273                   + FRAME_TOOLBAR_HEIGHT (f);
1275   /* Do not try to constrain to this screen.  We may have multiple
1276      screens, and want Emacs to span those.  Constraining to screen
1277      prevents that, and that is not nice to the user.  */
1278  if (f->output_data.ns->zooming)
1279    f->output_data.ns->zooming = 0;
1280  else
1281    wr.origin.y += FRAME_PIXEL_HEIGHT (f) - pixelheight;
1283   [view setRows: rows andColumns: cols];
1284   [window setFrame: wr display: YES];
1286 /*fprintf (stderr, "\tx_set_window_size %d, %d\t%d, %d\n", cols, rows, pixelwidth, pixelheight); */
1288   /* This is a trick to compensate for Emacs' managing the scrollbar area
1289      as a fixed number of standard character columns.  Instead of leaving
1290      blank space for the extra, we chopped it off above.  Now for
1291      left-hand scrollbars, we shift all rendering to the left by the
1292      difference between the real width and Emacs' imagined one.  For
1293      right-hand bars, don't worry about it since the extra is never used.
1294      (Obviously doesn't work for vertically split windows tho..) */
1295   {
1296     NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1297       ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1298                      - NS_SCROLL_BAR_WIDTH (f), 0)
1299       : NSMakePoint (0, 0);
1300     [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1301     [view setBoundsOrigin: origin];
1302   }
1304   change_frame_size (f, rows, cols, 0, 1, 0); /* pretend, delay, safe */
1305   FRAME_PIXEL_WIDTH (f) = pixelwidth;
1306   FRAME_PIXEL_HEIGHT (f) = pixelheight;
1307 /*  SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */
1309   mark_window_cursors_off (XWINDOW (f->root_window));
1310   cancel_mouse_face (f);
1312   UNBLOCK_INPUT;
1317 /* ==========================================================================
1319     Color management
1321    ========================================================================== */
1324 NSColor *
1325 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1327   struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1328   if (idx < 1 || idx >= color_table->avail)
1329     return nil;
1330   return color_table->colors[idx];
1334 unsigned long
1335 ns_index_color (NSColor *color, struct frame *f)
1337   struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1338   int idx;
1339   NSNumber *index;
1341   if (!color_table->colors)
1342     {
1343       color_table->size = NS_COLOR_CAPACITY;
1344       color_table->avail = 1; /* skip idx=0 as marker */
1345       color_table->colors
1346         = (NSColor **)xmalloc (color_table->size * sizeof (NSColor *));
1347       color_table->colors[0] = nil;
1348       color_table->empty_indices = [[NSMutableSet alloc] init];
1349     }
1351   /* do we already have this color ? */
1352   {
1353     int i;
1354     for (i = 1; i < color_table->avail; i++)
1355       {
1356         if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1357           {
1358             [color_table->colors[i] retain];
1359             return i;
1360           }
1361       }
1362   }
1364   if ([color_table->empty_indices count] > 0)
1365     {
1366       index = [color_table->empty_indices anyObject];
1367       [color_table->empty_indices removeObject: index];
1368       idx = [index unsignedIntValue];
1369     }
1370   else
1371     {
1372       if (color_table->avail == color_table->size)
1373         {
1374           color_table->size += NS_COLOR_CAPACITY;
1375           color_table->colors
1376             = (NSColor **)xrealloc (color_table->colors,
1377                                     color_table->size * sizeof (NSColor *));
1378         }
1379       idx = color_table->avail++;
1380     }
1382   color_table->colors[idx] = color;
1383   [color retain];
1384 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1385   return idx;
1389 void
1390 ns_free_indexed_color (unsigned long idx, struct frame *f)
1392   struct ns_color_table *color_table;
1393   NSColor *color;
1394   NSNumber *index;
1396   if (!f)
1397     return;
1399   color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1401   if (idx <= 0 || idx >= color_table->size) {
1402     message1("ns_free_indexed_color: Color index out of range.\n");
1403     return;
1404   }
1406   index = [NSNumber numberWithUnsignedInt: idx];
1407   if ([color_table->empty_indices containsObject: index]) {
1408     message1("ns_free_indexed_color: attempt to free already freed color.\n");
1409     return;
1410   }
1412   color = color_table->colors[idx];
1413   [color release];
1414   color_table->colors[idx] = nil;
1415   [color_table->empty_indices addObject: [NSNumber numberWithUnsignedInt: idx]];
1416 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1420 static int
1421 ns_get_color (const char *name, NSColor **col)
1422 /* --------------------------------------------------------------------------
1423      Parse a color name
1424    -------------------------------------------------------------------------- */
1425 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1426    X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1427    See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1429   NSColor *new = nil;
1430   static char hex[20];
1431   int scaling;
1432   float r = -1.0, g, b;
1433   NSString *nsname = [NSString stringWithUTF8String: name];
1435 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1436   BLOCK_INPUT;
1438   if ([nsname isEqualToString: @"ns_selection_color"])
1439     {
1440       nsname = ns_selection_color;
1441       name = [ns_selection_color UTF8String];
1442     }
1444   /* First, check for some sort of numeric specification. */
1445   hex[0] = '\0';
1447   if (name[0] == '0' || name[0] == '1' || name[0] == '.')  /* RGB decimal */
1448     {
1449       NSScanner *scanner = [NSScanner scannerWithString: nsname];
1450       [scanner scanFloat: &r];
1451       [scanner scanFloat: &g];
1452       [scanner scanFloat: &b];
1453     }
1454   else if (!strncmp(name, "rgb:", 4))  /* A newer X11 format -- rgb:r/g/b */
1455     {
1456       strncpy (hex, name + 4, 19);
1457       hex[19] = '\0';
1458       scaling = (strlen(hex) - 2) / 3;
1459     }
1460   else if (name[0] == '#')        /* An old X11 format; convert to newer */
1461     {
1462       int len = (strlen(name) - 1);
1463       int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1464       int i;
1465       scaling = strlen(name+start) / 3;
1466       for (i=0; i<3; i++) {
1467         strncpy(hex + i * (scaling + 1), name + start + i * scaling, scaling);
1468         hex[(i+1) * (scaling + 1) - 1] = '/';
1469       }
1470       hex[3 * (scaling + 1) - 1] = '\0';
1471     }
1473   if (hex[0])
1474     {
1475       int rr, gg, bb;
1476       float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1477       if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1478         {
1479           r = rr / fscale;
1480           g = gg / fscale;
1481           b = bb / fscale;
1482         }
1483     }
1485   if (r >= 0.0)
1486     {
1487       *col = [NSColor colorWithCalibratedRed: r green: g blue: b alpha: 1.0];
1488       UNBLOCK_INPUT;
1489       return 0;
1490     }
1492   /* Otherwise, color is expected to be from a list */
1493   {
1494     NSEnumerator *lenum, *cenum;
1495     NSString *name;
1496     NSColorList *clist;
1498 #ifdef NS_IMPL_GNUSTEP
1499     /* XXX: who is wrong, the requestor or the implementation? */
1500     if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1501         == NSOrderedSame)
1502       nsname = @"highlightColor";
1503 #endif
1505     lenum = [[NSColorList availableColorLists] objectEnumerator];
1506     while ( (clist = [lenum nextObject]) && new == nil)
1507       {
1508         cenum = [[clist allKeys] objectEnumerator];
1509         while ( (name = [cenum nextObject]) && new == nil )
1510           {
1511             if ([name compare: nsname
1512                       options: NSCaseInsensitiveSearch] == NSOrderedSame )
1513               new = [clist colorWithKey: name];
1514           }
1515       }
1516   }
1518   if (new)
1519     *col = [new colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1520   UNBLOCK_INPUT;
1521   return new ? 0 : 1;
1525 static NSColor *
1526 ns_get_color_default (const char *name, NSColor *dflt)
1527 /* --------------------------------------------------------------------------
1528      Parse a color or use a default value
1529    -------------------------------------------------------------------------- */
1531   NSColor * col;
1533   if (ns_get_color (name, &col))
1534     return dflt;
1535   else
1536     return col;
1541 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1542 /* --------------------------------------------------------------------------
1543      Convert a Lisp string object to a NS color
1544    -------------------------------------------------------------------------- */
1546   NSTRACE (ns_lisp_to_color);
1547   if (STRINGP (color))
1548     return ns_get_color (SDATA (color), col);
1549   else if (SYMBOLP (color))
1550     return ns_get_color (SDATA (SYMBOL_NAME (color)), col);
1551   return 1;
1555 Lisp_Object
1556 ns_color_to_lisp (NSColor *col)
1557 /* --------------------------------------------------------------------------
1558      Convert a color to a lisp string with the RGB equivalent
1559    -------------------------------------------------------------------------- */
1561   CGFloat red, green, blue, alpha, gray;
1562   char buf[1024];
1563   const char *str;
1564   NSTRACE (ns_color_to_lisp);
1566   BLOCK_INPUT;
1567   if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1569       if ((str =[[col colorNameComponent] UTF8String]))
1570         {
1571           UNBLOCK_INPUT;
1572           return build_string ((char *)str);
1573         }
1575     [[col colorUsingColorSpaceName: NSCalibratedRGBColorSpace]
1576         getRed: &red green: &green blue: &blue alpha: &alpha];
1577   if (red ==green && red ==blue)
1578     {
1579       [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1580             getWhite: &gray alpha: &alpha];
1581       snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1582                 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1583       UNBLOCK_INPUT;
1584       return build_string (buf);
1585     }
1587   snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1588             lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1590   UNBLOCK_INPUT;
1591   return build_string (buf);
1595 void
1596 ns_query_color(void *col, XColor *color_def, int setPixel)
1597 /* --------------------------------------------------------------------------
1598          Get ARGB values out of NSColor col and put them into color_def.
1599          If setPixel, set the pixel to a concatenated version.
1600          and set color_def pixel to the resulting index.
1601    -------------------------------------------------------------------------- */
1603   CGFloat r, g, b, a;
1605   [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1606   color_def->red   = r * 65535;
1607   color_def->green = g * 65535;
1608   color_def->blue  = b * 65535;
1610   if (setPixel == YES)
1611     color_def->pixel
1612       = ARGB_TO_ULONG((int)(a*255),
1613                       (int)(r*255), (int)(g*255), (int)(b*255));
1618 ns_defined_color (struct frame *f,
1619                   const char *name,
1620                   XColor *color_def,
1621                   int alloc,
1622                   char makeIndex)
1623 /* --------------------------------------------------------------------------
1624          Return 1 if named color found, and set color_def rgb accordingly.
1625          If makeIndex and alloc are nonzero put the color in the color_table,
1626          and set color_def pixel to the resulting index.
1627          If makeIndex is zero, set color_def pixel to ARGB.
1628          Return 0 if not found
1629    -------------------------------------------------------------------------- */
1631   NSColor *col;
1632   NSTRACE (ns_defined_color);
1634   BLOCK_INPUT;
1635   if (ns_get_color (name, &col) != 0) /* Color not found  */
1636     {
1637       UNBLOCK_INPUT;
1638       return 0;
1639     }
1640   if (makeIndex && alloc)
1641     color_def->pixel = ns_index_color (col, f);
1642   ns_query_color (col, color_def, !makeIndex);
1643   UNBLOCK_INPUT;
1644   return 1;
1648 unsigned long
1649 ns_get_rgb_color (struct frame *f, float r, float g, float b, float a)
1650 /* --------------------------------------------------------------------------
1651     return an autoreleased RGB color
1652    -------------------------------------------------------------------------- */
1654 /*static int c = 1; fprintf (stderr, "color request %d\n", c++); */
1655   if (r < 0.0) r = 0.0;
1656   else if (r > 1.0) r = 1.0;
1657   if (g < 0.0) g = 0.0;
1658   else if (g > 1.0) g = 1.0;
1659   if (b < 0.0) b = 0.0;
1660   else if (b > 1.0) b = 1.0;
1661   if (a < 0.0) a = 0.0;
1662   else if (a > 1.0) a = 1.0;
1663   return (unsigned long) ns_index_color(
1664     [NSColor colorWithCalibratedRed: r green: g blue: b alpha: a], f);
1668 void
1669 x_set_frame_alpha (struct frame *f)
1670 /* --------------------------------------------------------------------------
1671      change the entire-frame transparency
1672    -------------------------------------------------------------------------- */
1674   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1675   EmacsView *view = FRAME_NS_VIEW (f);
1676   double alpha = 1.0;
1677   double alpha_min = 1.0;
1679   if (dpyinfo->x_highlight_frame == f)
1680     alpha = f->alpha[0];
1681   else
1682     alpha = f->alpha[1];
1684   if (FLOATP (Vframe_alpha_lower_limit))
1685     alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1686   else if (INTEGERP (Vframe_alpha_lower_limit))
1687     alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1689   if (alpha < 0.0)
1690     return;
1691   else if (1.0 < alpha)
1692     alpha = 1.0;
1693   else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1694     alpha = alpha_min;
1696 #ifdef NS_IMPL_COCOA
1697   [[view window] setAlphaValue: alpha];
1698 #endif
1702 /* ==========================================================================
1704     Mouse handling
1706    ========================================================================== */
1709 void
1710 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1711 /* --------------------------------------------------------------------------
1712      Programmatically reposition mouse pointer in pixel coordinates
1713    -------------------------------------------------------------------------- */
1715   NSTRACE (x_set_mouse_pixel_position);
1716   ns_raise_frame (f);
1717 #if 0
1718   /* FIXME: this does not work, and what about GNUstep? */
1719 #ifdef NS_IMPL_COCOA
1720   [FRAME_NS_VIEW (f) lockFocus];
1721   PSsetmouse ((float)pix_x, (float)pix_y);
1722   [FRAME_NS_VIEW (f) unlockFocus];
1723 #endif
1724 #endif
1728 void
1729 x_set_mouse_position (struct frame *f, int h, int v)
1730 /* --------------------------------------------------------------------------
1731      Programmatically reposition mouse pointer in character coordinates
1732    -------------------------------------------------------------------------- */
1734   int pix_x, pix_y;
1736   pix_x = FRAME_COL_TO_PIXEL_X (f, h) + FRAME_COLUMN_WIDTH (f) / 2;
1737   pix_y = FRAME_LINE_TO_PIXEL_Y (f, v) + FRAME_LINE_HEIGHT (f) / 2;
1739   if (pix_x < 0) pix_x = 0;
1740   if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
1742   if (pix_y < 0) pix_y = 0;
1743   if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
1745   x_set_mouse_pixel_position (f, pix_x, pix_y);
1749 static int
1750 note_mouse_movement (struct frame *frame, float x, float y)
1751 /*   ------------------------------------------------------------------------
1752      Called by EmacsView on mouseMovement events.  Passes on
1753      to emacs mainstream code if we moved off of a rect of interest
1754      known as last_mouse_glyph.
1755      ------------------------------------------------------------------------ */
1757 //  NSTRACE (note_mouse_movement);
1759   XSETFRAME (last_mouse_motion_frame, frame);
1761   /* Note, this doesn't get called for enter/leave, since we don't have a
1762      position.  Those are taken care of in the corresponding NSView methods. */
1764   /* has movement gone beyond last rect we were tracking? */
1765   if (x < last_mouse_glyph.origin.x ||
1766       x >= (last_mouse_glyph.origin.x + last_mouse_glyph.size.width) ||
1767       y < last_mouse_glyph.origin.y ||
1768       y >= (last_mouse_glyph.origin.y + last_mouse_glyph.size.height))
1769     {
1770       ns_update_begin(frame);
1771       frame->mouse_moved = 1;
1772       note_mouse_highlight (frame, x, y);
1773       remember_mouse_glyph (frame, x, y, &last_mouse_glyph);
1774       ns_update_end(frame);
1775       return 1;
1776     }
1778   return 0;
1782 static void
1783 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1784                    enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1785                    unsigned long *time)
1786 /* --------------------------------------------------------------------------
1787     External (hook): inform emacs about mouse position and hit parts.
1788     If a scrollbar is being dragged, set bar_window, part, x, y, time.
1789     x & y should be position in the scrollbar (the whole bar, not the handle)
1790     and length of scrollbar respectively
1791    -------------------------------------------------------------------------- */
1793   id view;
1794   NSPoint position;
1795   int xchar, ychar;
1796   Lisp_Object frame, tail;
1797   struct frame *f;
1798   struct ns_display_info *dpyinfo;
1800   NSTRACE (ns_mouse_position);
1802   if (*fp == NULL)
1803     {
1804       fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1805       return;
1806     }
1808   dpyinfo = FRAME_NS_DISPLAY_INFO (*fp);
1810   BLOCK_INPUT;
1812   if (last_mouse_scroll_bar != nil && insist == 0)
1813     {
1814       /* TODO: we do not use this path at the moment because drag events will
1815            go directly to the EmacsScroller.  Leaving code in for now. */
1816       [last_mouse_scroll_bar getMouseMotionPart: (int *)part window: bar_window
1817                                               x: x y: y];
1818       if (time) *time = last_mouse_movement_time;
1819       last_mouse_scroll_bar = nil;
1820     }
1821   else
1822     {
1823       /* Clear the mouse-moved flag for every frame on this display.  */
1824       FOR_EACH_FRAME (tail, frame)
1825         if (FRAME_NS_P (XFRAME (frame))
1826             && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1827           XFRAME (frame)->mouse_moved = 0;
1829       last_mouse_scroll_bar = nil;
1830       if (last_mouse_frame && FRAME_LIVE_P (last_mouse_frame))
1831         f = last_mouse_frame;
1832       else
1833         f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame
1834                                     : SELECTED_FRAME ();
1836       if (f && f->output_data.ns)  /* TODO: 2nd check no longer needed? */
1837         {
1838           view = FRAME_NS_VIEW (*fp);
1840           position = [[view window] mouseLocationOutsideOfEventStream];
1841           position = [view convertPoint: position fromView: nil];
1842           remember_mouse_glyph (f, position.x, position.y, &last_mouse_glyph);
1843 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1845           if (bar_window) *bar_window = Qnil;
1846           if (part) *part = 0; /*scroll_bar_handle; */
1848           if (x) XSETINT (*x, lrint (position.x));
1849           if (y) XSETINT (*y, lrint (position.y));
1850           if (time) *time = last_mouse_movement_time;
1851           *fp = f;
1852         }
1853     }
1855   UNBLOCK_INPUT;
1859 static void
1860 ns_frame_up_to_date (struct frame *f)
1861 /* --------------------------------------------------------------------------
1862     External (hook): Fix up mouse highlighting right after a full update.
1863     Some highlighting was deferred if GC was happening during
1864     note_mouse_highlight (), while other highlighting was deferred for update.
1865    -------------------------------------------------------------------------- */
1867   NSTRACE (ns_frame_up_to_date);
1869   if (FRAME_NS_P (f))
1870     {
1871       Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1872       if ((hlinfo->mouse_face_deferred_gc || f ==hlinfo->mouse_face_mouse_frame)
1873       /*&& hlinfo->mouse_face_mouse_frame*/)
1874         {
1875           BLOCK_INPUT;
1876           ns_update_begin(f);
1877           if (hlinfo->mouse_face_mouse_frame)
1878             note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
1879                                   hlinfo->mouse_face_mouse_x,
1880                                   hlinfo->mouse_face_mouse_y);
1881           hlinfo->mouse_face_deferred_gc = 0;
1882           ns_update_end(f);
1883           UNBLOCK_INPUT;
1884         }
1885     }
1889 void
1890 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1891 /* --------------------------------------------------------------------------
1892     External (RIF): set frame mouse pointer type.
1893    -------------------------------------------------------------------------- */
1895   NSTRACE (ns_define_frame_cursor);
1896   if (FRAME_POINTER_TYPE (f) != cursor)
1897     {
1898       EmacsView *view = FRAME_NS_VIEW (f);
1899       FRAME_POINTER_TYPE (f) = cursor;
1900       [[view window] invalidateCursorRectsForView: view];
1901       /* Redisplay assumes this function also draws the changed frame
1902          cursor, but this function doesn't, so do it explicitly.  */
1903       x_update_cursor (f, 1);
1904     }
1909 /* ==========================================================================
1911     Keyboard handling
1913    ========================================================================== */
1916 static unsigned
1917 ns_convert_key (unsigned code)
1918 /* --------------------------------------------------------------------------
1919     Internal call used by NSView-keyDown.
1920    -------------------------------------------------------------------------- */
1922   const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym)
1923                                 / sizeof (convert_ns_to_X_keysym[0]));
1924   unsigned keysym;
1925   /* An array would be faster, but less easy to read. */
1926   for (keysym = 0; keysym < last_keysym; keysym += 2)
1927     if (code == convert_ns_to_X_keysym[keysym])
1928       return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
1929   return 0;
1930 /* if decide to use keyCode and Carbon table, use this line:
1931      return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
1935 char *
1936 x_get_keysym_name (int keysym)
1937 /* --------------------------------------------------------------------------
1938     Called by keyboard.c.  Not sure if the return val is important, except
1939     that it be unique.
1940    -------------------------------------------------------------------------- */
1942   static char value[16];
1943   NSTRACE (x_get_keysym_name);
1944   sprintf (value, "%d", keysym);
1945   return value;
1950 /* ==========================================================================
1952     Block drawing operations
1954    ========================================================================== */
1957 static void
1958 ns_redraw_scroll_bars (struct frame *f)
1960   int i;
1961   id view;
1962   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
1963   NSTRACE (ns_judge_scroll_bars);
1964   for (i =[subviews count]-1; i >= 0; i--)
1965     {
1966       view = [subviews objectAtIndex: i];
1967       if (![view isKindOfClass: [EmacsScroller class]]) continue;
1968       [view display];
1969     }
1973 void
1974 ns_clear_frame (struct frame *f)
1975 /* --------------------------------------------------------------------------
1976       External (hook): Erase the entire frame
1977    -------------------------------------------------------------------------- */
1979   NSView *view = FRAME_NS_VIEW (f);
1980   NSRect r;
1982   NSTRACE (ns_clear_frame);
1983   if (ns_in_resize)
1984     return;
1986  /* comes on initial frame because we have
1987     after-make-frame-functions = select-frame */
1988  if (!FRAME_DEFAULT_FACE (f))
1989    return;
1991   mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
1993   output_cursor.hpos = output_cursor.vpos = 0;
1994   output_cursor.x = -1;
1996   r = [view bounds];
1998   BLOCK_INPUT;
1999   ns_focus (f, &r, 1);
2000   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
2001   NSRectFill (r);
2002   ns_unfocus (f);
2004 #ifdef NS_IMPL_COCOA
2005   [[view window] display];  /* redraw resize handle */
2006 #endif
2008   /* as of 2006/11 or so this is now needed */
2009   ns_redraw_scroll_bars (f);
2010   UNBLOCK_INPUT;
2014 void
2015 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2016 /* --------------------------------------------------------------------------
2017     External (RIF):  Clear section of frame
2018    -------------------------------------------------------------------------- */
2020   NSRect r = NSMakeRect (x, y, width, height);
2021   NSView *view = FRAME_NS_VIEW (f);
2022   struct face *face = FRAME_DEFAULT_FACE (f);
2024   if (!view || !face)
2025     return;
2027   NSTRACE (ns_clear_frame_area);
2029   r = NSIntersectionRect (r, [view frame]);
2030   ns_focus (f, &r, 1);
2031   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2033 #ifdef NS_IMPL_COCOA
2034   {
2035     /* clip out the resize handle */
2036     NSWindow *window = [FRAME_NS_VIEW (f) window];
2037     NSRect ir
2038       = [view convertRect: ns_resize_handle_rect (window) fromView: nil];
2040     ir = NSIntersectionRect (r, ir);
2041     if (NSIsEmptyRect (ir))
2042       {
2043 #endif
2045   NSRectFill (r);
2047 #ifdef NS_IMPL_COCOA
2048       }
2049     else
2050       {
2051         NSRect r1 = r, r2 = r; /* upper and lower non-intersecting */
2052         r1.size.height -= ir.size.height;
2053         r2.origin.y += r1.size.height;
2054         r2.size.width -= ir.size.width;
2055         r2.size.height = ir.size.height;
2056         NSRectFill (r1);
2057         NSRectFill (r2);
2058       }
2059   }
2060 #endif
2062   ns_unfocus (f);
2063   return;
2067 static void
2068 ns_scroll_run (struct window *w, struct run *run)
2069 /* --------------------------------------------------------------------------
2070     External (RIF):  Insert or delete n lines at line vpos
2071    -------------------------------------------------------------------------- */
2073   struct frame *f = XFRAME (w->frame);
2074   int x, y, width, height, from_y, to_y, bottom_y;
2076   NSTRACE (ns_scroll_run);
2078   /* begin copy from other terms */
2079   /* Get frame-relative bounding box of the text display area of W,
2080      without mode lines.  Include in this box the left and right
2081      fringe of W.  */
2082   window_box (w, -1, &x, &y, &width, &height);
2084   from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2085   to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2086   bottom_y = y + height;
2088   if (to_y < from_y)
2089     {
2090       /* Scrolling up.  Make sure we don't copy part of the mode
2091          line at the bottom.  */
2092       if (from_y + run->height > bottom_y)
2093         height = bottom_y - from_y;
2094       else
2095         height = run->height;
2096     }
2097   else
2098     {
2099       /* Scolling down.  Make sure we don't copy over the mode line.
2100          at the bottom.  */
2101       if (to_y + run->height > bottom_y)
2102         height = bottom_y - to_y;
2103       else
2104         height = run->height;
2105     }
2106   /* end copy from other terms */
2108   if (height == 0)
2109       return;
2111   BLOCK_INPUT;
2113   updated_window = w;
2114   x_clear_cursor (w);
2116   {
2117     NSRect srcRect = NSMakeRect (x, from_y, width, height);
2118     NSRect dstRect = NSMakeRect (x, to_y, width, height);
2119     NSPoint dstOrigin = NSMakePoint (x, to_y);
2121     ns_focus (f, &dstRect, 1);
2122     NSCopyBits (0, srcRect , dstOrigin);
2123     ns_unfocus (f);
2124   }
2126   UNBLOCK_INPUT;
2130 static void
2131 ns_after_update_window_line (struct glyph_row *desired_row)
2132 /* --------------------------------------------------------------------------
2133     External (RIF): preparatory to fringe update after text was updated
2134    -------------------------------------------------------------------------- */
2136   struct window *w = updated_window;
2137   struct frame *f;
2138   int width, height;
2140   NSTRACE (ns_after_update_window_line);
2142   /* begin copy from other terms */
2143   xassert (w);
2145   if (!desired_row->mode_line_p && !w->pseudo_window_p)
2146     desired_row->redraw_fringe_bitmaps_p = 1;
2148   /* When a window has disappeared, make sure that no rest of
2149      full-width rows stays visible in the internal border.
2150      Under NS this is drawn inside the fringes. */
2151   if (windows_or_buffers_changed
2152       && (f = XFRAME (w->frame),
2153           width = FRAME_INTERNAL_BORDER_WIDTH (f),
2154           width != 0)
2155       && (height = desired_row->visible_height,
2156           height > 0))
2157     {
2158       int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2160       /* Internal border is drawn below the tool bar.  */
2161       if (WINDOWP (f->tool_bar_window)
2162           && w == XWINDOW (f->tool_bar_window))
2163         y -= width;
2164       /* end copy from other terms */
2166       BLOCK_INPUT;
2167       if (!desired_row->full_width_p)
2168         {
2169           int x1 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2170             + WINDOW_LEFT_FRINGE_WIDTH (w);
2171           int x2 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2172             + FRAME_PIXEL_WIDTH (f) - NS_SCROLL_BAR_WIDTH (f)
2173             - WINDOW_RIGHT_FRINGE_WIDTH (w)
2174             - FRAME_INTERNAL_BORDER_WIDTH (f);
2175           ns_clear_frame_area (f, x1, y, width, height);
2176           ns_clear_frame_area (f, x2, y, width, height);
2177         }
2178       UNBLOCK_INPUT;
2179     }
2183 static void
2184 ns_shift_glyphs_for_insert (struct frame *f,
2185                            int x, int y, int width, int height,
2186                            int shift_by)
2187 /* --------------------------------------------------------------------------
2188     External (RIF): copy an area horizontally, don't worry about clearing src
2189    -------------------------------------------------------------------------- */
2191   NSRect srcRect = NSMakeRect (x, y, width, height);
2192   NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2193   NSPoint dstOrigin = dstRect.origin;
2195   NSTRACE (ns_shift_glyphs_for_insert);
2197   ns_focus (f, &dstRect, 1);
2198   NSCopyBits (0, srcRect, dstOrigin);
2199   ns_unfocus (f);
2204 /* ==========================================================================
2206     Character encoding and metrics
2208    ========================================================================== */
2211 static inline void
2212 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2213 /* --------------------------------------------------------------------------
2214      External (RIF); compute left/right overhang of whole string and set in s
2215    -------------------------------------------------------------------------- */
2217   struct face *face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2218   struct font *font = s->font; /*face->font; */
2220   if (s->char2b)
2221     {
2222       struct font_metrics metrics;
2223       unsigned int codes[2];
2224       codes[0] = *(s->char2b);
2225       codes[1] = *(s->char2b + s->nchars - 1);
2227       font->driver->text_extents (font, codes, 2, &metrics);
2228       s->left_overhang = -metrics.lbearing;
2229       s->right_overhang
2230         = metrics.rbearing > metrics.width
2231         ? metrics.rbearing - metrics.width : 0;
2232     }
2233   else
2234     {
2235       s->left_overhang = 0;
2236       s->right_overhang = ((struct nsfont_info *)font)->ital ?
2237         FONT_HEIGHT (font) * 0.2 : 0;
2238     }
2243 /* ==========================================================================
2245     Fringe and cursor drawing
2247    ========================================================================== */
2250 extern int max_used_fringe_bitmap;
2251 static void
2252 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2253                       struct draw_fringe_bitmap_params *p)
2254 /* --------------------------------------------------------------------------
2255     External (RIF); fringe-related
2256    -------------------------------------------------------------------------- */
2258   struct frame *f = XFRAME (WINDOW_FRAME (w));
2259   struct face *face = p->face;
2260   int rowY;
2261   static EmacsImage **bimgs = NULL;
2262   static int nBimgs = 0;
2263   /* NS-specific: move internal border inside fringe */
2264   int x = p->bx < 0 ? p->x : p->bx;
2265   int wd = p->bx < 0 ? p->wd : p->nx;
2266   BOOL fringeOnVeryLeft
2267     = x - WINDOW_LEFT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w)
2268       - FRAME_INTERNAL_BORDER_WIDTH (f) < 10;
2269   BOOL fringeOnVeryRight
2270     = FRAME_PIXEL_WIDTH (f) - x - wd - FRAME_INTERNAL_BORDER_WIDTH (f)
2271       - WINDOW_RIGHT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w) < 10;
2272   int xAdjust = FRAME_INTERNAL_BORDER_WIDTH (f) *
2273     (fringeOnVeryLeft ? -1 : (fringeOnVeryRight ? 1 : 0));
2275   /* grow bimgs if needed */
2276   if (nBimgs < max_used_fringe_bitmap)
2277     {
2278       EmacsImage **newBimgs
2279         = xmalloc (max_used_fringe_bitmap * sizeof (EmacsImage *));
2280       memset (newBimgs, 0, max_used_fringe_bitmap * sizeof (EmacsImage *));
2282       if (nBimgs)
2283         {
2284           memcpy (newBimgs, bimgs, nBimgs * sizeof (EmacsImage *));
2285           xfree (bimgs);
2286         }
2288       bimgs = newBimgs;
2289       nBimgs = max_used_fringe_bitmap;
2290     }
2292   /* Must clip because of partially visible lines.  */
2293   rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
2294   ns_clip_to_row (w, row, -1, YES);
2296   if (p->bx >= 0 && !p->overlay_p)
2297     {
2298       int yAdjust = rowY - FRAME_INTERNAL_BORDER_WIDTH (f) < 5 ?
2299         -FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2300       int yIncr = FRAME_PIXEL_HEIGHT (f) - (p->by+yAdjust + p->ny) < 5 ?
2301         FRAME_INTERNAL_BORDER_WIDTH (f) : 0
2302         + (yAdjust ? FRAME_INTERNAL_BORDER_WIDTH (f) : 0);
2303       NSRect r = NSMakeRect (p->bx+xAdjust, p->by+yAdjust, p->nx, p->ny+yIncr);
2304       NSRectClip (r);
2305       [ns_lookup_indexed_color(face->background, f) set];
2306       NSRectFill (r);
2307     }
2309   if (p->which)
2310     {
2311       NSRect r = NSMakeRect (p->x+xAdjust, p->y, p->wd, p->h);
2312       NSPoint pt = r.origin;
2313       EmacsImage *img = bimgs[p->which - 1];
2315       if (!img)
2316         {
2317           unsigned short *bits = p->bits + p->dh;
2318           int len = 8 * p->h/8;
2319           int i;
2320           unsigned char *cbits = xmalloc (len);
2322           for (i =0; i<len; i++)
2323             cbits[i] = ~(bits[i] & 0xff);
2324           img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2325                                            flip: NO];
2326           bimgs[p->which - 1] = img;
2327           xfree (cbits);
2328         }
2330       NSRectClip (r);
2331       /* Since we composite the bitmap instead of just blitting it, we need
2332          to erase the whole background. */
2333       [ns_lookup_indexed_color(face->background, f) set];
2334       NSRectFill (r);
2335       pt.y += p->h;
2336       [img setXBMColor: ns_lookup_indexed_color(face->foreground, f)];
2337       [img compositeToPoint: pt operation: NSCompositeSourceOver];
2338     }
2339   ns_unfocus (f);
2343 void
2344 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2345                        int x, int y, int cursor_type, int cursor_width,
2346                        int on_p, int active_p)
2347 /* --------------------------------------------------------------------------
2348      External call (RIF): draw cursor.
2349      Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2350    -------------------------------------------------------------------------- */
2352   NSRect r, s;
2353   int fx, fy, h, cursor_height;
2354   struct frame *f = WINDOW_XFRAME (w);
2355   struct glyph *phys_cursor_glyph;
2356   int overspill;
2357   struct glyph *cursor_glyph;
2358   struct face *face;
2359   NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2361   /* If cursor is out of bounds, don't draw garbage.  This can happen
2362      in mini-buffer windows when switching between echo area glyphs
2363      and mini-buffer.  */
2365   NSTRACE (dumpcursor);
2367   if (!on_p)
2368     return;
2370   w->phys_cursor_type = cursor_type;
2371   w->phys_cursor_on_p = on_p;
2373   if (cursor_type == NO_CURSOR)
2374     {
2375       w->phys_cursor_width = 0;
2376       return;
2377     }
2379   if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2380     {
2381       if (glyph_row->exact_window_width_line_p
2382           && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2383         {
2384           glyph_row->cursor_in_fringe_p = 1;
2385           draw_fringe_bitmap (w, glyph_row, 0);
2386         }
2387       return;
2388     }
2390   /* We draw the cursor (with NSRectFill), then draw the glyph on top
2391      (other terminals do it the other way round).  We must set
2392      w->phys_cursor_width to the cursor width.  For bar cursors, that
2393      is CURSOR_WIDTH; for box cursors, it is the glyph width.  */
2394   get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2396   /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2397      to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2398   if (cursor_type == BAR_CURSOR)
2399     {
2400       if (cursor_width < 1)
2401         cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2402       w->phys_cursor_width = cursor_width;
2403     }
2404   /* If we have an HBAR, "cursor_width" MAY specify height. */
2405   else if (cursor_type == HBAR_CURSOR)
2406     {
2407       cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2408       fy += h - cursor_height;
2409       h = cursor_height;
2410     }
2412   r.origin.x = fx, r.origin.y = fy;
2413   r.size.height = h;
2414   r.size.width = w->phys_cursor_width;
2416   /* FIXME: if we overwrite the internal border area, it does not get erased;
2417      fix by truncating cursor, but better would be to erase properly */
2418   overspill = r.origin.x + r.size.width -
2419     WINDOW_TEXT_TO_FRAME_PIXEL_X (w, WINDOW_BOX_RIGHT_EDGE_X (w)
2420       - WINDOW_TOTAL_FRINGE_WIDTH (w) - FRAME_INTERNAL_BORDER_WIDTH (f));
2421   if (overspill > 0)
2422     r.size.width -= overspill;
2424   /* TODO: only needed in rare cases with last-resort font in HELLO..
2425      should we do this more efficiently? */
2426   ns_clip_to_row (w, glyph_row, -1, NO); /* do ns_focus(f, &r, 1); if remove */
2429   face = FACE_FROM_ID (f, phys_cursor_glyph->face_id);
2430   if (face && NS_FACE_BACKGROUND (face)
2431       == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2432     {
2433       [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2434       hollow_color = FRAME_CURSOR_COLOR (f);
2435     }
2436   else
2437     [FRAME_CURSOR_COLOR (f) set];
2439 #ifdef NS_IMPL_COCOA
2440   /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2441            atomic.  Cleaner ways of doing this should be investigated.
2442            One way would be to set a global variable DRAWING_CURSOR
2443            when making the call to draw_phys..(), don't focus in that
2444            case, then move the ns_unfocus() here after that call. */
2445   NSDisableScreenUpdates ();
2446 #endif
2448   switch (cursor_type)
2449     {
2450     case NO_CURSOR:
2451       break;
2452     case FILLED_BOX_CURSOR:
2453       NSRectFill (r);
2454       break;
2455     case HOLLOW_BOX_CURSOR:
2456       NSRectFill (r);
2457       [hollow_color set];
2458       NSRectFill (NSInsetRect (r, 1, 1));
2459       [FRAME_CURSOR_COLOR (f) set];
2460       break;
2461     case HBAR_CURSOR:
2462       NSRectFill (r);
2463       break;
2464     case BAR_CURSOR:
2465       s = r;
2466       /* If the character under cursor is R2L, draw the bar cursor
2467          on the right of its glyph, rather than on the left.  */
2468       cursor_glyph = get_phys_cursor_glyph (w);
2469       if ((cursor_glyph->resolved_level & 1) != 0)
2470         s.origin.x += cursor_glyph->pixel_width - s.size.width;
2472       NSRectFill (s);
2473       break;
2474     }
2475   ns_unfocus (f);
2477   /* draw the character under the cursor */
2478   if (cursor_type != NO_CURSOR)
2479     draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2481 #ifdef NS_IMPL_COCOA
2482   NSEnableScreenUpdates ();
2483 #endif
2488 static void
2489 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2490 /* --------------------------------------------------------------------------
2491      External (RIF): Draw a vertical line.
2492    -------------------------------------------------------------------------- */
2494   struct frame *f = XFRAME (WINDOW_FRAME (w));
2495   struct face *face;
2496   NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2498   NSTRACE (ns_draw_vertical_window_border);
2500   face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2501   if (face)
2502       [ns_lookup_indexed_color(face->foreground, f) set];
2504   ns_focus (f, &r, 1);
2505   NSRectFill(r);
2506   ns_unfocus (f);
2510 void
2511 show_hourglass (struct atimer *timer)
2513   if (hourglass_shown_p)
2514     return;
2516   BLOCK_INPUT;
2518   /* TODO: add NSProgressIndicator to selected frame (see macfns.c) */
2520   hourglass_shown_p = 1;
2521   UNBLOCK_INPUT;
2525 void
2526 hide_hourglass (void)
2528   if (!hourglass_shown_p)
2529     return;
2531   BLOCK_INPUT;
2533   /* TODO: remove NSProgressIndicator from all frames */
2535   hourglass_shown_p = 0;
2536   UNBLOCK_INPUT;
2541 /* ==========================================================================
2543     Glyph drawing operations
2545    ========================================================================== */
2548 static inline NSRect
2549 ns_fix_rect_ibw (NSRect r, int fibw, int frame_pixel_width)
2550 /* --------------------------------------------------------------------------
2551     Under NS we draw internal borders inside fringes, and want full-width
2552     rendering to go all the way to edge.  This function makes that correction.
2553    -------------------------------------------------------------------------- */
2555   if (r.origin.y <= fibw+1)
2556     {
2557       r.size.height += r.origin.y;
2558       r.origin.y = 0;
2559     }
2560   if (r.origin.x <= fibw+1)
2561     {
2562       r.size.width += r.origin.x;
2563       r.origin.x = 0;
2564     }
2565   if (frame_pixel_width - (r.origin.x+r.size.width) <= fibw+1)
2566     r.size.width += fibw;
2568   return r;
2572 static int
2573 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2574 /* --------------------------------------------------------------------------
2575     Wrapper utility to account for internal border width on full-width lines,
2576     and allow top full-width rows to hit the frame top.  nr should be pointer
2577     to two successive NSRects.  Number of rects actually used is returned.
2578    -------------------------------------------------------------------------- */
2580   int n = get_glyph_string_clip_rects (s, nr, 2);
2581   if (s->row->full_width_p)
2582     {
2583       *nr = ns_fix_rect_ibw (*nr, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2584                             FRAME_PIXEL_WIDTH (s->f));
2585       if (n == 2)
2586         *nr = ns_fix_rect_ibw (*(nr+1), FRAME_INTERNAL_BORDER_WIDTH (s->f),
2587                               FRAME_PIXEL_WIDTH (s->f));
2588     }
2589   return n;
2593 static void
2594 ns_draw_box (NSRect r, float thickness, NSColor *col, char left_p, char right_p)
2595 /* --------------------------------------------------------------------------
2596     Draw an unfilled rect inside r, optionally leaving left and/or right open.
2597     Note we can't just use an NSDrawRect command, because of the possibility
2598     of some sides not being drawn, and because the rect will be filled.
2599    -------------------------------------------------------------------------- */
2601   NSRect s = r;
2602   [col set];
2604   /* top, bottom */
2605   s.size.height = thickness;
2606   NSRectFill (s);
2607   s.origin.y += r.size.height - thickness;
2608   NSRectFill (s);
2610   s.size.height = r.size.height;
2611   s.origin.y = r.origin.y;
2613   /* left, right (optional) */
2614   s.size.width = thickness;
2615   if (left_p)
2616     NSRectFill (s);
2617   if (right_p)
2618     {
2619       s.origin.x += r.size.width - thickness;
2620       NSRectFill (s);
2621     }
2625 static void
2626 ns_draw_relief (NSRect r, int thickness, char raised_p,
2627                char top_p, char bottom_p, char left_p, char right_p,
2628                struct glyph_string *s)
2629 /* --------------------------------------------------------------------------
2630     Draw a relief rect inside r, optionally leaving some sides open.
2631     Note we can't just use an NSDrawBezel command, because of the possibility
2632     of some sides not being drawn, and because the rect will be filled.
2633    -------------------------------------------------------------------------- */
2635   static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2636   NSColor *newBaseCol = nil;
2637   NSRect sr = r;
2639   NSTRACE (ns_draw_relief);
2641   /* set up colors */
2643   if (s->face->use_box_color_for_shadows_p)
2644     {
2645       newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2646     }
2647 /*     else if (s->first_glyph->type == IMAGE_GLYPH
2648            && s->img->pixmap
2649            && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2650        {
2651          newBaseCol = IMAGE_BACKGROUND  (s->img, s->f, 0);
2652        } */
2653   else
2654     {
2655       newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2656     }
2658   if (newBaseCol == nil)
2659     newBaseCol = [NSColor grayColor];
2661   if (newBaseCol != baseCol)  /* TODO: better check */
2662     {
2663       [baseCol release];
2664       baseCol = [newBaseCol retain];
2665       [lightCol release];
2666       lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2667       [darkCol release];
2668       darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2669     }
2671   [(raised_p ? lightCol : darkCol) set];
2673   /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2675   /* top */
2676   sr.size.height = thickness;
2677   if (top_p) NSRectFill (sr);
2679   /* left */
2680   sr.size.height = r.size.height;
2681   sr.size.width = thickness;
2682   if (left_p) NSRectFill (sr);
2684   [(raised_p ? darkCol : lightCol) set];
2686   /* bottom */
2687   sr.size.width = r.size.width;
2688   sr.size.height = thickness;
2689   sr.origin.y += r.size.height - thickness;
2690   if (bottom_p) NSRectFill (sr);
2692   /* right */
2693   sr.size.height = r.size.height;
2694   sr.origin.y = r.origin.y;
2695   sr.size.width = thickness;
2696   sr.origin.x += r.size.width - thickness;
2697   if (right_p) NSRectFill (sr);
2701 static void
2702 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2703 /* --------------------------------------------------------------------------
2704       Function modeled after x_draw_glyph_string_box ().
2705       Sets up parameters for drawing.
2706    -------------------------------------------------------------------------- */
2708   int right_x, last_x;
2709   char left_p, right_p;
2710   struct glyph *last_glyph;
2711   NSRect r;
2712   int thickness;
2713   struct face *face;
2715   if (s->hl == DRAW_MOUSE_FACE)
2716     {
2717       face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2718       if (!face)
2719         face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2720     }
2721   else
2722     face = s->face;
2724   thickness = face->box_line_width;
2726   NSTRACE (ns_dumpglyphs_box_or_relief);
2728   last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2729             ? WINDOW_RIGHT_EDGE_X (s->w)
2730             : window_box_right (s->w, s->area));
2731   last_glyph = (s->cmp || s->img
2732                 ? s->first_glyph : s->first_glyph + s->nchars-1);
2734   right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2735               ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2737   left_p = (s->first_glyph->left_box_line_p
2738             || (s->hl == DRAW_MOUSE_FACE
2739                 && (s->prev == NULL || s->prev->hl != s->hl)));
2740   right_p = (last_glyph->right_box_line_p
2741              || (s->hl == DRAW_MOUSE_FACE
2742                  && (s->next == NULL || s->next->hl != s->hl)));
2744   r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2746   /* expand full-width row over internal borders */
2747   if (s->row->full_width_p)
2748     r = ns_fix_rect_ibw (r, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2749                         FRAME_PIXEL_WIDTH (s->f));
2751   /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
2752   if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
2753     {
2754       ns_draw_box (r, abs (thickness),
2755                    ns_lookup_indexed_color (face->box_color, s->f),
2756                   left_p, right_p);
2757     }
2758   else
2759     {
2760       ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2761                      1, 1, left_p, right_p, s);
2762     }
2766 static void
2767 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2768 /* --------------------------------------------------------------------------
2769       Modeled after x_draw_glyph_string_background, which draws BG in
2770       certain cases.  Others are left to the text rendering routine.
2771    -------------------------------------------------------------------------- */
2773   NSTRACE (ns_maybe_dumpglyphs_background);
2775   if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2776     {
2777       int box_line_width = max (s->face->box_line_width, 0);
2778       if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2779           || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2780         {
2781           struct face *face;
2782           if (s->hl == DRAW_MOUSE_FACE)
2783             {
2784               face = FACE_FROM_ID (s->f,
2785                                    MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2786               if (!face)
2787                 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2788             }
2789           else
2790             face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2791           if (!face->stipple)
2792             [(NS_FACE_BACKGROUND (face) != 0
2793               ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2794               : FRAME_BACKGROUND_COLOR (s->f)) set];
2795           else
2796             {
2797               struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (s->f);
2798               [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2799             }
2801           if (s->hl != DRAW_CURSOR)
2802             {
2803               NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2804                                     s->background_width,
2805                                     s->height-2*box_line_width);
2807               /* expand full-width row over internal borders */
2808               if (s->row->full_width_p)
2809                 {
2810                   int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2811                   if (r.origin.y <= fibw+1 + box_line_width)
2812                     {
2813                       r.size.height += r.origin.y;
2814                       r.origin.y = 0;
2815                     }
2816                   if (r.origin.x <= fibw+1)
2817                     {
2818                       r.size.width += 2*r.origin.x;
2819                       r.origin.x = 0;
2820                     }
2821                   if (FRAME_PIXEL_WIDTH (s->f) - (r.origin.x + r.size.width)
2822                       <= fibw+1)
2823                     r.size.width += fibw;
2824                 }
2826               NSRectFill (r);
2827             }
2829           s->background_filled_p = 1;
2830         }
2831     }
2835 static void
2836 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2837 /* --------------------------------------------------------------------------
2838       Renders an image and associated borders.
2839    -------------------------------------------------------------------------- */
2841   EmacsImage *img = s->img->pixmap;
2842   int box_line_vwidth = max (s->face->box_line_width, 0);
2843   int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2844   int bg_x, bg_y, bg_height;
2845   int th;
2846   char raised_p;
2847   NSRect br;
2848   struct face *face;
2850   NSTRACE (ns_dumpglyphs_image);
2852   if (s->face->box != FACE_NO_BOX
2853       && s->first_glyph->left_box_line_p && s->slice.x == 0)
2854     x += abs (s->face->box_line_width);
2856   bg_x = x;
2857   bg_y =  s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2858   bg_height = s->height;
2859   /* other terms have this, but was causing problems w/tabbar mode */
2860   /* - 2 * box_line_vwidth; */
2862   if (s->slice.x == 0) x += s->img->hmargin;
2863   if (s->slice.y == 0) y += s->img->vmargin;
2865   /* Draw BG: if we need larger area than image itself cleared, do that,
2866      otherwise, since we composite the image under NS (instead of mucking
2867      with its background color), we must clear just the image area. */
2868   if (s->hl == DRAW_MOUSE_FACE)
2869     {
2870       face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2871       if (!face)
2872        face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2873     }
2874   else
2875     face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2877   if (s->hl == DRAW_CURSOR)
2878       [FRAME_CURSOR_COLOR (s->f) set];
2879   else
2880     [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
2882   if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
2883       || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
2884     {
2885       br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
2886       s->background_filled_p = 1;
2887     }
2888   else
2889     {
2890       br = NSMakeRect (x, y, s->slice.width, s->slice.height);
2891     }
2893   /* expand full-width row over internal borders */
2894   if (s->row->full_width_p)
2895     {
2896       int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2897       if (br.origin.y <= fibw+1 + box_line_vwidth)
2898         {
2899           br.size.height += br.origin.y;
2900           br.origin.y = 0;
2901         }
2902       if (br.origin.x <= fibw+1 + box_line_vwidth)
2903         {
2904           br.size.width += br.origin.x;
2905           br.origin.x = 0;
2906         }
2907       if (FRAME_PIXEL_WIDTH (s->f) - (br.origin.x + br.size.width) <= fibw+1)
2908         br.size.width += fibw;
2909     }
2911   NSRectFill (br);
2913   /* Draw the image.. do we need to draw placeholder if img ==nil? */
2914   if (img != nil)
2915     [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
2916                 operation: NSCompositeSourceOver];
2918   /* Draw relief, if requested */
2919   if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
2920     {
2921       if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
2922         {
2923           th = tool_bar_button_relief >= 0 ?
2924             tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2925           raised_p = (s->hl == DRAW_IMAGE_RAISED);
2926         }
2927       else
2928         {
2929           th = abs (s->img->relief);
2930           raised_p = (s->img->relief > 0);
2931         }
2933       r.origin.x = x - th;
2934       r.origin.y = y - th;
2935       r.size.width = s->slice.width + 2*th-1;
2936       r.size.height = s->slice.height + 2*th-1;
2937       ns_draw_relief (r, th, raised_p,
2938                       s->slice.y == 0,
2939                       s->slice.y + s->slice.height == s->img->height,
2940                       s->slice.x == 0,
2941                       s->slice.x + s->slice.width == s->img->width, s);
2942     }
2944   /* If there is no mask, the background won't be seen,
2945      so draw a rectangle on the image for the cursor.
2946      Do this for all images, getting trancparency right is not reliable.  */
2947   if (s->hl == DRAW_CURSOR)
2948     {
2949       int thickness = abs (s->img->relief);
2950       if (thickness == 0) thickness = 1;
2951       ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
2952     }
2956 static void
2957 ns_dumpglyphs_stretch (struct glyph_string *s)
2959   NSRect r[2];
2960   int n, i;
2961   struct face *face;
2963   if (!s->background_filled_p)
2964     {
2965       n = ns_get_glyph_string_clip_rect (s, r);
2966       *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
2968       for (i=0; i<n; i++)
2969         {
2970           if (!s->row->full_width_p)
2971             {
2972               /* truncate to avoid overwriting fringe and/or scrollbar */
2973               int overrun = max (0, (s->x + s->background_width)
2974                                   - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
2975                                     - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
2976               r[i].size.width -= overrun;
2978               /* XXX: Try to work between problem where a stretch glyph on
2979                  a partially-visible bottom row will clear part of the
2980                  modeline, and another where list-buffers headers and similar
2981                  rows erroneously have visible_height set to 0.  Not sure
2982                  where this is coming from as other terms seem not to show. */
2983               r[i].size.height = min (s->height, s->row->visible_height);
2984             }
2986           /* expand full-width rows over internal borders */
2987           else
2988             {
2989               r[i] = ns_fix_rect_ibw (r[i], FRAME_INTERNAL_BORDER_WIDTH (s->f),
2990                                       FRAME_PIXEL_WIDTH (s->f));
2991             }
2993           /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
2994              overwriting cursor (usually when cursor on a tab) */
2995           if (s->hl == DRAW_CURSOR)
2996             {
2997               r[i].origin.x += s->width;
2998               r[i].size.width -= s->width;
2999             }
3000         }
3002       ns_focus (s->f, r, n);
3004       if (s->hl == DRAW_MOUSE_FACE)
3005        {
3006          face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3007          if (!face)
3008            face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3009        }
3010       else
3011        face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3013       [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
3015       NSRectFill (r[0]);
3016       NSRectFill (r[1]);
3017       ns_unfocus (s->f);
3018       s->background_filled_p = 1;
3019     }
3023 static void
3024 ns_draw_glyph_string (struct glyph_string *s)
3025 /* --------------------------------------------------------------------------
3026       External (RIF): Main draw-text call.
3027    -------------------------------------------------------------------------- */
3029   /* TODO (optimize): focus for box and contents draw */
3030   NSRect r[2];
3031   int n;
3032   char box_drawn_p = 0;
3034   NSTRACE (ns_draw_glyph_string);
3036   if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3037     {
3038       int width;
3039       struct glyph_string *next;
3041       for (width = 0, next = s->next;
3042            next && width < s->right_overhang;
3043            width += next->width, next = next->next)
3044         if (next->first_glyph->type != IMAGE_GLYPH)
3045           {
3046             if (next->first_glyph->type != STRETCH_GLYPH)
3047               {
3048                 n = ns_get_glyph_string_clip_rect (s->next, r);
3049                 ns_focus (s->f, r, n);
3050                 ns_maybe_dumpglyphs_background (s->next, 1);
3051                 ns_unfocus (s->f);
3052               }
3053             else
3054               {
3055                 ns_dumpglyphs_stretch (s->next);
3056               }
3057             next->num_clips = 0;
3058           }
3059     }
3061   if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3062         && (s->first_glyph->type == CHAR_GLYPH
3063             || s->first_glyph->type == COMPOSITE_GLYPH))
3064     {
3065       n = ns_get_glyph_string_clip_rect (s, r);
3066       ns_focus (s->f, r, n);
3067       ns_maybe_dumpglyphs_background (s, 1);
3068       ns_dumpglyphs_box_or_relief (s);
3069       ns_unfocus (s->f);
3070       box_drawn_p = 1;
3071     }
3073   switch (s->first_glyph->type)
3074     {
3076     case IMAGE_GLYPH:
3077       n = ns_get_glyph_string_clip_rect (s, r);
3078       ns_focus (s->f, r, n);
3079       ns_dumpglyphs_image (s, r[0]);
3080       ns_unfocus (s->f);
3081       break;
3083     case STRETCH_GLYPH:
3084       ns_dumpglyphs_stretch (s);
3085       break;
3087     case CHAR_GLYPH:
3088     case COMPOSITE_GLYPH:
3089       n = ns_get_glyph_string_clip_rect (s, r);
3090       ns_focus (s->f, r, n);
3092       if (s->for_overlaps || (s->cmp_from > 0
3093                               && ! s->first_glyph->u.cmp.automatic))
3094         s->background_filled_p = 1;
3095       else
3096         ns_maybe_dumpglyphs_background
3097           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3099       ns_tmp_flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3100                     (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3101                      (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3102                       NS_DUMPGLYPH_NORMAL));
3103       ns_tmp_font = (struct nsfont_info *)s->face->font;
3104       if (ns_tmp_font == NULL)
3105           ns_tmp_font = (struct nsfont_info *)FRAME_FONT (s->f);
3107       if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3108         {
3109           unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3110           NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3111           NS_FACE_FOREGROUND (s->face) = tmp;
3112         }
3114       ns_tmp_font->font.driver->draw
3115         (s, 0, s->nchars, s->x, s->y,
3116          (ns_tmp_flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3117          || ns_tmp_flags == NS_DUMPGLYPH_MOUSEFACE);
3119       if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3120         {
3121           unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3122           NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3123           NS_FACE_FOREGROUND (s->face) = tmp;
3124         }
3126       ns_unfocus (s->f);
3127       break;
3129     case GLYPHLESS_GLYPH:
3130       n = ns_get_glyph_string_clip_rect (s, r);
3131       ns_focus (s->f, r, n);
3133       if (s->for_overlaps || (s->cmp_from > 0
3134                               && ! s->first_glyph->u.cmp.automatic))
3135         s->background_filled_p = 1;
3136       else
3137         ns_maybe_dumpglyphs_background
3138           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3139       /* ... */
3140       /* Not yet implemented.  */
3141       /* ... */
3142       ns_unfocus (s->f);
3143       break;
3145     default:
3146       abort ();
3147     }
3149   /* Draw box if not done already. */
3150   if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3151     {
3152       n = ns_get_glyph_string_clip_rect (s, r);
3153       ns_focus (s->f, r, n);
3154       ns_dumpglyphs_box_or_relief (s);
3155       ns_unfocus (s->f);
3156     }
3158   s->num_clips = 0;
3163 /* ==========================================================================
3165     Event loop
3167    ========================================================================== */
3170 static void
3171 ns_send_appdefined (int value)
3172 /* --------------------------------------------------------------------------
3173     Internal: post an appdefined event which EmacsApp-sendEvent will
3174               recognize and take as a command to halt the event loop.
3175    -------------------------------------------------------------------------- */
3177   /*NSTRACE (ns_send_appdefined); */
3179   /* Only post this event if we haven't already posted one.  This will end
3180        the [NXApp run] main loop after having processed all events queued at
3181        this moment.  */
3182   if (send_appdefined)
3183     {
3184       NSEvent *nxev;
3186       /* We only need one NX_APPDEFINED event to stop NXApp from running.  */
3187       send_appdefined = NO;
3189       /* Don't need wakeup timer any more */
3190       if (timed_entry)
3191         {
3192           [timed_entry invalidate];
3193           [timed_entry release];
3194           timed_entry = nil;
3195         }
3197       /* Ditto for file descriptor poller */
3198       if (fd_entry)
3199         {
3200           [fd_entry invalidate];
3201           [fd_entry release];
3202           fd_entry = nil;
3203         }
3205       nxev = [NSEvent otherEventWithType: NSApplicationDefined
3206                                 location: NSMakePoint (0, 0)
3207                            modifierFlags: 0
3208                                timestamp: 0
3209                             windowNumber: [[NSApp mainWindow] windowNumber]
3210                                  context: [NSApp context]
3211                                  subtype: 0
3212                                    data1: value
3213                                    data2: 0];
3215       /* Post an application defined event on the event queue.  When this is
3216          received the [NXApp run] will return, thus having processed all
3217          events which are currently queued.  */
3218       [NSApp postEvent: nxev atStart: NO];
3219     }
3223 static int
3224 ns_read_socket (struct terminal *terminal, int expected,
3225                 struct input_event *hold_quit)
3226 /* --------------------------------------------------------------------------
3227      External (hook): Post an event to ourself and keep reading events until
3228      we read it back again.  In effect process all events which were waiting.
3229      From 21+ we have to manage the event buffer ourselves.
3230    -------------------------------------------------------------------------- */
3232   struct input_event ev;
3233   int nevents;
3235 /* NSTRACE (ns_read_socket); */
3237   if (interrupt_input_blocked)
3238     {
3239       interrupt_input_pending = 1;
3240 #ifdef SYNC_INPUT
3241       pending_signals = 1;
3242 #endif
3243       return -1;
3244     }
3246   interrupt_input_pending = 0;
3247 #ifdef SYNC_INPUT
3248   pending_signals = pending_atimers;
3249 #endif
3251   BLOCK_INPUT;
3252   n_emacs_events_pending = 0;
3253   EVENT_INIT (ev);
3254   emacs_event = &ev;
3255   q_event_ptr = hold_quit;
3257   /* we manage autorelease pools by allocate/reallocate each time around
3258      the loop; strict nesting is occasionally violated but seems not to
3259      matter.. earlier methods using full nesting caused major memory leaks */
3260   [outerpool release];
3261   outerpool = [[NSAutoreleasePool alloc] init];
3263   /* If have pending open-file requests, attend to the next one of those. */
3264   if (ns_pending_files && [ns_pending_files count] != 0
3265       && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3266     {
3267       [ns_pending_files removeObjectAtIndex: 0];
3268     }
3269   /* Deal with pending service requests. */
3270   else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3271     && [(EmacsApp *)
3272          NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3273                       withArg: [ns_pending_service_args objectAtIndex: 0]])
3274     {
3275       [ns_pending_service_names removeObjectAtIndex: 0];
3276       [ns_pending_service_args removeObjectAtIndex: 0];
3277     }
3278   else
3279     {
3280       /* Run and wait for events.  We must always send one NX_APPDEFINED event
3281          to ourself, otherwise [NXApp run] will never exit.  */
3282       send_appdefined = YES;
3284       /* If called via ns_select, this is called once with expected=1,
3285          because we expect either the timeout or file descriptor activity.
3286          In this case the first event through will either be real input or
3287          one of these.  read_avail_input() then calls once more with expected=0
3288          and in that case we need to return quickly if there is nothing.
3289          If we're being called outside of that, it's also OK to return quickly
3290          after one iteration through the event loop, since other terms do
3291          this and emacs expects it. */
3292       if (!(inNsSelect && expected))
3293         {
3294           /* Post an application defined event on the event queue.  When this is
3295              received the [NXApp run] will return, thus having processed all
3296              events which are currently queued, if any.  */
3297           ns_send_appdefined (-1);
3298         }
3300       [NSApp run];
3301     }
3303   nevents = n_emacs_events_pending;
3304   n_emacs_events_pending = 0;
3305   emacs_event = q_event_ptr = NULL;
3306   UNBLOCK_INPUT;
3308   return nevents;
3313 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3314            fd_set *exceptfds, struct timeval *timeout)
3315 /* --------------------------------------------------------------------------
3316      Replacement for select, checking for events
3317    -------------------------------------------------------------------------- */
3319   int result;
3320   double time;
3321   NSEvent *ev;
3322 /*  NSTRACE (ns_select); */
3324   if (NSApp == nil || inNsSelect == 1 /* || ([NSApp isActive] == NO &&
3325                       [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
3326  inMode:NSDefaultRunLoopMode dequeue:NO] == nil) */)
3327     return select (nfds, readfds, writefds, exceptfds, timeout);
3329   /* Save file descriptor set, which gets overwritten in calls to select ()
3330      Note, this is called from process.c, and only readfds is ever set */
3331   if (readfds)
3332     {
3333       memcpy (&select_readfds, readfds, sizeof (fd_set));
3334       select_nfds = nfds;
3335     }
3336   else
3337     select_nfds = 0;
3339     /* Try an initial select for pending data on input files */
3340   select_timeout.tv_sec = select_timeout.tv_usec = 0;
3341   result = select (nfds, readfds, writefds, exceptfds, &select_timeout);
3342   if (result)
3343     return result;
3345   /* if (!timeout || timed_entry || fd_entry)
3346        fprintf (stderr, "assertion failed: timeout null or timed_entry/fd_entry non-null in ns_select\n"); */
3348     /* set a timeout and run the main AppKit event loop while continuing
3349        to monitor the files */
3350   time = ((double) timeout->tv_sec) + ((double) timeout->tv_usec)/1000000.0;
3351   timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3352                                            target: NSApp
3353                                          selector: @selector (timeout_handler:)
3354                                          userInfo: 0
3355                                           repeats: YES] /* for safe removal */
3356                                                          retain];
3358   /* set a periodic task to try the select () again */
3359   fd_entry = [[NSTimer scheduledTimerWithTimeInterval: 0.1
3360                                                target: NSApp
3361                                              selector: @selector (fd_handler:)
3362                                              userInfo: 0
3363                                               repeats: YES]
3364                retain];
3366   /* Let Application dispatch events until it receives an event of the type
3367      NX_APPDEFINED, which should only be sent by timeout_handler.
3368      We tell read_avail_input() that input is "expected" because we do expect
3369      either the timeout or fd handler to fire, and if they don't, the original
3370      call from process.c that got us here expects us to wait until some input
3371      comes. */
3372   inNsSelect = 1;
3373   gobble_input (1);
3374   ev = last_appdefined_event;
3375   inNsSelect = 0;
3377   if (ev)
3378     {
3379       int t;
3380       if ([ev type] != NSApplicationDefined)
3381         abort ();
3383       t = [ev data1];
3384       last_appdefined_event = 0;
3386       if (t == -2)
3387         {
3388           /* The NX_APPDEFINED event we received was a timeout. */
3389           return 0;
3390         }
3391       else if (t == -1)
3392         {
3393           /* The NX_APPDEFINED event we received was the result of
3394              at least one real input event arriving.  */
3395           errno = EINTR;
3396           return -1;
3397         }
3398       else
3399         {
3400           /* Received back from select () in fd_handler; copy the results */
3401           if (readfds)
3402             memcpy (readfds, &select_readfds, sizeof (fd_set));
3403           return t;
3404         }
3405     }
3406   /* never reached, shut compiler up */
3407   return 0;
3412 /* ==========================================================================
3414     Scrollbar handling
3416    ========================================================================== */
3419 static void
3420 ns_set_vertical_scroll_bar (struct window *window,
3421                            int portion, int whole, int position)
3422 /* --------------------------------------------------------------------------
3423       External (hook): Update or add scrollbar
3424    -------------------------------------------------------------------------- */
3426   Lisp_Object win;
3427   NSRect r, v;
3428   struct frame *f = XFRAME (WINDOW_FRAME (window));
3429   EmacsView *view = FRAME_NS_VIEW (f);
3430   int window_y, window_height;
3431   BOOL barOnVeryLeft, barOnVeryRight;
3432   int top, left, height, width, sb_width, sb_left;
3433   EmacsScroller *bar;
3434 static int count = 0;
3436   /* optimization; display engine sends WAY too many of these.. */
3437   if (!NILP (window->vertical_scroll_bar))
3438     {
3439       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3440       if ([bar checkSamePosition: position portion: portion whole: whole])
3441         {
3442           if (view->scrollbarsNeedingUpdate == 0)
3443             {
3444               if (!windows_or_buffers_changed)
3445                   return;
3446             }
3447           else
3448             view->scrollbarsNeedingUpdate--;
3449         }
3450     }
3452   NSTRACE (ns_set_vertical_scroll_bar);
3454   /* Get dimensions.  */
3455   window_box (window, -1, 0, &window_y, 0, &window_height);
3456   top = window_y;
3457   height = window_height;
3458   width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3459   left = WINDOW_SCROLL_BAR_AREA_X (window);
3461   if (top < 5) /* top scrollbar adjustment */
3462     {
3463       top -= FRAME_INTERNAL_BORDER_WIDTH (f);
3464       height += FRAME_INTERNAL_BORDER_WIDTH (f);
3465     }
3467   /* allow for displaying a skinnier scrollbar than char area allotted */
3468   sb_width = (WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) > 0) ?
3469     WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) : width;
3471   barOnVeryLeft = left < 5;
3472   barOnVeryRight = FRAME_PIXEL_WIDTH (f) - left - width < 5;
3473   sb_left = left + FRAME_INTERNAL_BORDER_WIDTH (f)
3474       * (barOnVeryLeft ? -1 : (barOnVeryRight ? 1 : 0));
3476   r = NSMakeRect (sb_left, top, sb_width, height);
3477   /* the parent view is flipped, so we need to flip y value */
3478   v = [view frame];
3479   r.origin.y = (v.size.height - r.size.height - r.origin.y);
3481   XSETWINDOW (win, window);
3482   BLOCK_INPUT;
3484   /* we want at least 5 lines to display a scrollbar */
3485   if (WINDOW_TOTAL_LINES (window) < 5)
3486     {
3487       if (!NILP (window->vertical_scroll_bar))
3488         {
3489           bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3490           [bar removeFromSuperview];
3491           window->vertical_scroll_bar = Qnil;
3492         }
3493       ns_clear_frame_area (f, sb_left, top, width, height);
3494       UNBLOCK_INPUT;
3495       return;
3496     }
3498   if (NILP (window->vertical_scroll_bar))
3499     {
3500       ns_clear_frame_area (f, sb_left, top, width, height);
3501       bar = [[EmacsScroller alloc] initFrame: r window: win];
3502       window->vertical_scroll_bar = make_save_value (bar, 0);
3503     }
3504   else
3505     {
3506       NSRect oldRect;
3507       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3508       oldRect = [bar frame];
3509       r.size.width = oldRect.size.width;
3510       if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3511         {
3512           if (oldRect.origin.x != r.origin.x)
3513               ns_clear_frame_area (f, sb_left, top, width, height);
3514           [bar setFrame: r];
3515         }
3516     }
3518   [bar setPosition: position portion: portion whole: whole];
3519   UNBLOCK_INPUT;
3523 static void
3524 ns_condemn_scroll_bars (struct frame *f)
3525 /* --------------------------------------------------------------------------
3526      External (hook): arrange for all frame's scrollbars to be removed
3527      at next call to judge_scroll_bars, except for those redeemed.
3528    -------------------------------------------------------------------------- */
3530   int i;
3531   id view;
3532   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3534   NSTRACE (ns_condemn_scroll_bars);
3536   for (i =[subviews count]-1; i >= 0; i--)
3537     {
3538       view = [subviews objectAtIndex: i];
3539       if ([view isKindOfClass: [EmacsScroller class]])
3540         [view condemn];
3541     }
3545 static void
3546 ns_redeem_scroll_bar (struct window *window)
3547 /* --------------------------------------------------------------------------
3548      External (hook): arrange to spare this window's scrollbar
3549      at next call to judge_scroll_bars.
3550    -------------------------------------------------------------------------- */
3552   id bar;
3553   NSTRACE (ns_redeem_scroll_bar);
3554   if (!NILP (window->vertical_scroll_bar))
3555     {
3556       bar =XNS_SCROLL_BAR (window->vertical_scroll_bar);
3557       [bar reprieve];
3558     }
3562 static void
3563 ns_judge_scroll_bars (struct frame *f)
3564 /* --------------------------------------------------------------------------
3565      External (hook): destroy all scrollbars on frame that weren't
3566      redeemed after call to condemn_scroll_bars.
3567    -------------------------------------------------------------------------- */
3569   int i;
3570   id view;
3571   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3572   NSTRACE (ns_judge_scroll_bars);
3573   for (i =[subviews count]-1; i >= 0; i--)
3574     {
3575       view = [subviews objectAtIndex: i];
3576       if (![view isKindOfClass: [EmacsScroller class]]) continue;
3577       [view judge];
3578     }
3582 void
3583 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
3585   /* XXX irrelevant under NS */
3590 /* ==========================================================================
3592     Initialization
3594    ========================================================================== */
3597 x_display_pixel_height (struct ns_display_info *dpyinfo)
3599   NSScreen *screen = [NSScreen mainScreen];
3600   return [screen frame].size.height;
3604 x_display_pixel_width (struct ns_display_info *dpyinfo)
3606   NSScreen *screen = [NSScreen mainScreen];
3607   return [screen frame].size.width;
3611 static Lisp_Object ns_string_to_lispmod (const char *s)
3612 /* --------------------------------------------------------------------------
3613      Convert modifier name to lisp symbol
3614    -------------------------------------------------------------------------- */
3616   if (!strncmp (SDATA (SYMBOL_NAME (Qmeta)), s, 10))
3617     return Qmeta;
3618   else if (!strncmp (SDATA (SYMBOL_NAME (Qsuper)), s, 10))
3619     return Qsuper;
3620   else if (!strncmp (SDATA (SYMBOL_NAME (Qcontrol)), s, 10))
3621     return Qcontrol;
3622   else if (!strncmp (SDATA (SYMBOL_NAME (Qalt)), s, 10))
3623     return Qalt;
3624   else if (!strncmp (SDATA (SYMBOL_NAME (Qhyper)), s, 10))
3625     return Qhyper;
3626   else if (!strncmp (SDATA (SYMBOL_NAME (Qnone)), s, 10))
3627     return Qnone;
3628   else
3629     return Qnil;
3633 static Lisp_Object ns_mod_to_lisp (int m)
3634 /* --------------------------------------------------------------------------
3635      Convert modifier code (see lisp.h) to lisp symbol
3636    -------------------------------------------------------------------------- */
3638   if (m == CHAR_META)
3639     return Qmeta;
3640   else if (m == CHAR_SUPER)
3641     return Qsuper;
3642   else if (m == CHAR_CTL)
3643     return Qcontrol;
3644   else if (m == CHAR_ALT)
3645     return Qalt;
3646   else if (m == CHAR_HYPER)
3647     return Qhyper;
3648   else /* if (m == 0) */
3649     return Qnone;
3653 static void
3654 ns_default (const char *parameter, Lisp_Object *result,
3655            Lisp_Object yesval, Lisp_Object noval,
3656            BOOL is_float, BOOL is_modstring)
3657 /* --------------------------------------------------------------------------
3658       Check a parameter value in user's preferences
3659    -------------------------------------------------------------------------- */
3661   const char *value;
3663   if ( (value =[[[NSUserDefaults standardUserDefaults]
3664                    stringForKey: [NSString stringWithUTF8String: parameter]]
3665                 UTF8String]) )
3666     {
3667       double f;
3668       char *pos;
3669       if (strcasecmp (value, "YES") == 0)
3670         *result = yesval;
3671       else if (strcasecmp (value, "NO") == 0)
3672         *result = noval;
3673       else if (is_float && (f = strtod (value, &pos), pos != value))
3674         *result = make_float (f);
3675       else if (is_modstring && value)
3676         *result = ns_string_to_lispmod (value);
3677       else fprintf (stderr,
3678                    "Bad value for default \"%s\": \"%s\"\n", parameter, value);
3679     }
3683 void
3684 ns_initialize_display_info (struct ns_display_info *dpyinfo)
3685 /* --------------------------------------------------------------------------
3686       Initialize global info and storage for display.
3687    -------------------------------------------------------------------------- */
3689     NSScreen *screen = [NSScreen mainScreen];
3690     NSWindowDepth depth = [screen depth];
3691     Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
3693     dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
3694     dpyinfo->resy = 72.27;
3695     dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
3696                                                   NSColorSpaceFromDepth (depth)]
3697                 && ![NSCalibratedWhiteColorSpace isEqualToString:
3698                                                  NSColorSpaceFromDepth (depth)];
3699     dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
3700     dpyinfo->image_cache = make_image_cache ();
3701     dpyinfo->color_table
3702       = (struct ns_color_table *)xmalloc (sizeof (struct ns_color_table));
3703     dpyinfo->color_table->colors = NULL;
3704     dpyinfo->root_window = 42; /* a placeholder.. */
3706     hlinfo->mouse_face_mouse_frame = NULL;
3707     hlinfo->mouse_face_deferred_gc = 0;
3708     hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
3709     hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
3710     hlinfo->mouse_face_face_id = DEFAULT_FACE_ID;
3711     hlinfo->mouse_face_window = hlinfo->mouse_face_overlay = Qnil;
3712     hlinfo->mouse_face_hidden = 0;
3714     hlinfo->mouse_face_mouse_x = hlinfo->mouse_face_mouse_y = 0;
3715     hlinfo->mouse_face_defer = 0;
3717     dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
3719     dpyinfo->n_fonts = 0;
3720     dpyinfo->smallest_font_height = 1;
3721     dpyinfo->smallest_char_width = 1;
3725 /* This and next define (many of the) public functions in this file. */
3726 /* x_... are generic versions in xdisp.c that we, and other terms, get away
3727          with using despite presence in the "system dependent" redisplay
3728          interface.  In addition, many of the ns_ methods have code that is
3729          shared with all terms, indicating need for further refactoring. */
3730 extern frame_parm_handler ns_frame_parm_handlers[];
3731 static struct redisplay_interface ns_redisplay_interface =
3733   ns_frame_parm_handlers,
3734   x_produce_glyphs,
3735   x_write_glyphs,
3736   x_insert_glyphs,
3737   x_clear_end_of_line,
3738   ns_scroll_run,
3739   ns_after_update_window_line,
3740   ns_update_window_begin,
3741   ns_update_window_end,
3742   x_cursor_to,
3743   ns_flush,
3744   0, /* flush_display_optional */
3745   x_clear_window_mouse_face,
3746   x_get_glyph_overhangs,
3747   x_fix_overlapping_area,
3748   ns_draw_fringe_bitmap,
3749   0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
3750   0, /* destroy_fringe_bitmap */
3751   ns_compute_glyph_string_overhangs,
3752   ns_draw_glyph_string, /* interface to nsfont.m */
3753   ns_define_frame_cursor,
3754   ns_clear_frame_area,
3755   ns_draw_window_cursor,
3756   ns_draw_vertical_window_border,
3757   ns_shift_glyphs_for_insert
3761 static void
3762 ns_delete_display (struct ns_display_info *dpyinfo)
3764   /* TODO... */
3768 /* This function is called when the last frame on a display is deleted. */
3769 static void
3770 ns_delete_terminal (struct terminal *terminal)
3772   struct ns_display_info *dpyinfo = terminal->display_info.ns;
3773   int i;
3775   /* Protect against recursive calls.  delete_frame in
3776      delete_terminal calls us back when it deletes our last frame.  */
3777   if (!terminal->name)
3778     return;
3780   BLOCK_INPUT;
3782   x_destroy_all_bitmaps (dpyinfo);
3783   ns_delete_display (dpyinfo);
3784   UNBLOCK_INPUT;
3788 static struct terminal *
3789 ns_create_terminal (struct ns_display_info *dpyinfo)
3790 /* --------------------------------------------------------------------------
3791       Set up use of NS before we make the first connection.
3792    -------------------------------------------------------------------------- */
3794   struct terminal *terminal;
3796   NSTRACE (ns_create_terminal);
3798   terminal = create_terminal ();
3800   terminal->type = output_ns;
3801   terminal->display_info.ns = dpyinfo;
3802   dpyinfo->terminal = terminal;
3804   terminal->rif = &ns_redisplay_interface;
3806   terminal->clear_frame_hook = ns_clear_frame;
3807   terminal->ins_del_lines_hook = 0; /* XXX vestigial? */
3808   terminal->delete_glyphs_hook = 0; /* XXX vestigial? */
3809   terminal->ring_bell_hook = ns_ring_bell;
3810   terminal->reset_terminal_modes_hook = ns_reset_terminal_modes;
3811   terminal->set_terminal_modes_hook = ns_set_terminal_modes;
3812   terminal->update_begin_hook = ns_update_begin;
3813   terminal->update_end_hook = ns_update_end;
3814   terminal->set_terminal_window_hook = NULL; /* XXX vestigial? */
3815   terminal->read_socket_hook = ns_read_socket;
3816   terminal->frame_up_to_date_hook = ns_frame_up_to_date;
3817   terminal->mouse_position_hook = ns_mouse_position;
3818   terminal->frame_rehighlight_hook = ns_frame_rehighlight;
3819   terminal->frame_raise_lower_hook = ns_frame_raise_lower;
3821   terminal->fullscreen_hook = 0; /* see XTfullscreen_hook */
3823   terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
3824   terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
3825   terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
3826   terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
3828   terminal->delete_frame_hook = x_destroy_window;
3829   terminal->delete_terminal_hook = ns_delete_terminal;
3831   terminal->scroll_region_ok = 1;
3832   terminal->char_ins_del_ok = 1;
3833   terminal->line_ins_del_ok = 1;
3834   terminal->fast_clear_end_of_line = 1;
3835   terminal->memory_below_frame = 0;
3837   return terminal;
3841 struct ns_display_info *
3842 ns_term_init (Lisp_Object display_name)
3843 /* --------------------------------------------------------------------------
3844      Start the Application and get things rolling.
3845    -------------------------------------------------------------------------- */
3847   struct terminal *terminal;
3848   struct ns_display_info *dpyinfo;
3849   static int ns_initialized = 0;
3850   Lisp_Object tmp;
3852   NSTRACE (ns_term_init);
3854   /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
3855   /*GSDebugAllocationActive (YES); */
3856   BLOCK_INPUT;
3857   handling_signal = 0;
3859   if (!ns_initialized)
3860     {
3861       baud_rate = 38400;
3862       Fset_input_interrupt_mode (Qnil);
3863       ns_initialized = 1;
3864     }
3866   ns_pending_files = [[NSMutableArray alloc] init];
3867   ns_pending_service_names = [[NSMutableArray alloc] init];
3868   ns_pending_service_args = [[NSMutableArray alloc] init];
3870   /* Start app and create the main menu, window, view.
3871      Needs to be here because ns_initialize_display_info () uses AppKit classes.
3872      The view will then ask the NSApp to stop and return to Emacs. */
3873   [EmacsApp sharedApplication];
3874   if (NSApp == nil)
3875     return NULL;
3876   [NSApp setDelegate: NSApp];
3878   /* debugging: log all notifications */
3879   /*   [[NSNotificationCenter defaultCenter] addObserver: NSApp
3880                                          selector: @selector (logNotification:)
3881                                              name: nil object: nil]; */
3883   dpyinfo = (struct ns_display_info *)xmalloc (sizeof (struct ns_display_info));
3884   memset (dpyinfo, 0, sizeof (struct ns_display_info));
3886   ns_initialize_display_info (dpyinfo);
3887   terminal = ns_create_terminal (dpyinfo);
3889   terminal->kboard = (KBOARD *) xmalloc (sizeof (KBOARD));
3890   init_kboard (terminal->kboard);
3891   KVAR (terminal->kboard, Vwindow_system) = Qns;
3892   terminal->kboard->next_kboard = all_kboards;
3893   all_kboards = terminal->kboard;
3894   /* Don't let the initial kboard remain current longer than necessary.
3895      That would cause problems if a file loaded on startup tries to
3896      prompt in the mini-buffer.  */
3897   if (current_kboard == initial_kboard)
3898     current_kboard = terminal->kboard;
3899   terminal->kboard->reference_count++;
3901   dpyinfo->next = x_display_list;
3902   x_display_list = dpyinfo;
3904   /* Put it on ns_display_name_list */
3905   ns_display_name_list = Fcons (Fcons (display_name, Qnil),
3906                                 ns_display_name_list);
3907   dpyinfo->name_list_element = XCAR (ns_display_name_list);
3909   /* Set the name of the terminal. */
3910   terminal->name = (char *) xmalloc (SBYTES (display_name) + 1);
3911   strncpy (terminal->name, SDATA (display_name), SBYTES (display_name));
3912   terminal->name[SBYTES (display_name)] = 0;
3914   UNBLOCK_INPUT;
3916   if (!inhibit_x_resources)
3917     {
3918       ns_default ("GSFontAntiAlias", &ns_antialias_text,
3919                  Qt, Qnil, NO, NO);
3920       tmp = Qnil;
3921       /* this is a standard variable */
3922       ns_default ("AppleAntiAliasingThreshold", &tmp,
3923                  make_float (10.0), make_float (6.0), YES, NO);
3924       ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
3925     }
3927   ns_selection_color = [[NSUserDefaults standardUserDefaults]
3928                          stringForKey: @"AppleHighlightColor"];
3929   if (ns_selection_color == nil)
3930     ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
3932   {
3933     NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
3935     if ( cl == nil )
3936       {
3937         Lisp_Object color_file, color_map, color;
3938         int r,g,b;
3939         unsigned long c;
3940         char *name;
3942         color_file = Fexpand_file_name (build_string ("rgb.txt"),
3943                          Fsymbol_value (intern ("data-directory")));
3944         if (NILP (Ffile_readable_p (color_file)))
3945           fatal ("Could not find %s.\n", SDATA (color_file));
3947         color_map = Fx_load_color_file (color_file);
3948         if (NILP (color_map))
3949           fatal ("Could not read %s.\n", SDATA (color_file));
3951         cl = [[NSColorList alloc] initWithName: @"Emacs"];
3952         for ( ; CONSP (color_map); color_map = XCDR (color_map))
3953           {
3954             color = XCAR (color_map);
3955             name = SDATA (XCAR (color));
3956             c = XINT (XCDR (color));
3957             [cl setColor:
3958                   [NSColor colorWithCalibratedRed: RED_FROM_ULONG (c) / 255.0
3959                                             green: GREEN_FROM_ULONG (c) / 255.0
3960                                              blue: BLUE_FROM_ULONG (c) / 255.0
3961                                             alpha: 1.0]
3962                   forKey: [NSString stringWithUTF8String: name]];
3963           }
3964         [cl writeToFile: nil];
3965       }
3966   }
3968   {
3969     char c[128];
3970 #ifdef NS_IMPL_GNUSTEP
3971     strncpy (c, gnustep_base_version, sizeof (c));
3972 #else
3973     /*PSnextrelease (128, c); */
3974     snprintf (c, sizeof (c), "%g", NSAppKitVersionNumber);
3975 #endif
3976     Vwindow_system_version = build_string (c);
3977   }
3979   delete_keyboard_wait_descriptor (0);
3981   ns_app_name = [[NSProcessInfo processInfo] processName];
3983 /* Set up OS X app menu */
3984 #ifdef NS_IMPL_COCOA
3985   {
3986     NSMenu *appMenu;
3987     NSMenuItem *item;
3988     /* set up the application menu */
3989     svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
3990     [svcsMenu setAutoenablesItems: NO];
3991     appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
3992     [appMenu setAutoenablesItems: NO];
3993     mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
3994     dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
3996     [appMenu insertItemWithTitle: @"About Emacs"
3997                           action: @selector (orderFrontStandardAboutPanel:)
3998                    keyEquivalent: @""
3999                          atIndex: 0];
4000     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4001     [appMenu insertItemWithTitle: @"Preferences..."
4002                           action: @selector (showPreferencesWindow:)
4003                    keyEquivalent: @","
4004                          atIndex: 2];
4005     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4006     item = [appMenu insertItemWithTitle: @"Services"
4007                                  action: @selector (menuDown:)
4008                           keyEquivalent: @""
4009                                 atIndex: 4];
4010     [appMenu setSubmenu: svcsMenu forItem: item];
4011     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4012     [appMenu insertItemWithTitle: @"Hide Emacs"
4013                           action: @selector (hide:)
4014                    keyEquivalent: @"h"
4015                          atIndex: 6];
4016     item =  [appMenu insertItemWithTitle: @"Hide Others"
4017                           action: @selector (hideOtherApplications:)
4018                    keyEquivalent: @"h"
4019                          atIndex: 7];
4020     [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4021     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4022     [appMenu insertItemWithTitle: @"Quit Emacs"
4023                           action: @selector (terminate:)
4024                    keyEquivalent: @"q"
4025                          atIndex: 9];
4027     item = [mainMenu insertItemWithTitle: ns_app_name
4028                                   action: @selector (menuDown:)
4029                            keyEquivalent: @""
4030                                  atIndex: 0];
4031     [mainMenu setSubmenu: appMenu forItem: item];
4032     [dockMenu insertItemWithTitle: @"New Frame"
4033                            action: @selector (newFrame:)
4034                     keyEquivalent: @""
4035                           atIndex: 0];
4037     [NSApp setMainMenu: mainMenu];
4038     [NSApp setAppleMenu: appMenu];
4039     [NSApp setServicesMenu: svcsMenu];
4040     /* Needed at least on Cocoa, to get dock menu to show windows */
4041     [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4042   }
4043 #endif /* MAC OS X menu setup */
4045   [NSApp run];
4047   return dpyinfo;
4051 void
4052 ns_term_shutdown (int sig)
4054   /* code not reached in emacs.c after this is called by shut_down_emacs: */
4055   if (STRINGP (Vauto_save_list_file_name))
4056     unlink (SDATA (Vauto_save_list_file_name));
4058   if (sig == 0 || sig == SIGTERM)
4059     {
4060       [NSApp terminate: NSApp];
4061     }
4062   else // force a stack trace to happen
4063     {
4064       abort();
4065     }
4069 /* ==========================================================================
4071     EmacsApp implementation
4073    ========================================================================== */
4076 @implementation EmacsApp
4078 - (void)logNotification: (NSNotification *)notification
4080   const char *name = [[notification name] UTF8String];
4081   if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4082       && !strstr (name, "WindowNumber"))
4083     NSLog (@"notification: '%@'", [notification name]);
4087 - (void)sendEvent: (NSEvent *)theEvent
4088 /* --------------------------------------------------------------------------
4089      Called when NSApp is running for each event received.  Used to stop
4090      the loop when we choose, since there's no way to just run one iteration.
4091    -------------------------------------------------------------------------- */
4093   int type = [theEvent type];
4094   NSWindow *window = [theEvent window];
4095 /*  NSTRACE (sendEvent); */
4096 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4098   if (type == NSCursorUpdate && window == nil)
4099     {
4100       fprintf (stderr, "Dropping external cursor update event.\n");
4101       return;
4102     }
4104 #ifdef NS_IMPL_COCOA
4105   /* pass mouse down in resize handle and subsequent drags directly to
4106      EmacsWindow so we can generate continuous redisplays */
4107   if (ns_in_resize)
4108     {
4109       if (type == NSLeftMouseDragged)
4110         {
4111           [window mouseDragged: theEvent];
4112           return;
4113         }
4114       else if (type == NSLeftMouseUp)
4115         {
4116           [window mouseUp: theEvent];
4117           return;
4118         }
4119     }
4120   else if (type == NSLeftMouseDown)
4121     {
4122       NSRect r = ns_resize_handle_rect (window);
4123       if (NSPointInRect ([theEvent locationInWindow], r))
4124         {
4125           ns_in_resize = YES;
4126           [window mouseDown: theEvent];
4127           return;
4128         }
4129     }
4130 #endif
4132   if (type == NSApplicationDefined)
4133     {
4134       /* Events posted by ns_send_appdefined interrupt the run loop here.
4135          But, if a modal window is up, an appdefined can still come through,
4136          (e.g., from a makeKeyWindow event) but stopping self also stops the
4137          modal loop. Just defer it until later. */
4138       if ([NSApp modalWindow] == nil)
4139         {
4140           last_appdefined_event = theEvent;
4141           [self stop: self];
4142         }
4143       else
4144         {
4145           send_appdefined = YES;
4146         }
4147     }
4149   [super sendEvent: theEvent];
4153 - (void)showPreferencesWindow: (id)sender
4155   struct frame *emacsframe = SELECTED_FRAME ();
4156   NSEvent *theEvent = [NSApp currentEvent];
4158   if (!emacs_event)
4159     return;
4160   emacs_event->kind = NS_NONKEY_EVENT;
4161   emacs_event->code = KEY_NS_SHOW_PREFS;
4162   emacs_event->modifiers = 0;
4163   EV_TRAILER (theEvent);
4167 - (void)newFrame: (id)sender
4169   struct frame *emacsframe = SELECTED_FRAME ();
4170   NSEvent *theEvent = [NSApp currentEvent];
4172   if (!emacs_event)
4173     return;
4174   emacs_event->kind = NS_NONKEY_EVENT;
4175   emacs_event->code = KEY_NS_NEW_FRAME;
4176   emacs_event->modifiers = 0;
4177   EV_TRAILER (theEvent);
4181 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4182 - (BOOL) openFile: (NSString *)fileName
4184   struct frame *emacsframe = SELECTED_FRAME ();
4185   NSEvent *theEvent = [NSApp currentEvent];
4187   if (!emacs_event)
4188     return NO;
4190   emacs_event->kind = NS_NONKEY_EVENT;
4191   emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4192   ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4193   ns_input_line = Qnil; /* can be start or cons start,end */
4194   emacs_event->modifiers =0;
4195   EV_TRAILER (theEvent);
4197   return YES;
4201 /* **************************************************************************
4203       EmacsApp delegate implementation
4205    ************************************************************************** */
4207 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4208 /* --------------------------------------------------------------------------
4209      When application is loaded, terminate event loop in ns_term_init
4210    -------------------------------------------------------------------------- */
4212   NSTRACE (applicationDidFinishLaunching);
4213   [NSApp setServicesProvider: NSApp];
4214   ns_send_appdefined (-2);
4218 /* Termination sequences:
4219     C-x C-c:
4220     Cmd-Q:
4221     MenuBar | File | Exit:
4222     Select Quit from App menubar:
4223         -terminate
4224         KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4225         ns_term_shutdown()
4227     Select Quit from Dock menu:
4228     Logout attempt:
4229         -appShouldTerminate
4230           Cancel -> Nothing else
4231           Accept ->
4233           -terminate
4234           KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4235           ns_term_shutdown()
4239 - (void) terminate: (id)sender
4241   struct frame *emacsframe = SELECTED_FRAME ();
4243   if (!emacs_event)
4244     return;
4246   emacs_event->kind = NS_NONKEY_EVENT;
4247   emacs_event->code = KEY_NS_POWER_OFF;
4248   emacs_event->arg = Qt; /* mark as non-key event */
4249   EV_TRAILER ((id)nil);
4253 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4255   int ret;
4257   if (NILP (ns_confirm_quit)) //   || ns_shutdown_properly  --> TO DO
4258     return NSTerminateNow;
4260     ret = NSRunAlertPanel(ns_app_name,
4261                           [NSString stringWithUTF8String:"Exit requested.  Would you like to Save Buffers and Exit, or Cancel the request?"],
4262                           @"Save Buffers and Exit", @"Cancel", nil);
4264     if (ret == NSAlertDefaultReturn)
4265         return NSTerminateNow;
4266     else if (ret == NSAlertAlternateReturn)
4267         return NSTerminateCancel;
4268     return NSTerminateNow;  /* just in case */
4272 /*   Notification from the Workspace to open a file */
4273 - (BOOL)application: sender openFile: (NSString *)file
4275   [ns_pending_files addObject: file];
4276   return YES;
4280 /*   Open a file as a temporary file */
4281 - (BOOL)application: sender openTempFile: (NSString *)file
4283   [ns_pending_files addObject: file];
4284   return YES;
4288 /*   Notification from the Workspace to open a file noninteractively (?) */
4289 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4291   [ns_pending_files addObject: file];
4292   return YES;
4296 /*   Notification from the Workspace to open multiple files */
4297 - (void)application: sender openFiles: (NSArray *)fileList
4299   NSEnumerator *files = [fileList objectEnumerator];
4300   NSString *file;
4301   while ((file = [files nextObject]) != nil)
4302     [ns_pending_files addObject: file];
4304   [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4309 /* Handle dock menu requests.  */
4310 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4312   return dockMenu;
4316 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4317 - (void)applicationWillBecomeActive: (NSNotification *)notification
4319   //ns_app_active=YES;
4321 - (void)applicationDidBecomeActive: (NSNotification *)notification
4323   NSTRACE (applicationDidBecomeActive);
4325   //ns_app_active=YES;
4327   ns_update_auto_hide_menu_bar ();
4328   // No constrining takes place when the application is not active.
4329   ns_constrain_all_frames ();
4331 - (void)applicationDidResignActive: (NSNotification *)notification
4333   //ns_app_active=NO;
4334   ns_send_appdefined (-1);
4339 /* ==========================================================================
4341     EmacsApp aux handlers for managing event loop
4343    ========================================================================== */
4346 - (void)timeout_handler: (NSTimer *)timedEntry
4347 /* --------------------------------------------------------------------------
4348      The timeout specified to ns_select has passed.
4349    -------------------------------------------------------------------------- */
4351   /*NSTRACE (timeout_handler); */
4352   ns_send_appdefined (-2);
4355 - (void)fd_handler: (NSTimer *) fdEntry
4356 /* --------------------------------------------------------------------------
4357      Check data waiting on file descriptors and terminate if so
4358    -------------------------------------------------------------------------- */
4360   int result;
4361   /* NSTRACE (fd_handler); */
4363   if (select_nfds == 0)
4364     return;
4366   memcpy (&t_readfds, &select_readfds, sizeof (fd_set));
4368   select_timeout.tv_sec = select_timeout.tv_usec = 0;
4369   result = select (select_nfds, &t_readfds, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
4370                   &select_timeout);
4371   if (result)
4372     {
4373       memcpy (&select_readfds, &t_readfds, sizeof (fd_set));
4374       ns_send_appdefined (result);
4375     }
4380 /* ==========================================================================
4382     Service provision
4384    ========================================================================== */
4386 /* called from system: queue for next pass through event loop */
4387 - (void)requestService: (NSPasteboard *)pboard
4388               userData: (NSString *)userData
4389                  error: (NSString **)error
4391   [ns_pending_service_names addObject: userData];
4392   [ns_pending_service_args addObject: [NSString stringWithUTF8String:
4393       SDATA (ns_string_from_pasteboard (pboard))]];
4397 /* called from ns_read_socket to clear queue */
4398 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
4400   struct frame *emacsframe = SELECTED_FRAME ();
4401   NSEvent *theEvent = [NSApp currentEvent];
4403   if (!emacs_event)
4404     return NO;
4406   emacs_event->kind = NS_NONKEY_EVENT;
4407   emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
4408   ns_input_spi_name = build_string ([name UTF8String]);
4409   ns_input_spi_arg = build_string ([arg UTF8String]);
4410   emacs_event->modifiers = EV_MODIFIERS (theEvent);
4411   EV_TRAILER (theEvent);
4413   return YES;
4417 @end  /* EmacsApp */
4421 /* ==========================================================================
4423     EmacsView implementation
4425    ========================================================================== */
4428 @implementation EmacsView
4430 /* needed to inform when window closed from LISP */
4431 - (void) setWindowClosing: (BOOL)closing
4433   windowClosing = closing;
4437 - (void)dealloc
4439   NSTRACE (EmacsView_dealloc);
4440   [toolbar release];
4441   [super dealloc];
4445 /* called on font panel selection */
4446 - (void)changeFont: (id)sender
4448   NSEvent *e =[[self window] currentEvent];
4449   struct face *face =FRAME_DEFAULT_FACE (emacsframe);
4450   id newFont;
4451   float size;
4453   NSTRACE (changeFont);
4454   if (!emacs_event)
4455     return;
4457   if (newFont = [sender convertFont:
4458                            ((struct nsfont_info *)face->font)->nsfont])
4459     {
4460       SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
4462       emacs_event->kind = NS_NONKEY_EVENT;
4463       emacs_event->modifiers = 0;
4464       emacs_event->code = KEY_NS_CHANGE_FONT;
4466       size = [newFont pointSize];
4467       ns_input_fontsize = make_number (lrint (size));
4468       ns_input_font = build_string ([[newFont familyName] UTF8String]);
4469       EV_TRAILER (e);
4470     }
4474 - (BOOL)acceptsFirstResponder
4476   NSTRACE (acceptsFirstResponder);
4477   return YES;
4481 - (void)resetCursorRects
4483   NSRect visible = [self visibleRect];
4484   NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
4485   NSTRACE (resetCursorRects);
4487   if (currentCursor == nil)
4488     currentCursor = [NSCursor arrowCursor];
4490   if (!NSIsEmptyRect (visible))
4491     [self addCursorRect: visible cursor: currentCursor];
4492   [currentCursor setOnMouseEntered: YES];
4497 /*****************************************************************************/
4498 /* Keyboard handling. */
4499 #define NS_KEYLOG 0
4501 - (void)keyDown: (NSEvent *)theEvent
4503   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
4504   int code;
4505   unsigned fnKeysym = 0;
4506   int flags;
4507   static NSMutableArray *nsEvArray;
4508   static BOOL firstTime = YES;
4509   int left_is_none;
4511   NSTRACE (keyDown);
4513   /* Rhapsody and OS X give up and down events for the arrow keys */
4514   if (ns_fake_keydown == YES)
4515     ns_fake_keydown = NO;
4516   else if ([theEvent type] != NSKeyDown)
4517     return;
4519   if (!emacs_event)
4520     return;
4522  if (![[self window] isKeyWindow]
4523      && [[theEvent window] isKindOfClass: [EmacsWindow class]]
4524      /* we must avoid an infinite loop here. */
4525      && (EmacsView *)[[theEvent window] delegate] != self)
4526    {
4527      /* XXX: There is an occasional condition in which, when Emacs display
4528          updates a different frame from the current one, and temporarily
4529          selects it, then processes some interrupt-driven input
4530          (dispnew.c:3878), OS will send the event to the correct NSWindow, but
4531          for some reason that window has its first responder set to the NSView
4532          most recently updated (I guess), which is not the correct one. */
4533      [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
4534      return;
4535    }
4537   if (nsEvArray == nil)
4538     nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
4540   [NSCursor setHiddenUntilMouseMoves: YES];
4542   if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
4543     {
4544       clear_mouse_face (hlinfo);
4545       hlinfo->mouse_face_hidden = 1;
4546     }
4548   if (!processingCompose)
4549     {
4550       code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
4551         0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
4552       /* (Carbon way: [theEvent keyCode]) */
4554       /* is it a "function key"? */
4555       fnKeysym = ns_convert_key (code);
4556       if (fnKeysym)
4557         {
4558           /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
4559              because Emacs treats Delete and KP-Delete same (in simple.el). */
4560           if (fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
4561             code = 0xFF08; /* backspace */
4562           else
4563             code = fnKeysym;
4564         }
4566       /* are there modifiers? */
4567       emacs_event->modifiers = 0;
4568       flags = [theEvent modifierFlags];
4570       if (flags & NSHelpKeyMask)
4571           emacs_event->modifiers |= hyper_modifier;
4573       if (flags & NSShiftKeyMask)
4574         emacs_event->modifiers |= shift_modifier;
4576       if ((flags & NSRightCommandKeyMask) == NSRightCommandKeyMask)
4577         emacs_event->modifiers |= parse_solitary_modifier
4578           (EQ (ns_right_command_modifier, Qleft)
4579            ? ns_command_modifier
4580            : ns_right_command_modifier);
4582       if ((flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask)
4583         {
4584           emacs_event->modifiers |= parse_solitary_modifier
4585             (ns_command_modifier);
4587           /* if super (default), take input manager's word so things like
4588              dvorak / qwerty layout work */
4589           if (EQ (ns_command_modifier, Qsuper)
4590               && !fnKeysym
4591               && [[theEvent characters] length] != 0)
4592             {
4593               /* XXX: the code we get will be unshifted, so if we have
4594                  a shift modifier, must convert ourselves */
4595               if (!(flags & NSShiftKeyMask))
4596                 code = [[theEvent characters] characterAtIndex: 0];
4597 #if 0
4598               /* this is ugly and also requires linking w/Carbon framework
4599                  (for LMGetKbdType) so for now leave this rare (?) case
4600                  undealt with.. in future look into CGEvent methods */
4601               else
4602                 {
4603                   long smv = GetScriptManagerVariable (smKeyScript);
4604                   Handle uchrHandle = GetResource
4605                     ('uchr', GetScriptVariable (smv, smScriptKeys));
4606                   UInt32 dummy = 0;
4607                   UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
4608                                  [[theEvent characters] characterAtIndex: 0],
4609                                  kUCKeyActionDisplay,
4610                                  (flags & ~NSCommandKeyMask) >> 8,
4611                                  LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
4612                                  &dummy, 1, &dummy, &code);
4613                   code &= 0xFF;
4614                 }
4615 #endif
4616             }
4617         }
4619       if ((flags & NSRightControlKeyMask) == NSRightControlKeyMask)
4620           emacs_event->modifiers |= parse_solitary_modifier
4621               (EQ (ns_right_control_modifier, Qleft)
4622                ? ns_control_modifier
4623                : ns_right_control_modifier);
4625       if ((flags & NSLeftControlKeyMask) == NSLeftControlKeyMask)
4626         emacs_event->modifiers |= parse_solitary_modifier
4627           (ns_control_modifier);
4629       if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
4630           emacs_event->modifiers |=
4631             parse_solitary_modifier (ns_function_modifier);
4633       left_is_none = NILP (ns_alternate_modifier)
4634         || EQ (ns_alternate_modifier, Qnone);
4636       if ((flags & NSRightAlternateKeyMask) == NSRightAlternateKeyMask)
4637         {
4638           if ((NILP (ns_right_alternate_modifier)
4639                || EQ (ns_right_alternate_modifier, Qnone)
4640                || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
4641               && !fnKeysym)
4642             {   /* accept pre-interp alt comb */
4643               if ([[theEvent characters] length] > 0)
4644                 code = [[theEvent characters] characterAtIndex: 0];
4645               /*HACK: clear lone shift modifier to stop next if from firing */
4646               if (emacs_event->modifiers == shift_modifier)
4647                 emacs_event->modifiers = 0;
4648             }
4649           else
4650             emacs_event->modifiers |= parse_solitary_modifier
4651               (EQ (ns_right_alternate_modifier, Qleft)
4652                ? ns_alternate_modifier
4653                : ns_right_alternate_modifier);
4654         }
4656       if ((flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask) /* default = meta */
4657         {
4658           if (left_is_none && !fnKeysym)
4659             {   /* accept pre-interp alt comb */
4660               if ([[theEvent characters] length] > 0)
4661                 code = [[theEvent characters] characterAtIndex: 0];
4662               /*HACK: clear lone shift modifier to stop next if from firing */
4663               if (emacs_event->modifiers == shift_modifier)
4664                 emacs_event->modifiers = 0;
4665             }
4666           else
4667               emacs_event->modifiers |=
4668                 parse_solitary_modifier (ns_alternate_modifier);
4669         }
4671   if (NS_KEYLOG)
4672     fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
4673              code, fnKeysym, flags, emacs_event->modifiers);
4675       /* if it was a function key or had modifiers, pass it directly to emacs */
4676       if (fnKeysym || (emacs_event->modifiers
4677                        && (emacs_event->modifiers != shift_modifier)
4678                        && [[theEvent charactersIgnoringModifiers] length] > 0))
4679 /*[[theEvent characters] length] */
4680         {
4681           emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4682           if (code < 0x20)
4683             code |= (1<<28)|(3<<16);
4684           else if (code == 0x7f)
4685             code |= (1<<28)|(3<<16);
4686           else if (!fnKeysym)
4687             emacs_event->kind = code > 0xFF
4688               ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4690           emacs_event->code = code;
4691           EV_TRAILER (theEvent);
4692           return;
4693         }
4694     }
4696   /* if we get here we should send the key for input manager processing */
4697   if (firstTime && [[NSInputManager currentInputManager]
4698                      wantsToDelayTextChangeNotifications] == NO)
4699     fprintf (stderr,
4700           "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
4701   firstTime = NO;
4703   if (NS_KEYLOG && !processingCompose)
4704     fprintf (stderr, "keyDown: Begin compose sequence.\n");
4706   processingCompose = YES;
4707   [nsEvArray addObject: theEvent];
4708   [self interpretKeyEvents: nsEvArray];
4709   [nsEvArray removeObject: theEvent];
4713 #ifdef NS_IMPL_COCOA
4714 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
4715    decided not to send key-down for.
4716    See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
4717    This only applies on Tiger and earlier.
4718    If it matches one of these, send it on to keyDown. */
4719 -(void)keyUp: (NSEvent *)theEvent
4721   int flags = [theEvent modifierFlags];
4722   int code = [theEvent keyCode];
4723   if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
4724       code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
4725     {
4726       if (NS_KEYLOG)
4727         fprintf (stderr, "keyUp: passed test");
4728       ns_fake_keydown = YES;
4729       [self keyDown: theEvent];
4730     }
4732 #endif
4735 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
4738 /* <NSTextInput>: called when done composing;
4739    NOTE: also called when we delete over working text, followed immed.
4740          by doCommandBySelector: deleteBackward: */
4741 - (void)insertText: (id)aString
4743   int code;
4744   int len = [(NSString *)aString length];
4745   int i;
4747   if (NS_KEYLOG)
4748     NSLog (@"insertText '%@'\tlen = %d", aString, len);
4749   processingCompose = NO;
4751   if (!emacs_event)
4752     return;
4754   /* first, clear any working text */
4755   if (workingText != nil)
4756     [self deleteWorkingText];
4758   /* now insert the string as keystrokes */
4759   for (i =0; i<len; i++)
4760     {
4761       code = [aString characterAtIndex: i];
4762       /* TODO: still need this? */
4763       if (code == 0x2DC)
4764         code = '~'; /* 0x7E */
4765       emacs_event->modifiers = 0;
4766       emacs_event->kind
4767         = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4768       emacs_event->code = code;
4769       EV_TRAILER ((id)nil);
4770     }
4774 /* <NSTextInput>: inserts display of composing characters */
4775 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
4777   NSString *str = [aString respondsToSelector: @selector (string)] ?
4778     [aString string] : aString;
4779   if (NS_KEYLOG)
4780     NSLog (@"setMarkedText '%@' len =%d range %d from %d", str, [str length],
4781            selRange.length, selRange.location);
4783   if (workingText != nil)
4784     [self deleteWorkingText];
4785   if ([str length] == 0)
4786     return;
4788   if (!emacs_event)
4789     return;
4791   processingCompose = YES;
4792   workingText = [str copy];
4793   ns_working_text = build_string ([workingText UTF8String]);
4795   emacs_event->kind = NS_TEXT_EVENT;
4796   emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
4797   EV_TRAILER ((id)nil);
4801 /* delete display of composing characters [not in <NSTextInput>] */
4802 - (void)deleteWorkingText
4804   if (workingText == nil)
4805     return;
4806   if (NS_KEYLOG)
4807     NSLog(@"deleteWorkingText len =%d\n", [workingText length]);
4808   [workingText release];
4809   workingText = nil;
4810   processingCompose = NO;
4812   if (!emacs_event)
4813     return;
4815   emacs_event->kind = NS_TEXT_EVENT;
4816   emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
4817   EV_TRAILER ((id)nil);
4821 - (BOOL)hasMarkedText
4823   return workingText != nil;
4827 - (NSRange)markedRange
4829   NSRange rng = workingText != nil
4830     ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
4831   if (NS_KEYLOG)
4832     NSLog (@"markedRange request");
4833   return rng;
4837 - (void)unmarkText
4839   if (NS_KEYLOG)
4840     NSLog (@"unmark (accept) text");
4841   [self deleteWorkingText];
4842   processingCompose = NO;
4846 /* used to position char selection windows, etc. */
4847 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
4849   NSRect rect;
4850   NSPoint pt;
4851   struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
4852   if (NS_KEYLOG)
4853     NSLog (@"firstRectForCharRange request");
4855   rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
4856   rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
4857   pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
4858   pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
4859                                        +FRAME_LINE_HEIGHT (emacsframe));
4861   pt = [self convertPoint: pt toView: nil];
4862   pt = [[self window] convertBaseToScreen: pt];
4863   rect.origin = pt;
4864   return rect;
4868 - (long)conversationIdentifier
4870   return (long)self;
4874 - (void)doCommandBySelector: (SEL)aSelector
4876   if (NS_KEYLOG)
4877     NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
4879   if (aSelector == @selector (deleteBackward:))
4880     {
4881       /* happens when user backspaces over an ongoing composition:
4882          throw a 'delete' into the event queue */
4883       if (!emacs_event)
4884         return;
4885       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4886       emacs_event->code = 0xFF08;
4887       EV_TRAILER ((id)nil);
4888     }
4891 - (NSArray *)validAttributesForMarkedText
4893   static NSArray *arr = nil;
4894   if (arr == nil) arr = [NSArray new];
4895  /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
4896   return arr;
4899 - (NSRange)selectedRange
4901   if (NS_KEYLOG)
4902     NSLog (@"selectedRange request");
4903   return NSMakeRange (NSNotFound, 0);
4906 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
4908   if (NS_KEYLOG)
4909     NSLog (@"characterIndexForPoint request");
4910   return 0;
4913 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
4915   static NSAttributedString *str = nil;
4916   if (str == nil) str = [NSAttributedString new];
4917   if (NS_KEYLOG)
4918     NSLog (@"attributedSubstringFromRange request");
4919   return str;
4922 /* End <NSTextInput> impl. */
4923 /*****************************************************************************/
4926 /* This is what happens when the user presses a mouse button.  */
4927 - (void)mouseDown: (NSEvent *)theEvent
4929   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
4930   Lisp_Object window;
4932   NSTRACE (mouseDown);
4934   [self deleteWorkingText];
4936   if (!emacs_event)
4937     return;
4939   last_mouse_frame = emacsframe;
4940   /* appears to be needed to prevent spurious movement events generated on
4941      button clicks */
4942   last_mouse_frame->mouse_moved = 0;
4944   if ([theEvent type] == NSScrollWheel)
4945     {
4946       float delta = [theEvent deltaY];
4947       /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
4948       if (delta == 0)
4949         return;
4950       emacs_event->kind = WHEEL_EVENT;
4951       emacs_event->code = 0;
4952       emacs_event->modifiers = EV_MODIFIERS (theEvent) |
4953         ((delta > 0) ? up_modifier : down_modifier);
4954     }
4955   else
4956     {
4957       emacs_event->kind = MOUSE_CLICK_EVENT;
4958       emacs_event->code = EV_BUTTON (theEvent);
4959       emacs_event->modifiers = EV_MODIFIERS (theEvent)
4960                              | EV_UDMODIFIERS (theEvent);
4961     }
4962   XSETINT (emacs_event->x, lrint (p.x));
4963   XSETINT (emacs_event->y, lrint (p.y));
4964   EV_TRAILER (theEvent);
4968 - (void)rightMouseDown: (NSEvent *)theEvent
4970   NSTRACE (rightMouseDown);
4971   [self mouseDown: theEvent];
4975 - (void)otherMouseDown: (NSEvent *)theEvent
4977   NSTRACE (otherMouseDown);
4978   [self mouseDown: theEvent];
4982 - (void)mouseUp: (NSEvent *)theEvent
4984   NSTRACE (mouseUp);
4985   [self mouseDown: theEvent];
4989 - (void)rightMouseUp: (NSEvent *)theEvent
4991   NSTRACE (rightMouseUp);
4992   [self mouseDown: theEvent];
4996 - (void)otherMouseUp: (NSEvent *)theEvent
4998   NSTRACE (otherMouseUp);
4999   [self mouseDown: theEvent];
5003 - (void) scrollWheel: (NSEvent *)theEvent
5005   NSTRACE (scrollWheel);
5006   [self mouseDown: theEvent];
5010 /* Tell emacs the mouse has moved. */
5011 - (void)mouseMoved: (NSEvent *)e
5013   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5014   Lisp_Object frame;
5016 //  NSTRACE (mouseMoved);
5018   last_mouse_movement_time = EV_TIMESTAMP (e);
5019   last_mouse_motion_position
5020     = [self convertPoint: [e locationInWindow] fromView: nil];
5022   /* update any mouse face */
5023   if (hlinfo->mouse_face_hidden)
5024     {
5025       hlinfo->mouse_face_hidden = 0;
5026       clear_mouse_face (hlinfo);
5027     }
5029   /* tooltip handling */
5030   previous_help_echo_string = help_echo_string;
5031   help_echo_string = Qnil;
5033   if (!note_mouse_movement (emacsframe, last_mouse_motion_position.x,
5034                             last_mouse_motion_position.y))
5035     help_echo_string = previous_help_echo_string;
5037   XSETFRAME (frame, emacsframe);
5038   if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
5039     {
5040       /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
5041          (note_mouse_highlight), which is called through the
5042          note_mouse_movement () call above */
5043       gen_help_event (help_echo_string, frame, help_echo_window,
5044                       help_echo_object, help_echo_pos);
5045     }
5046   else
5047     {
5048       help_echo_string = Qnil;
5049       gen_help_event (Qnil, frame, Qnil, Qnil, 0);
5050     }
5052   if (emacsframe->mouse_moved && send_appdefined)
5053     ns_send_appdefined (-1);
5057 - (void)mouseDragged: (NSEvent *)e
5059   NSTRACE (mouseDragged);
5060   [self mouseMoved: e];
5064 - (void)rightMouseDragged: (NSEvent *)e
5066   NSTRACE (rightMouseDragged);
5067   [self mouseMoved: e];
5071 - (void)otherMouseDragged: (NSEvent *)e
5073   NSTRACE (otherMouseDragged);
5074   [self mouseMoved: e];
5078 - (BOOL)windowShouldClose: (id)sender
5080   NSEvent *e =[[self window] currentEvent];
5082   NSTRACE (windowShouldClose);
5083   windowClosing = YES;
5084   if (!emacs_event)
5085     return NO;
5086   emacs_event->kind = DELETE_WINDOW_EVENT;
5087   emacs_event->modifiers = 0;
5088   emacs_event->code = 0;
5089   EV_TRAILER (e);
5090   /* Don't close this window, let this be done from lisp code.  */
5091   return NO;
5095 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
5096 /* normalize frame to gridded text size */
5098   NSTRACE (windowWillResize);
5099 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
5101   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe,
5102 #ifdef NS_IMPL_GNUSTEP
5103                                         frameSize.width + 3);
5104 #else
5105                                         frameSize.width);
5106 #endif
5107   if (cols < MINWIDTH)
5108     cols = MINWIDTH;
5110   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, frameSize.height
5111 #ifdef NS_IMPL_GNUSTEP
5112       - FRAME_NS_TITLEBAR_HEIGHT (emacsframe) + 3
5113         - FRAME_TOOLBAR_HEIGHT (emacsframe));
5114 #else
5115       - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5116         - FRAME_TOOLBAR_HEIGHT (emacsframe));
5117 #endif
5118   if (rows < MINHEIGHT)
5119     rows = MINHEIGHT;
5120 #ifdef NS_IMPL_COCOA
5121   {
5122     /* this sets window title to have size in it; the wm does this under GS */
5123     NSRect r = [[self window] frame];
5124     if (r.size.height == frameSize.height && r.size.width == frameSize.width)
5125       {
5126         if (old_title != 0)
5127           {
5128             xfree (old_title);
5129             old_title = 0;
5130           }
5131       }
5132     else
5133       {
5134         char *size_title;
5135         NSWindow *window = [self window];
5136         if (old_title == 0)
5137           {
5138             const char *t = [[[self window] title] UTF8String];
5139             char *pos = strstr (t, "  â€”  ");
5140             if (pos)
5141               *pos = '\0';
5142             old_title = (char *) xmalloc (strlen (t) + 1);
5143             strcpy (old_title, t);
5144           }
5145         size_title = xmalloc (strlen (old_title) + 40);
5146         sprintf (size_title, "%s  â€”  (%d x %d)", old_title, cols, rows);
5147         [window setTitle: [NSString stringWithUTF8String: size_title]];
5148         [window display];
5149         xfree (size_title);
5150       }
5151   }
5152 #endif /* NS_IMPL_COCOA */
5153 /*fprintf (stderr,"    ...size became %.0f x %.0f  (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
5155   return frameSize;
5159 - (void)windowDidResize: (NSNotification *)notification
5161   NSWindow *theWindow = [notification object];
5163 #ifdef NS_IMPL_GNUSTEP
5164    /* in GNUstep, at least currently, it's possible to get a didResize
5165       without getting a willResize.. therefore we need to act as if we got
5166       the willResize now */
5167   NSSize sz = [theWindow frame].size;
5168   sz = [self windowWillResize: theWindow toSize: sz];
5169 #endif /* NS_IMPL_GNUSTEP */
5171   NSTRACE (windowDidResize);
5172 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
5174 #ifdef NS_IMPL_COCOA
5175   if (old_title != 0)
5176     {
5177       xfree (old_title);
5178       old_title = 0;
5179     }
5180 #endif /* NS_IMPL_COCOA */
5182   /* Avoid loop under GNUstep due to call at beginning of this function.
5183      (x_set_window_size causes a resize which causes
5184      a "windowDidResize" which calls x_set_window_size).  */
5185 #ifndef NS_IMPL_GNUSTEP
5186   if (cols > 0 && rows > 0)
5187     x_set_window_size (emacsframe, 0, cols, rows);
5188 #endif
5190   ns_send_appdefined (-1);
5194 - (void)windowDidBecomeKey: (NSNotification *)notification
5195 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5197   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5198   struct frame *old_focus = dpyinfo->x_focus_frame;
5200   NSTRACE (windowDidBecomeKey);
5202   if (emacsframe != old_focus)
5203     dpyinfo->x_focus_frame = emacsframe;
5205   ns_frame_rehighlight (emacsframe);
5207   if (emacs_event)
5208     {
5209       emacs_event->kind = FOCUS_IN_EVENT;
5210       EV_TRAILER ((id)nil);
5211     }
5215 - (void)windowDidResignKey: (NSNotification *)notification
5216 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5218   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5219   NSTRACE (windowDidResignKey);
5221   if (dpyinfo->x_focus_frame == emacsframe)
5222     dpyinfo->x_focus_frame = 0;
5224   ns_frame_rehighlight (emacsframe);
5226   /* FIXME: for some reason needed on second and subsequent clicks away
5227             from sole-frame Emacs to get hollow box to show */
5228   if (!windowClosing && [[self window] isVisible] == YES)
5229     {
5230       x_update_cursor (emacsframe, 1);
5231       x_set_frame_alpha (emacsframe);
5232     }
5234   if (emacs_event)
5235     {
5236       [self deleteWorkingText];
5237       emacs_event->kind = FOCUS_IN_EVENT;
5238       EV_TRAILER ((id)nil);
5239     }
5243 - (void)windowWillMiniaturize: sender
5245   NSTRACE (windowWillMiniaturize);
5249 - (BOOL)isFlipped
5251   return YES;
5255 - (BOOL)isOpaque
5257   return NO;
5261 - initFrameFromEmacs: (struct frame *)f
5263   NSRect r, wr;
5264   Lisp_Object tem;
5265   NSWindow *win;
5266   NSButton *toggleButton;
5267   int vbextra = NS_SCROLL_BAR_WIDTH (f);
5268   NSSize sz;
5269   NSColor *col;
5270   NSString *name;
5272   NSTRACE (initFrameFromEmacs);
5274   windowClosing = NO;
5275   processingCompose = NO;
5276   scrollbarsNeedingUpdate = 0;
5278 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
5280   ns_userRect = NSMakeRect (0, 0, 0, 0);
5281   r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
5282                  FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
5283   [self initWithFrame: r];
5284   [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
5286   FRAME_NS_VIEW (f) = self;
5287   emacsframe = f;
5288   old_title = 0;
5290   win = [[EmacsWindow alloc]
5291             initWithContentRect: r
5292                       styleMask: (NSResizableWindowMask |
5293                                   NSMiniaturizableWindowMask |
5294                                   NSClosableWindowMask)
5295                         backing: NSBackingStoreBuffered
5296                           defer: YES];
5298   wr = [win frame];
5299   f->border_width = wr.size.width - r.size.width;
5300   FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
5302   [win setAcceptsMouseMovedEvents: YES];
5303   [win setDelegate: self];
5304   [win useOptimizedDrawing: YES];
5306   sz.width = FRAME_COLUMN_WIDTH (f);
5307   sz.height = FRAME_LINE_HEIGHT (f);
5308   [win setResizeIncrements: sz];
5310   [[win contentView] addSubview: self];
5312   if (ns_drag_types)
5313     [self registerForDraggedTypes: ns_drag_types];
5315   tem = f->name;
5316   name = [NSString stringWithUTF8String:
5317                    NILP (tem) ? (unsigned char *)"Emacs" : SDATA (tem)];
5318   [win setTitle: name];
5320   /* toolbar support */
5321   toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
5322                          [NSString stringWithFormat: @"Emacs Frame %d",
5323                                    ns_window_num]];
5324   [win setToolbar: toolbar];
5325   [toolbar setVisible: NO];
5326 #ifdef NS_IMPL_COCOA
5327   toggleButton = [win standardWindowButton: NSWindowToolbarButton];
5328   [toggleButton setTarget: self];
5329   [toggleButton setAction: @selector (toggleToolbar: )];
5330 #endif
5331   FRAME_TOOLBAR_HEIGHT (f) = 0;
5333   tem = f->icon_name;
5334   if (!NILP (tem))
5335     [win setMiniwindowTitle:
5336            [NSString stringWithUTF8String: SDATA (tem)]];
5338   {
5339     NSScreen *screen = [win screen];
5341     if (screen != 0)
5342       [win setFrameTopLeftPoint: NSMakePoint
5343            (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
5344             IN_BOUND (-SCREENMAX,
5345                      [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
5346   }
5348   [win makeFirstResponder: self];
5350   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5351                                   (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
5352   [win setBackgroundColor: col];
5353   if ([col alphaComponent] != 1.0)
5354     [win setOpaque: NO];
5356   [self allocateGState];
5358   ns_window_num++;
5359   return self;
5363 - (void)windowDidMove: sender
5365   NSWindow *win = [self window];
5366   NSRect r = [win frame];
5367   NSArray *screens = [NSScreen screens];
5368   NSScreen *screen = [screens objectAtIndex: 0];
5370   NSTRACE (windowDidMove);
5372   if (!emacsframe->output_data.ns)
5373     return;
5374   if (screen != nil)
5375     {
5376       emacsframe->left_pos = r.origin.x;
5377       emacsframe->top_pos =
5378         [screen frame].size.height - (r.origin.y + r.size.height);
5379     }
5383 /* Called AFTER method below, but before our windowWillResize call there leads
5384    to windowDidResize -> x_set_window_size.  Update emacs' notion of frame
5385    location so set_window_size moves the frame. */
5386 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
5388   emacsframe->output_data.ns->zooming = 1;
5389   return YES;
5393 /* Override to do something slightly nonstandard, but nice.  First click on
5394    zoom button will zoom vertically.  Second will zoom completely.  Third
5395    returns to original. */
5396 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
5397                         defaultFrame:(NSRect)defaultFrame
5399   NSRect result = [sender frame];
5401   NSTRACE (windowWillUseStandardFrame);
5403   if (abs (defaultFrame.size.height - result.size.height)
5404       > FRAME_LINE_HEIGHT (emacsframe))
5405     {
5406       /* first click */
5407       ns_userRect = result;
5408       result.size.height = defaultFrame.size.height;
5409       result.origin.y = defaultFrame.origin.y;
5410     }
5411   else
5412     {
5413       if (abs (defaultFrame.size.width - result.size.width)
5414           > FRAME_COLUMN_WIDTH (emacsframe))
5415         result = defaultFrame;  /* second click */
5416       else
5417         {
5418           /* restore */
5419           result = ns_userRect.size.height ? ns_userRect : result;
5420           ns_userRect = NSMakeRect (0, 0, 0, 0);
5421         }
5422     }
5424   [self windowWillResize: sender toSize: result.size];
5425   return result;
5429 - (void)windowDidDeminiaturize: sender
5431   NSTRACE (windowDidDeminiaturize);
5432   if (!emacsframe->output_data.ns)
5433     return;
5434   emacsframe->async_iconified = 0;
5435   emacsframe->async_visible   = 1;
5436   windows_or_buffers_changed++;
5438   if (emacs_event)
5439     {
5440       emacs_event->kind = ICONIFY_EVENT;
5441       EV_TRAILER ((id)nil);
5442     }
5446 - (void)windowDidExpose: sender
5448   NSTRACE (windowDidExpose);
5449   if (!emacsframe->output_data.ns)
5450     return;
5451   emacsframe->async_visible = 1;
5452   SET_FRAME_GARBAGED (emacsframe);
5454   if (send_appdefined)
5455     ns_send_appdefined (-1);
5459 - (void)windowDidMiniaturize: sender
5461   NSTRACE (windowDidMiniaturize);
5462   if (!emacsframe->output_data.ns)
5463     return;
5465   emacsframe->async_iconified = 1;
5466   emacsframe->async_visible = 0;
5468   if (emacs_event)
5469     {
5470       emacs_event->kind = ICONIFY_EVENT;
5471       EV_TRAILER ((id)nil);
5472     }
5476 - (void)mouseEntered: (NSEvent *)theEvent
5478   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5479   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5480   NSTRACE (mouseEntered);
5482   last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5486 - (void)mouseExited: (NSEvent *)theEvent
5488   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5489   NSRect r;
5490   Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
5492   NSTRACE (mouseExited);
5494   if (!hlinfo)
5495     return;
5497   last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5499   if (emacsframe == hlinfo->mouse_face_mouse_frame)
5500     {
5501       clear_mouse_face (hlinfo);
5502       hlinfo->mouse_face_mouse_frame = 0;
5503     }
5507 - menuDown: sender
5509   NSTRACE (menuDown);
5510   if (context_menu_value == -1)
5511     context_menu_value = [sender tag];
5512   else
5513     find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
5514                                   emacsframe->menu_bar_vector,
5515                                   (void *)[sender tag]);
5516   ns_send_appdefined (-1);
5517   return self;
5521 - (EmacsToolbar *)toolbar
5523   return toolbar;
5527 /* this gets called on toolbar button click */
5528 - toolbarClicked: (id)item
5530   NSEvent *theEvent;
5531   int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
5533   NSTRACE (toolbarClicked);
5535   if (!emacs_event)
5536     return self;
5538   /* send first event (for some reason two needed) */
5539   theEvent = [[self window] currentEvent];
5540   emacs_event->kind = TOOL_BAR_EVENT;
5541   XSETFRAME (emacs_event->arg, emacsframe);
5542   EV_TRAILER (theEvent);
5544   emacs_event->kind = TOOL_BAR_EVENT;
5545 /*   XSETINT (emacs_event->code, 0); */
5546   emacs_event->arg = AREF (emacsframe->tool_bar_items,
5547                           idx + TOOL_BAR_ITEM_KEY);
5548   emacs_event->modifiers = EV_MODIFIERS (theEvent);
5549   EV_TRAILER (theEvent);
5550   return self;
5554 - toggleToolbar: (id)sender
5556   if (!emacs_event)
5557     return self;
5559   emacs_event->kind = NS_NONKEY_EVENT;
5560   emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
5561   EV_TRAILER ((id)nil);
5562   return self;
5566 - (void)drawRect: (NSRect)rect
5568   int x = NSMinX (rect), y = NSMinY (rect);
5569   int width = NSWidth (rect), height = NSHeight (rect);
5571   NSTRACE (drawRect);
5573   if (!emacsframe || !emacsframe->output_data.ns || ns_in_resize)
5574     return;
5576   ns_clear_frame_area (emacsframe, x, y, width, height);
5577   expose_frame (emacsframe, x, y, width, height);
5579   /*
5580     drawRect: may be called (at least in OS X 10.5) for invisible
5581     views as well for some reason.  Thus, do not infer visibility
5582     here.
5584     emacsframe->async_visible = 1;
5585     emacsframe->async_iconified = 0;
5586   */
5590 /* NSDraggingDestination protocol methods.  Actually this is not really a
5591    protocol, but a category of Object.  O well...  */
5593 -(NSUInteger) draggingEntered: (id <NSDraggingInfo>) sender
5595   NSTRACE (draggingEntered);
5596   return NSDragOperationGeneric;
5600 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
5602   return YES;
5606 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
5608   id pb;
5609   int x, y;
5610   NSString *type;
5611   NSEvent *theEvent = [[self window] currentEvent];
5612   NSPoint position;
5614   NSTRACE (performDragOperation);
5616   if (!emacs_event)
5617     return NO;
5619   position = [self convertPoint: [sender draggingLocation] fromView: nil];
5620   x = lrint (position.x);  y = lrint (position.y);
5622   pb = [sender draggingPasteboard];
5623   type = [pb availableTypeFromArray: ns_drag_types];
5624   if (type == 0)
5625     {
5626       return NO;
5627     }
5628   else if ([type isEqualToString: NSFilenamesPboardType])
5629     {
5630       NSArray *files;
5631       NSEnumerator *fenum;
5632       NSString *file;
5634       if (!(files = [pb propertyListForType: type]))
5635         return NO;
5637       fenum = [files objectEnumerator];
5638       while ( (file = [fenum nextObject]) )
5639         {
5640           emacs_event->kind = NS_NONKEY_EVENT;
5641           emacs_event->code = KEY_NS_DRAG_FILE;
5642           XSETINT (emacs_event->x, x);
5643           XSETINT (emacs_event->y, y);
5644           ns_input_file = append2 (ns_input_file,
5645                                    build_string ([file UTF8String]));
5646           emacs_event->modifiers = EV_MODIFIERS (theEvent);
5647           EV_TRAILER (theEvent);
5648         }
5649       return YES;
5650     }
5651   else if ([type isEqualToString: NSURLPboardType])
5652     {
5653       NSString *file;
5654       NSURL *fileURL;
5656       if (!(fileURL = [NSURL URLFromPasteboard: pb]) ||
5657           [fileURL isFileURL] == NO)
5658         return NO;
5660       file = [fileURL path];
5661       emacs_event->kind = NS_NONKEY_EVENT;
5662       emacs_event->code = KEY_NS_DRAG_FILE;
5663       XSETINT (emacs_event->x, x);
5664       XSETINT (emacs_event->y, y);
5665       ns_input_file = append2 (ns_input_file, build_string ([file UTF8String]));
5666       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5667       EV_TRAILER (theEvent);
5668       return YES;
5669     }
5670   else if ([type isEqualToString: NSStringPboardType]
5671            || [type isEqualToString: NSTabularTextPboardType])
5672     {
5673       NSString *data;
5675       if (! (data = [pb stringForType: type]))
5676         return NO;
5678       emacs_event->kind = NS_NONKEY_EVENT;
5679       emacs_event->code = KEY_NS_DRAG_TEXT;
5680       XSETINT (emacs_event->x, x);
5681       XSETINT (emacs_event->y, y);
5682       ns_input_text = build_string ([data UTF8String]);
5683       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5684       EV_TRAILER (theEvent);
5685       return YES;
5686     }
5687   else if ([type isEqualToString: NSColorPboardType])
5688     {
5689       NSColor *c = [NSColor colorFromPasteboard: pb];
5690       emacs_event->kind = NS_NONKEY_EVENT;
5691       emacs_event->code = KEY_NS_DRAG_COLOR;
5692       XSETINT (emacs_event->x, x);
5693       XSETINT (emacs_event->y, y);
5694       ns_input_color = ns_color_to_lisp (c);
5695       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5696       EV_TRAILER (theEvent);
5697       return YES;
5698     }
5699   else if ([type isEqualToString: NSFontPboardType])
5700     {
5701       /* impl based on GNUstep NSTextView.m */
5702       NSData *data = [pb dataForType: NSFontPboardType];
5703       NSDictionary *dict = [NSUnarchiver unarchiveObjectWithData: data];
5704       NSFont *font = [dict objectForKey: NSFontAttributeName];
5705       char fontSize[10];
5707       if (font == nil)
5708         return NO;
5710       emacs_event->kind = NS_NONKEY_EVENT;
5711       emacs_event->code = KEY_NS_CHANGE_FONT;
5712       XSETINT (emacs_event->x, x);
5713       XSETINT (emacs_event->y, y);
5714       ns_input_font = build_string ([[font fontName] UTF8String]);
5715       snprintf (fontSize, 10, "%f", [font pointSize]);
5716       ns_input_fontsize = build_string (fontSize);
5717       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5718       EV_TRAILER (theEvent);
5719       return YES;
5720     }
5721   else
5722     {
5723       error ("Invalid data type in dragging pasteboard.");
5724       return NO;
5725     }
5729 - validRequestorForSendType: (NSString *)typeSent
5730                  returnType: (NSString *)typeReturned
5732   NSTRACE (validRequestorForSendType);
5733   if ([ns_send_types indexOfObjectIdenticalTo: typeSent] != NSNotFound &&
5734       [ns_return_types indexOfObjectIdenticalTo: typeSent] != NSNotFound)
5735     return self;
5737   return [super validRequestorForSendType: typeSent
5738                                returnType: typeReturned];
5742 /* The next two methods are part of NSServicesRequests informal protocol,
5743    supposedly called when a services menu item is chosen from this app.
5744    But this should not happen because we override the services menu with our
5745    own entries which call ns-perform-service.
5746    Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
5747    So let's at least stub them out until further investigation can be done. */
5749 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
5751   /* we could call ns_string_from_pasteboard(pboard) here but then it should
5752      be written into the buffer in place of the existing selection..
5753      ordinary service calls go through functions defined in ns-win.el */
5754   return NO;
5757 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
5759   /* supposed to write for as many of types as we are able */
5760   return NO;
5764 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
5765    (gives a miniaturized version of the window); currently we use the latter for
5766    frames whose active buffer doesn't correspond to any file
5767    (e.g., '*scratch*') */
5768 - setMiniwindowImage: (BOOL) setMini
5770   id image = [[self window] miniwindowImage];
5771   NSTRACE (setMiniwindowImage);
5773   /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
5774      about "AppleDockIconEnabled" notwithstanding, however the set message
5775      below has its effect nonetheless. */
5776   if (image != emacsframe->output_data.ns->miniimage)
5777     {
5778       if (image && [image isKindOfClass: [EmacsImage class]])
5779         [image release];
5780       [[self window] setMiniwindowImage:
5781                        setMini ? emacsframe->output_data.ns->miniimage : nil];
5782     }
5784   return self;
5788 - (void) setRows: (int) r andColumns: (int) c
5790   rows = r;
5791   cols = c;
5794 @end  /* EmacsView */
5798 /* ==========================================================================
5800     EmacsWindow implementation
5802    ========================================================================== */
5804 @implementation EmacsWindow
5806 /* If we have multiple monitors, one above the other, we don't want to
5807    restrict the height to just one monitor.  So we override this.  */
5808 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
5810   /* When making the frame visible for the first time, we want to
5811      constrain.  Other times not.  */
5812   struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
5813   NSTRACE (constrainFrameRect);
5815   if (f->output_data.ns->dont_constrain
5816       || ns_menu_bar_should_be_hidden ())
5817     return frameRect;
5819   f->output_data.ns->dont_constrain = 1;
5820   return [super constrainFrameRect:frameRect toScreen:screen];
5824 /* called only on resize clicks by special case in EmacsApp-sendEvent */
5825 - (void)mouseDown: (NSEvent *)theEvent
5827   if (ns_in_resize)
5828     {
5829       NSSize size = [[theEvent window] frame].size;
5830       grabOffset = [theEvent locationInWindow];
5831       grabOffset.x = size.width - grabOffset.x;
5832     }
5833   else
5834     [super mouseDown: theEvent];
5838 /* stop resizing */
5839 - (void)mouseUp: (NSEvent *)theEvent
5841   if (ns_in_resize)
5842     {
5843       struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
5844       ns_in_resize = NO;
5845       ns_set_name_as_filename (f);
5846       [self display];
5847       ns_send_appdefined (-1);
5848     }
5849   else
5850     [super mouseUp: theEvent];
5854 /* send resize events */
5855 - (void)mouseDragged: (NSEvent *)theEvent
5857   if (ns_in_resize)
5858     {
5859       NSPoint p = [theEvent locationInWindow];
5860       NSSize size, vettedSize, origSize = [self frame].size;
5862       size.width = p.x + grabOffset.x;
5863       size.height = origSize.height - p.y + grabOffset.y;
5865       if (size.width == origSize.width && size.height == origSize.height)
5866         return;
5868       vettedSize = [[self delegate] windowWillResize: self toSize: size];
5869       [[NSNotificationCenter defaultCenter]
5870             postNotificationName: NSWindowDidResizeNotification
5871                           object: self];
5872     }
5873   else
5874     [super mouseDragged: theEvent];
5877 @end /* EmacsWindow */
5880 /* ==========================================================================
5882     EmacsScroller implementation
5884    ========================================================================== */
5887 @implementation EmacsScroller
5889 /* for repeat button push */
5890 #define SCROLL_BAR_FIRST_DELAY 0.5
5891 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
5893 + (CGFloat) scrollerWidth
5895   /* TODO: if we want to allow variable widths, this is the place to do it,
5896            however neither GNUstep nor Cocoa support it very well */
5897   return [NSScroller scrollerWidth];
5901 - initFrame: (NSRect )r window: (Lisp_Object)nwin
5903   NSTRACE (EmacsScroller_initFrame);
5905   r.size.width = [EmacsScroller scrollerWidth];
5906   [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
5907   [self setContinuous: YES];
5908   [self setEnabled: YES];
5910   /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
5911      locked against the top and bottom edges, and right edge on OS X, where
5912      scrollers are on right. */
5913 #ifdef NS_IMPL_GNUSTEP
5914   [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
5915 #else
5916   [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
5917 #endif
5919   win = nwin;
5920   condemned = NO;
5921   pixel_height = NSHeight (r);
5922   if (pixel_height == 0) pixel_height = 1;
5923   min_portion = 20 / pixel_height;
5925   frame = XFRAME (XWINDOW (win)->frame);
5926   if (FRAME_LIVE_P (frame))
5927     {
5928       int i;
5929       EmacsView *view = FRAME_NS_VIEW (frame);
5930       NSView *sview = [[view window] contentView];
5931       NSArray *subs = [sview subviews];
5933       /* disable optimization stopping redraw of other scrollbars */
5934       view->scrollbarsNeedingUpdate = 0;
5935       for (i =[subs count]-1; i >= 0; i--)
5936         if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
5937           view->scrollbarsNeedingUpdate++;
5938       [sview addSubview: self];
5939     }
5941 /*  [self setFrame: r]; */
5943   return self;
5947 - (void)setFrame: (NSRect)newRect
5949   NSTRACE (EmacsScroller_setFrame);
5950 /*  BLOCK_INPUT; */
5951   pixel_height = NSHeight (newRect);
5952   if (pixel_height == 0) pixel_height = 1;
5953   min_portion = 20 / pixel_height;
5954   [super setFrame: newRect];
5955   [self display];
5956 /*  UNBLOCK_INPUT; */
5960 - (void)dealloc
5962   NSTRACE (EmacsScroller_dealloc);
5963   if (!NILP (win))
5964     XWINDOW (win)->vertical_scroll_bar = Qnil;
5965   [super dealloc];
5969 - condemn
5971   NSTRACE (condemn);
5972   condemned =YES;
5973   return self;
5977 - reprieve
5979   NSTRACE (reprieve);
5980   condemned =NO;
5981   return self;
5985 - judge
5987   NSTRACE (judge);
5988   if (condemned)
5989     {
5990       EmacsView *view;
5991       BLOCK_INPUT;
5992       /* ensure other scrollbar updates after deletion */
5993       view = (EmacsView *)FRAME_NS_VIEW (frame);
5994       if (view != nil)
5995         view->scrollbarsNeedingUpdate++;
5996       [self removeFromSuperview];
5997       [self release];
5998       UNBLOCK_INPUT;
5999     }
6000   return self;
6004 - (void)resetCursorRects
6006   NSRect visible = [self visibleRect];
6007   NSTRACE (resetCursorRects);
6009   if (!NSIsEmptyRect (visible))
6010     [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
6011   [[NSCursor arrowCursor] setOnMouseEntered: YES];
6015 - (int) checkSamePosition: (int) position portion: (int) portion
6016                     whole: (int) whole
6018   return em_position ==position && em_portion ==portion && em_whole ==whole
6019     && portion != whole; /* needed for resize empty buf */
6023 - setPosition: (int)position portion: (int)portion whole: (int)whole
6025   NSTRACE (setPosition);
6027   em_position = position;
6028   em_portion = portion;
6029   em_whole = whole;
6031   if (portion >= whole)
6032     [self setFloatValue: 0.0 knobProportion: 1.0];
6033   else
6034     {
6035       float pos, por;
6036       portion = max ((float)whole*min_portion/pixel_height, portion);
6037       pos = (float)position / (whole - portion);
6038       por = (float)portion/whole;
6039       [self setFloatValue: pos knobProportion: por];
6040     }
6041   return self;
6044 /* FIXME: unused at moment (see ns_mouse_position) at the moment because
6045      drag events will go directly to the EmacsScroller.  Leaving in for now. */
6046 -(void)getMouseMotionPart: (int *)part window: (Lisp_Object *)window
6047                         x: (Lisp_Object *)x y: ( Lisp_Object *)y
6049   *part = last_hit_part;
6050   *window = win;
6051   XSETINT (*y, pixel_height);
6052   if ([self floatValue] > 0.999)
6053     XSETINT (*x, pixel_height);
6054   else
6055     XSETINT (*x, pixel_height * [self floatValue]);
6059 /* set up emacs_event */
6060 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
6062   if (!emacs_event)
6063     return;
6065   emacs_event->part = last_hit_part;
6066   emacs_event->code = 0;
6067   emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
6068   emacs_event->frame_or_window = win;
6069   emacs_event->timestamp = EV_TIMESTAMP (e);
6070   emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
6071   emacs_event->arg = Qnil;
6072   XSETINT (emacs_event->x, loc * pixel_height);
6073   XSETINT (emacs_event->y, pixel_height-20);
6075   n_emacs_events_pending++;
6076   kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
6077   EVENT_INIT (*emacs_event);
6078   ns_send_appdefined (-1);
6082 /* called manually thru timer to implement repeated button action w/hold-down */
6083 - repeatScroll: (NSTimer *)scrollEntry
6085   NSEvent *e = [[self window] currentEvent];
6086   NSPoint p =  [[self window] mouseLocationOutsideOfEventStream];
6087   BOOL inKnob = [self testPart: p] == NSScrollerKnob;
6089   /* clear timer if need be */
6090   if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
6091     {
6092         [scroll_repeat_entry invalidate];
6093         [scroll_repeat_entry release];
6094         scroll_repeat_entry = nil;
6096         if (inKnob)
6097           return self;
6099         scroll_repeat_entry
6100           = [[NSTimer scheduledTimerWithTimeInterval:
6101                         SCROLL_BAR_CONTINUOUS_DELAY
6102                                             target: self
6103                                           selector: @selector (repeatScroll:)
6104                                           userInfo: 0
6105                                            repeats: YES]
6106               retain];
6107     }
6109   [self sendScrollEventAtLoc: 0 fromEvent: e];
6110   return self;
6114 /* Asynchronous mouse tracking for scroller.  This allows us to dispatch
6115    mouseDragged events without going into a modal loop. */
6116 - (void)mouseDown: (NSEvent *)e
6118   NSRect sr, kr;
6119   /* hitPart is only updated AFTER event is passed on */
6120   NSScrollerPart part = [self testPart: [e locationInWindow]];
6121   double inc = 0.0, loc, kloc, pos;
6122   int edge = 0;
6124   NSTRACE (EmacsScroller_mouseDown);
6126   switch (part)
6127     {
6128     case NSScrollerDecrementPage:
6129         last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
6130     case NSScrollerIncrementPage:
6131         last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
6132     case NSScrollerDecrementLine:
6133       last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
6134     case NSScrollerIncrementLine:
6135       last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
6136     case NSScrollerKnob:
6137       last_hit_part = scroll_bar_handle; break;
6138     case NSScrollerKnobSlot:  /* GNUstep-only */
6139       last_hit_part = scroll_bar_move_ratio; break;
6140     default:  /* NSScrollerNoPart? */
6141       fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
6142                (long) part);
6143       return;
6144     }
6146   if (inc != 0.0)
6147     {
6148       pos = 0;      /* ignored */
6150       /* set a timer to repeat, as we can't let superclass do this modally */
6151       scroll_repeat_entry
6152         = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
6153                                             target: self
6154                                           selector: @selector (repeatScroll:)
6155                                           userInfo: 0
6156                                            repeats: YES]
6157             retain];
6158     }
6159   else
6160     {
6161       /* handle, or on GNUstep possibly slot */
6162       NSEvent *fake_event;
6164       /* compute float loc in slot and mouse offset on knob */
6165       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6166                       toView: nil];
6167       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6168       if (loc <= 0.0)
6169         {
6170           loc = 0.0;
6171           edge = -1;
6172         }
6173       else if (loc >= NSHeight (sr))
6174         {
6175           loc = NSHeight (sr);
6176           edge = 1;
6177         }
6179       if (edge)
6180         kloc = 0.5 * edge;
6181       else
6182         {
6183           kr = [self convertRect: [self rectForPart: NSScrollerKnob]
6184                           toView: nil];
6185           kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
6186         }
6187       last_mouse_offset = kloc;
6189       /* if knob, tell emacs a location offset by knob pos
6190          (to indicate top of handle) */
6191       if (part == NSScrollerKnob)
6192           pos = (loc - last_mouse_offset) / NSHeight (sr);
6193       else
6194         /* else this is a slot click on GNUstep: go straight there */
6195         pos = loc / NSHeight (sr);
6197       /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
6198       fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
6199                                       location: [e locationInWindow]
6200                                  modifierFlags: [e modifierFlags]
6201                                      timestamp: [e timestamp]
6202                                   windowNumber: [e windowNumber]
6203                                        context: [e context]
6204                                    eventNumber: [e eventNumber]
6205                                     clickCount: [e clickCount]
6206                                       pressure: [e pressure]];
6207       [super mouseUp: fake_event];
6208     }
6210   if (part != NSScrollerKnob)
6211     [self sendScrollEventAtLoc: pos fromEvent: e];
6215 /* Called as we manually track scroller drags, rather than superclass. */
6216 - (void)mouseDragged: (NSEvent *)e
6218     NSRect sr;
6219     double loc, pos;
6220     int edge = 0;
6222     NSTRACE (EmacsScroller_mouseDragged);
6224       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6225                       toView: nil];
6226       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6228       if (loc <= 0.0)
6229         {
6230           loc = 0.0;
6231           edge = -1;
6232         }
6233       else if (loc >= NSHeight (sr) + last_mouse_offset)
6234         {
6235           loc = NSHeight (sr) + last_mouse_offset;
6236           edge = 1;
6237         }
6239       pos = /*(edge ? loc :*/ (loc - last_mouse_offset) / NSHeight (sr);
6240       [self sendScrollEventAtLoc: pos fromEvent: e];
6244 - (void)mouseUp: (NSEvent *)e
6246   if (scroll_repeat_entry)
6247     {
6248       [scroll_repeat_entry invalidate];
6249       [scroll_repeat_entry release];
6250       scroll_repeat_entry = nil;
6251     }
6252   last_hit_part = 0;
6256 /* treat scrollwheel events in the bar as though they were in the main window */
6257 - (void) scrollWheel: (NSEvent *)theEvent
6259   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
6260   [view mouseDown: theEvent];
6263 @end  /* EmacsScroller */
6268 /* ==========================================================================
6270    Font-related functions; these used to be in nsfaces.m
6272    ========================================================================== */
6275 Lisp_Object
6276 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
6278   struct font *font = XFONT_OBJECT (font_object);
6280   if (fontset < 0)
6281     fontset = fontset_from_font (font_object);
6282   FRAME_FONTSET (f) = fontset;
6284   if (FRAME_FONT (f) == font)
6285     /* This font is already set in frame F.  There's nothing more to
6286        do.  */
6287     return font_object;
6289   FRAME_FONT (f) = font;
6291   FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
6292   FRAME_COLUMN_WIDTH (f) = font->average_width;
6293   FRAME_SPACE_WIDTH (f) = font->space_width;
6294   FRAME_LINE_HEIGHT (f) = font->height;
6296   compute_fringe_widths (f, 1);
6298   /* Compute the scroll bar width in character columns.  */
6299   if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
6300     {
6301       int wid = FRAME_COLUMN_WIDTH (f);
6302       FRAME_CONFIG_SCROLL_BAR_COLS (f)
6303         = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
6304     }
6305   else
6306     {
6307       int wid = FRAME_COLUMN_WIDTH (f);
6308       FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
6309     }
6311   /* Now make the frame display the given font.  */
6312   if (FRAME_NS_WINDOW (f) != 0)
6313         x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
6315   return font_object;
6319 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
6320 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
6321          in 1.43. */
6323 const char *
6324 ns_xlfd_to_fontname (const char *xlfd)
6325 /* --------------------------------------------------------------------------
6326     Convert an X font name (XLFD) to an NS font name.
6327     Only family is used.
6328     The string returned is temporarily allocated.
6329    -------------------------------------------------------------------------- */
6331   char *name = xmalloc (180);
6332   int i, len;
6333   const char *ret;
6335   if (!strncmp (xlfd, "--", 2))
6336     sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
6337   else
6338     sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
6340   /* stopgap for malformed XLFD input */
6341   if (strlen (name) == 0)
6342     strcpy (name, "Monaco");
6344   /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
6345      also uppercase after '-' or ' ' */
6346   name[0] = toupper (name[0]);
6347   for (len =strlen (name), i =0; i<len; i++)
6348     {
6349       if (name[i] == '$')
6350         {
6351           name[i] = '-';
6352           if (i+1<len)
6353             name[i+1] = toupper (name[i+1]);
6354         }
6355       else if (name[i] == '_')
6356         {
6357           name[i] = ' ';
6358           if (i+1<len)
6359             name[i+1] = toupper (name[i+1]);
6360         }
6361     }
6362 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name);  */
6363   ret = [[NSString stringWithUTF8String: name] UTF8String];
6364   xfree (name);
6365   return ret;
6369 void
6370 syms_of_nsterm (void)
6372   NSTRACE (syms_of_nsterm);
6374   ns_antialias_threshold = 10.0;
6376   /* from 23+ we need to tell emacs what modifiers there are.. */
6377   DEFSYM (Qmodifier_value, "modifier-value");
6378   DEFSYM (Qalt, "alt");
6379   DEFSYM (Qhyper, "hyper");
6380   DEFSYM (Qmeta, "meta");
6381   DEFSYM (Qsuper, "super");
6382   DEFSYM (Qcontrol, "control");
6383   DEFSYM (Qnone, "none");
6384   Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
6385   Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
6386   Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
6387   Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
6388   Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
6390   DEFVAR_LISP ("ns-input-file", ns_input_file,
6391               "The file specified in the last NS event.");
6392   ns_input_file =Qnil;
6394   DEFVAR_LISP ("ns-input-text", ns_input_text,
6395               "The data received in the last NS text drag event.");
6396   ns_input_text =Qnil;
6398   DEFVAR_LISP ("ns-working-text", ns_working_text,
6399               "String for visualizing working composition sequence.");
6400   ns_working_text =Qnil;
6402   DEFVAR_LISP ("ns-input-font", ns_input_font,
6403               "The font specified in the last NS event.");
6404   ns_input_font =Qnil;
6406   DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
6407               "The fontsize specified in the last NS event.");
6408   ns_input_fontsize =Qnil;
6410   DEFVAR_LISP ("ns-input-line", ns_input_line,
6411                "The line specified in the last NS event.");
6412   ns_input_line =Qnil;
6414   DEFVAR_LISP ("ns-input-color", ns_input_color,
6415                "The color specified in the last NS event.");
6416   ns_input_color =Qnil;
6418   DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
6419                "The service name specified in the last NS event.");
6420   ns_input_spi_name =Qnil;
6422   DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
6423                "The service argument specified in the last NS event.");
6424   ns_input_spi_arg =Qnil;
6426   DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
6427                "This variable describes the behavior of the alternate or option key.\n\
6428 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6429 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6430 at all, allowing it to be used at a lower level for accented character entry.");
6431   ns_alternate_modifier = Qmeta;
6433   DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
6434                "This variable describes the behavior of the right alternate or option key.\n\
6435 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6436 Set to left means be the same key as `ns-alternate-modifier'.\n\
6437 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6438 at all, allowing it to be used at a lower level for accented character entry.");
6439   ns_right_alternate_modifier = Qleft;
6441   DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
6442                "This variable describes the behavior of the command key.\n\
6443 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6444   ns_command_modifier = Qsuper;
6446   DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
6447                "This variable describes the behavior of the right command key.\n\
6448 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6449 Set to left means be the same key as `ns-command-modifier'.\n\
6450 Set to none means that the command / option key is not interpreted by Emacs\n\
6451 at all, allowing it to be used at a lower level for accented character entry.");
6452   ns_right_command_modifier = Qleft;
6454   DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
6455                "This variable describes the behavior of the control key.\n\
6456 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6457   ns_control_modifier = Qcontrol;
6459   DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
6460                "This variable describes the behavior of the right control key.\n\
6461 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6462 Set to left means be the same key as `ns-control-modifier'.\n\
6463 Set to none means that the control / option key is not interpreted by Emacs\n\
6464 at all, allowing it to be used at a lower level for accented character entry.");
6465   ns_right_control_modifier = Qleft;
6467   DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
6468                "This variable describes the behavior of the function key (on laptops).\n\
6469 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6470 Set to none means that the function key is not interpreted by Emacs at all,\n\
6471 allowing it to be used at a lower level for accented character entry.");
6472   ns_function_modifier = Qnone;
6474   DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
6475                "Non-nil (the default) means to render text antialiased. Only has an effect on OS X Panther and above.");
6476   ns_antialias_text = Qt;
6478   DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
6479                "Whether to confirm application quit using dialog.");
6480   ns_confirm_quit = Qnil;
6482   staticpro (&ns_display_name_list);
6483   ns_display_name_list = Qnil;
6485   staticpro (&last_mouse_motion_frame);
6486   last_mouse_motion_frame = Qnil;
6488   DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
6489                "Non-nil means that the menu bar is hidden, but appears when the mouse is near.  Only works on OSX 10.6 or later.");
6490   ns_auto_hide_menu_bar = Qnil;
6492   /* TODO: move to common code */
6493   DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
6494                doc: /* If not nil, Emacs uses toolkit scroll bars.  */);
6495 #ifdef USE_TOOLKIT_SCROLL_BARS
6496   Vx_toolkit_scroll_bars = Qt;
6497 #else
6498   Vx_toolkit_scroll_bars = Qnil;
6499 #endif
6501   /* these are unsupported but we need the declarations to avoid whining
6502      messages from cus-start.el */
6503   DEFVAR_BOOL ("x-use-underline-position-properties",
6504                x_use_underline_position_properties,
6505      doc: /* NOT SUPPORTED UNDER NS.
6506 *Non-nil means make use of UNDERLINE_POSITION font properties.
6507 A value of nil means ignore them.  If you encounter fonts with bogus
6508 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
6509 to 4.1, set this to nil.
6511 NOTE: Not supported on Mac yet.  */);
6512   x_use_underline_position_properties = 0;
6514   DEFVAR_BOOL ("x-underline-at-descent-line",
6515                x_underline_at_descent_line,
6516      doc: /* NOT SUPPORTED UNDER NS.
6517 *Non-nil means to draw the underline at the same place as the descent line.
6518 A value of nil means to draw the underline according to the value of the
6519 variable `x-use-underline-position-properties', which is usually at the
6520 baseline level.  The default value is nil.  */);
6521   x_underline_at_descent_line = 0;
6523   /* Tell emacs about this window system. */
6524   Fprovide (intern ("ns"), Qnil);