Avoid infloop when scrolling conservatively (Bug#7537).
[emacs.git] / src / nsterm.m
blob43e53cb30e7c13c71b8ca56e84d486b60c317e9d
1 /* NeXT/Open/GNUstep / MacOSX communication module.
2    Copyright (C) 1989, 1993, 1994, 2005, 2006, 2008, 2009, 2010
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 /* Lisp communications */
139 Lisp_Object ns_input_file, ns_input_font, ns_input_fontsize, ns_input_line;
140 Lisp_Object ns_input_color, ns_input_text, ns_working_text;
141 Lisp_Object ns_input_spi_name, ns_input_spi_arg;
142 Lisp_Object Vx_toolkit_scroll_bars;
143 static Lisp_Object Qmodifier_value;
144 Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper, Qnone;
145 extern Lisp_Object Qcursor_color, Qcursor_type, Qns, Qleft;
147 /* Specifies which emacs modifier should be generated when NS receives
148    the Alternate modifier.  May be Qnone or any of the modifier lisp symbols. */
149 Lisp_Object ns_alternate_modifier;
151 /* Specifies which emacs modifier should be generated when NS receives
152    the right Alternate modifier.  Has same values as ns_alternate_modifier plus
153    the value Qleft which means whatever value ns_alternate_modifier has.  */
154 Lisp_Object ns_right_alternate_modifier;
156 /* Specifies which emacs modifier should be generated when NS receives
157    the Command modifier.  May be any of the modifier lisp symbols. */
158 Lisp_Object ns_command_modifier;
160 /* Specifies which emacs modifier should be generated when NS receives
161    the Control modifier.  May be any of the modifier lisp symbols. */
162 Lisp_Object ns_control_modifier;
164 /* Specifies which emacs modifier should be generated when NS receives
165    the Function modifier (laptops).  May be any of the modifier lisp symbols. */
166 Lisp_Object ns_function_modifier;
168 /* Control via default 'GSFontAntiAlias' on OS X and GNUstep. */
169 Lisp_Object ns_antialias_text;
171 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
172    the maximum font size to NOT antialias.  On GNUstep there is currently
173    no way to control this behavior. */
174 float ns_antialias_threshold;
176 /* Used to pick up AppleHighlightColor on OS X */
177 NSString *ns_selection_color;
179 /* Confirm on exit. */
180 Lisp_Object ns_confirm_quit;
182 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
183 NSString *ns_app_name = @"Emacs";  /* default changed later */
185 /* Display variables */
186 struct ns_display_info *x_display_list; /* Chain of existing displays */
187 Lisp_Object ns_display_name_list;
188 long context_menu_value = 0;
190 /* display update */
191 NSPoint last_mouse_motion_position;
192 static NSRect last_mouse_glyph;
193 static unsigned long last_mouse_movement_time = 0;
194 static Lisp_Object last_mouse_motion_frame;
195 static EmacsScroller *last_mouse_scroll_bar = nil;
196 static struct frame *ns_updating_frame;
197 static NSView *focus_view = NULL;
198 static int ns_window_num =0;
199 static NSRect uRect;
200 static BOOL gsaved = NO;
201 BOOL ns_in_resize = NO;
202 static BOOL ns_fake_keydown = NO;
203 int ns_tmp_flags; /* FIXME */
204 struct nsfont_info *ns_tmp_font; /* FIXME */
205 /*static int debug_lock = 0; */
207 /* event loop */
208 static BOOL send_appdefined = YES;
209 static NSEvent *last_appdefined_event = 0;
210 static NSTimer *timed_entry = 0;
211 static NSTimer *fd_entry = nil;
212 static NSTimer *scroll_repeat_entry = nil;
213 static fd_set select_readfds, t_readfds;
214 static struct timeval select_timeout;
215 static int select_nfds;
216 static NSAutoreleasePool *outerpool;
217 static struct input_event *emacs_event = NULL;
218 static struct input_event *q_event_ptr = NULL;
219 static int n_emacs_events_pending = 0;
220 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
221   *ns_pending_service_args;
222 static BOOL inNsSelect = 0;
224 /* Convert modifiers in a NeXTSTEP event to emacs style modifiers.  */
225 #define NS_FUNCTION_KEY_MASK 0x800000
226 #define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
227 #define EV_MODIFIERS(e)                               \
228     ((([e modifierFlags] & NSHelpKeyMask) ?           \
229            hyper_modifier : 0)                        \
230      | (!EQ (ns_right_alternate_modifier, Qleft) && \
231         (([e modifierFlags] & NSRightAlternateKeyMask) \
232          == NSRightAlternateKeyMask) ? \
233            parse_solitary_modifier (ns_right_alternate_modifier) : 0) \
234      | (([e modifierFlags] & NSAlternateKeyMask) ?                 \
235            parse_solitary_modifier (ns_alternate_modifier) : 0)   \
236      | (([e modifierFlags] & NSShiftKeyMask) ?     \
237            shift_modifier : 0)                        \
238      | (([e modifierFlags] & NSControlKeyMask) ?      \
239            parse_solitary_modifier (ns_control_modifier) : 0)     \
240      | (([e modifierFlags] & NS_FUNCTION_KEY_MASK) ?  \
241            parse_solitary_modifier (ns_function_modifier) : 0)    \
242      | (([e modifierFlags] & NSCommandKeyMask) ?      \
243            parse_solitary_modifier (ns_command_modifier):0))
245 #define EV_UDMODIFIERS(e)                                      \
246     ((([e type] == NSLeftMouseDown) ? down_modifier : 0)       \
247      | (([e type] == NSRightMouseDown) ? down_modifier : 0)    \
248      | (([e type] == NSOtherMouseDown) ? down_modifier : 0)    \
249      | (([e type] == NSLeftMouseDragged) ? down_modifier : 0)  \
250      | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
251      | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
252      | (([e type] == NSLeftMouseUp)   ? up_modifier   : 0)     \
253      | (([e type] == NSRightMouseUp)   ? up_modifier   : 0)    \
254      | (([e type] == NSOtherMouseUp)   ? up_modifier   : 0))
256 #define EV_BUTTON(e)                                                         \
257     ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 :    \
258       (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
259      [e buttonNumber] - 1)
261 /* Convert the time field to a timestamp in milliseconds. */
262 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
264 /* This is a piece of code which is common to all the event handling
265    methods.  Maybe it should even be a function.  */
266 #define EV_TRAILER(e)                                         \
267   {                                                           \
268   XSETFRAME (emacs_event->frame_or_window, emacsframe);       \
269   if (e) emacs_event->timestamp = EV_TIMESTAMP (e);           \
270   n_emacs_events_pending++;                                   \
271   kbd_buffer_store_event_hold (emacs_event, q_event_ptr);     \
272   EVENT_INIT (*emacs_event);                                  \
273   ns_send_appdefined (-1);                                    \
274   }
276 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
278 /* TODO: get rid of need for these forward declarations */
279 static void ns_condemn_scroll_bars (struct frame *f);
280 static void ns_judge_scroll_bars (struct frame *f);
281 void x_set_frame_alpha (struct frame *f);
283 /* unused variables needed for compatibility reasons */
284 int x_use_underline_position_properties, x_underline_at_descent_line;
285 /* FIXME: figure out what to do with underline_minimum_offset. */
288 /* ==========================================================================
290     Utilities
292    ========================================================================== */
295 static Lisp_Object
296 append2 (Lisp_Object list, Lisp_Object item)
297 /* --------------------------------------------------------------------------
298    Utility to append to a list
299    -------------------------------------------------------------------------- */
301   Lisp_Object array[2];
302   array[0] = list;
303   array[1] = Fcons (item, Qnil);
304   return Fnconc (2, &array[0]);
308 void
309 ns_init_paths ()
310 /* --------------------------------------------------------------------------
311    Used to allow emacs to find its resources under Emacs.app
312    Called from emacs.c at startup.
313    -------------------------------------------------------------------------- */
315   NSBundle *bundle = [NSBundle mainBundle];
316   NSString *binDir = [bundle bundlePath], *resourceDir = [bundle resourcePath];
317   NSString *resourcePath, *resourcePaths;
318   NSRange range;
319   BOOL onWindows = NO; /* how do I determine this? */
320   NSString *pathSeparator = onWindows ? @";" : @":";
321   NSFileManager *fileManager = [NSFileManager defaultManager];
322   BOOL isDir;
323 /*NSLog (@"ns_init_paths: '%@'\n%@\n", [[NSBundle mainBundle] bundlePath], [[NSBundle mainBundle] resourcePath]); */
325   /* get bindir from base */
326   range = [resourceDir rangeOfString: @"Contents"];
327   if (range.location != NSNotFound)
328     {
329       binDir = [binDir stringByAppendingPathComponent: @"Contents"];
330 #ifdef NS_IMPL_COCOA
331       binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
332 #endif
333     }
335   /* the following based on Andrew Choi's init_mac_osx_environment () */
336   if (!getenv ("EMACSLOADPATH"))
337     {
338       NSArray *paths = [resourceDir stringsByAppendingPaths:
339                                   [NSArray arrayWithObjects:
340                                          @"site-lisp", @"lisp", @"leim", nil]];
341       NSEnumerator *pathEnum = [paths objectEnumerator];
342       resourcePaths = @"";
343       while (resourcePath = [pathEnum nextObject])
344         {
345           if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
346             if (isDir)
347               {
348                 if ([resourcePaths length] > 0)
349                   resourcePaths
350                     = [resourcePaths stringByAppendingString: pathSeparator];
351                 resourcePaths
352                   = [resourcePaths stringByAppendingString: resourcePath];
353               }
354         }
355       if ([resourcePaths length] > 0)
356         setenv ("EMACSLOADPATH", [resourcePaths UTF8String], 1);
357 /*NSLog (@"loadPath: '%@'\n", resourcePaths); */
358     }
360   if (!getenv ("EMACSPATH"))
361     {
362       NSArray *paths = [binDir stringsByAppendingPaths:
363                                   [NSArray arrayWithObjects: @"bin",
364                                                              @"lib-exec", nil]];
365       NSEnumerator *pathEnum = [paths objectEnumerator];
366       resourcePaths = @"";
367       while (resourcePath = [pathEnum nextObject])
368         {
369           if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
370             if (isDir)
371               {
372                 if ([resourcePaths length] > 0)
373                   resourcePaths
374                     = [resourcePaths stringByAppendingString: pathSeparator];
375                 resourcePaths
376                   = [resourcePaths stringByAppendingString: resourcePath];
377               }
378         }
379       if ([resourcePaths length] > 0)
380         setenv ("EMACSPATH", [resourcePaths UTF8String], 1);
381     }
383   resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
384   if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
385     {
386       if (isDir)
387         {
388           if (!getenv ("EMACSDATA"))
389             setenv ("EMACSDATA", [resourcePath UTF8String], 1);
390           if (!getenv ("EMACSDOC"))
391             setenv ("EMACSDOC", [resourcePath UTF8String], 1);
392         }
393     }
395   if (!getenv ("INFOPATH"))
396     {
397       resourcePath = [resourceDir stringByAppendingPathComponent: @"info"];
398       if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
399         if (isDir)
400           setenv ("INFOPATH", [[resourcePath stringByAppendingString: @":"]
401                                              UTF8String], 1);
402       /* Note, extra colon needed to cause merge w/later user additions. */
403     }
407 static int
408 timeval_subtract (struct timeval *result, struct timeval x, struct timeval y)
409 /* --------------------------------------------------------------------------
410    Subtract the `struct timeval' values X and Y, storing the result in RESULT.
411    Return 1 if the difference is negative, otherwise 0.
412    -------------------------------------------------------------------------- */
414   /* Perform the carry for the later subtraction by updating y.
415      This is safer because on some systems
416      the tv_sec member is unsigned.  */
417   if (x.tv_usec < y.tv_usec)
418     {
419       int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
420       y.tv_usec -= 1000000 * nsec;
421       y.tv_sec += nsec;
422     }
423   if (x.tv_usec - y.tv_usec > 1000000)
424     {
425       int nsec = (y.tv_usec - x.tv_usec) / 1000000;
426       y.tv_usec += 1000000 * nsec;
427       y.tv_sec -= nsec;
428     }
430   /* Compute the time remaining to wait.  tv_usec is certainly positive.  */
431   result->tv_sec = x.tv_sec - y.tv_sec;
432   result->tv_usec = x.tv_usec - y.tv_usec;
434   /* Return indication of whether the result should be considered negative.  */
435   return x.tv_sec < y.tv_sec;
438 static void
439 ns_timeout (int usecs)
440 /* --------------------------------------------------------------------------
441      Blocking timer utility used by ns_ring_bell
442    -------------------------------------------------------------------------- */
444   struct timeval wakeup;
446   EMACS_GET_TIME (wakeup);
448   /* Compute time to wait until, propagating carry from usecs.  */
449   wakeup.tv_usec += usecs;
450   wakeup.tv_sec += (wakeup.tv_usec / 1000000);
451   wakeup.tv_usec %= 1000000;
453   /* Keep waiting until past the time wakeup.  */
454   while (1)
455     {
456       struct timeval timeout;
458       EMACS_GET_TIME (timeout);
460       /* In effect, timeout = wakeup - timeout.
461          Break if result would be negative.  */
462       if (timeval_subtract (&timeout, wakeup, timeout))
463         break;
465       /* Try to wait that long--but we might wake up sooner.  */
466       select (0, NULL, NULL, NULL, &timeout);
467     }
471 void
472 ns_release_object (void *obj)
473 /* --------------------------------------------------------------------------
474     Release an object (callable from C)
475    -------------------------------------------------------------------------- */
477     [(id)obj release];
481 void
482 ns_retain_object (void *obj)
483 /* --------------------------------------------------------------------------
484     Retain an object (callable from C)
485    -------------------------------------------------------------------------- */
487     [(id)obj retain];
491 void *
492 ns_alloc_autorelease_pool ()
493 /* --------------------------------------------------------------------------
494      Allocate a pool for temporary objects (callable from C)
495    -------------------------------------------------------------------------- */
497   return [[NSAutoreleasePool alloc] init];
501 void
502 ns_release_autorelease_pool (void *pool)
503 /* --------------------------------------------------------------------------
504      Free a pool and temporary objects it refers to (callable from C)
505    -------------------------------------------------------------------------- */
507   ns_release_object (pool);
512 /* ==========================================================================
514     Focus (clipping) and screen update
516    ========================================================================== */
518 static NSRect
519 ns_resize_handle_rect (NSWindow *window)
521   NSRect r = [window frame];
522   r.origin.x = r.size.width - RESIZE_HANDLE_SIZE;
523   r.origin.y = 0;
524   r.size.width = r.size.height = RESIZE_HANDLE_SIZE;
525   return r;
529 static void
530 ns_update_begin (struct frame *f)
531 /* --------------------------------------------------------------------------
532    Prepare for a grouped sequence of drawing calls
533    external (RIF) call; whole frame, called before update_window_begin
534    -------------------------------------------------------------------------- */
536   NSView *view = FRAME_NS_VIEW (f);
537   NSTRACE (ns_update_begin);
539   ns_updating_frame = f;
540   [view lockFocus];
542 #ifdef NS_IMPL_GNUSTEP
543   uRect = NSMakeRect (0, 0, 0, 0);
544 #endif
548 static void
549 ns_update_window_begin (struct window *w)
550 /* --------------------------------------------------------------------------
551    Prepare for a grouped sequence of drawing calls
552    external (RIF) call; for one window, called after update_begin
553    -------------------------------------------------------------------------- */
555   struct frame *f = XFRAME (WINDOW_FRAME (w));
556   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
557   NSTRACE (ns_update_window_begin);
559   updated_window = w;
560   set_output_cursor (&w->cursor);
562   BLOCK_INPUT;
564   if (f == dpyinfo->mouse_face_mouse_frame)
565     {
566       /* Don't do highlighting for mouse motion during the update.  */
567       dpyinfo->mouse_face_defer = 1;
569         /* If the frame needs to be redrawn,
570            simply forget about any prior mouse highlighting.  */
571       if (FRAME_GARBAGED_P (f))
572         dpyinfo->mouse_face_window = Qnil;
574       /* (further code for mouse faces ifdef'd out in other terms elided) */
575     }
577   UNBLOCK_INPUT;
581 static void
582 ns_update_window_end (struct window *w, int cursor_on_p,
583                       int mouse_face_overwritten_p)
584 /* --------------------------------------------------------------------------
585    Finished a grouped sequence of drawing calls
586    external (RIF) call; for one window called before update_end
587    -------------------------------------------------------------------------- */
589   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (XFRAME (w->frame));
591   /* note: this fn is nearly identical in all terms */
592   if (!w->pseudo_window_p)
593     {
594       BLOCK_INPUT;
596       if (cursor_on_p)
597         display_and_set_cursor (w, 1,
598                                 output_cursor.hpos, output_cursor.vpos,
599                                 output_cursor.x, output_cursor.y);
601       if (draw_window_fringes (w, 1))
602         x_draw_vertical_border (w);
604       UNBLOCK_INPUT;
605     }
607   /* If a row with mouse-face was overwritten, arrange for
608      frame_up_to_date to redisplay the mouse highlight.  */
609   if (mouse_face_overwritten_p)
610     {
611       dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
612       dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
613       dpyinfo->mouse_face_window = Qnil;
614     }
616   updated_window = NULL;
617   NSTRACE (update_window_end);
621 static void
622 ns_update_end (struct frame *f)
623 /* --------------------------------------------------------------------------
624    Finished a grouped sequence of drawing calls
625    external (RIF) call; for whole frame, called after update_window_end
626    -------------------------------------------------------------------------- */
628   NSView *view = FRAME_NS_VIEW (f);
630 /*   if (f == FRAME_NS_DISPLAY_INFO (f)->mouse_face_mouse_frame) */
631     FRAME_NS_DISPLAY_INFO (f)->mouse_face_defer = 0;
633   BLOCK_INPUT;
635 #ifdef NS_IMPL_GNUSTEP
636   /* trigger flush only in the rectangle we tracked as being drawn */
637   [view unlockFocusNeedsFlush: NO];
638 /*fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", uRect.origin.x, uRect.origin.y, uRect.size.width, uRect.size.height); */
639   [view lockFocusInRect: uRect];
640 #endif
642   [view unlockFocus];
643   [[view window] flushWindow];
645   UNBLOCK_INPUT;
646   ns_updating_frame = NULL;
647   NSTRACE (ns_update_end);
651 static void
652 ns_flush (struct frame *f)
653 /* --------------------------------------------------------------------------
654    external (RIF) call
655    NS impl is no-op since currently we flush in ns_update_end and elsewhere
656    -------------------------------------------------------------------------- */
658     NSTRACE (ns_flush);
662 static void
663 ns_focus (struct frame *f, NSRect *r, int n)
664 /* --------------------------------------------------------------------------
665    Internal: Focus on given frame.  During small local updates this is used to
666      draw, however during large updates, ns_update_begin and ns_update_end are
667      called to wrap the whole thing, in which case these calls are stubbed out.
668      Except, on GNUstep, we accumulate the rectangle being drawn into, because
669      the back end won't do this automatically, and will just end up flushing
670      the entire window.
671    -------------------------------------------------------------------------- */
673 //  NSTRACE (ns_focus);
674 #ifdef NS_IMPL_GNUSTEP
675   NSRect u;
676     if (n == 2)
677       u = NSUnionRect (r[0], r[1]);
678     else if (r)
679       u = *r;
680 #endif
681 /* static int c =0;
682    fprintf (stderr, "focus: %d", c++);
683    if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
684    fprintf (stderr, "\n"); */
686   if (f != ns_updating_frame)
687     {
688       NSView *view = FRAME_NS_VIEW (f);
689       if (view != focus_view)
690         {
691           if (focus_view != NULL)
692             {
693               [focus_view unlockFocus];
694               [[focus_view window] flushWindow];
695 /*debug_lock--; */
696             }
698           if (view)
699 #ifdef NS_IMPL_GNUSTEP
700             r ? [view lockFocusInRect: u] : [view lockFocus];
701 #else
702             [view lockFocus];
703 #endif
704           focus_view = view;
705 /*if (view) debug_lock++; */
706         }
707 #ifdef NS_IMPL_GNUSTEP
708       else
709         {
710           /* more than one rect being drawn into */
711           if (view && r)
712             {
713               [view unlockFocus]; /* add prev rect to redraw list */
714               [view lockFocusInRect: u]; /* focus for draw in new rect */
715             }
716         }
717 #endif
718     }
719 #ifdef NS_IMPL_GNUSTEP
720   else
721     {
722       /* in batch mode, but in GNUstep must still track rectangles explicitly */
723       uRect = (r ? NSUnionRect (uRect, u) : [FRAME_NS_VIEW (f) visibleRect]);
724     }
725 #endif
727   /* clipping */
728   if (r)
729     {
730       [[NSGraphicsContext currentContext] saveGraphicsState];
731       if (n == 2)
732         NSRectClipList (r, 2);
733       else
734         NSRectClip (*r);
735       gsaved = YES;
736     }
740 static void
741 ns_unfocus (struct frame *f)
742 /* --------------------------------------------------------------------------
743      Internal: Remove focus on given frame
744    -------------------------------------------------------------------------- */
746 //  NSTRACE (ns_unfocus);
748   if (gsaved)
749     {
750       [[NSGraphicsContext currentContext] restoreGraphicsState];
751       gsaved = NO;
752     }
754   if (f != ns_updating_frame)
755     {
756       if (focus_view != NULL)
757         {
758           [focus_view unlockFocus];
759           [[focus_view window] flushWindow];
760           focus_view = NULL;
761 /*debug_lock--; */
762         }
763     }
767 static void
768 ns_clip_to_row (struct window *w, struct glyph_row *row, int area, BOOL gc)
769 /* --------------------------------------------------------------------------
770      Internal (but parallels other terms): Focus drawing on given row
771    -------------------------------------------------------------------------- */
773   struct frame *f = XFRAME (WINDOW_FRAME (w));
774   NSRect clip_rect;
775   int window_x, window_y, window_width;
777   window_box (w, area, &window_x, &window_y, &window_width, 0);
779   clip_rect.origin.x = window_x - FRAME_INTERNAL_BORDER_WIDTH (f);
780   clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
781   clip_rect.origin.y = max (clip_rect.origin.y, window_y);
782   clip_rect.size.width = window_width + 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
783   clip_rect.size.height = row->visible_height;
785   /* allow a full-height row at the top when requested
786      (used to draw fringe all the way through internal border area) */
787   if (gc && clip_rect.origin.y < 5)
788     {
789       clip_rect.origin.y -= FRAME_INTERNAL_BORDER_WIDTH (f);
790       clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
791     }
793   /* likewise at bottom */
794   if (gc &&
795       FRAME_PIXEL_HEIGHT (f) - (clip_rect.origin.y + clip_rect.size.height) < 5)
796     clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
798   ns_focus (f, &clip_rect, 1);
802 static void
803 ns_ring_bell ()
804 /* --------------------------------------------------------------------------
805      "Beep" routine
806    -------------------------------------------------------------------------- */
808   NSTRACE (ns_ring_bell);
809   if (visible_bell)
810     {
811       NSAutoreleasePool *pool;
812       struct frame *frame = SELECTED_FRAME ();
813       NSView *view;
815       BLOCK_INPUT;
816       pool = [[NSAutoreleasePool alloc] init];
818       view = FRAME_NS_VIEW (frame);
819       if (view != nil)
820         {
821           NSRect r, surr;
822           NSPoint dim = NSMakePoint (128, 128);
824           r = [view bounds];
825           r.origin.x += (r.size.width - dim.x) / 2;
826           r.origin.y += (r.size.height - dim.y) / 2;
827           r.size.width = dim.x;
828           r.size.height = dim.y;
829           surr = NSInsetRect (r, -2, -2);
830           ns_focus (frame, &surr, 1);
831           [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
832           [ns_lookup_indexed_color (NS_FACE_FOREGROUND
833                                       (FRAME_DEFAULT_FACE (frame)), frame) set];
834           NSRectFill (r);
835           [[view window] flushWindow];
836           ns_timeout (150000);
837           [[view window] restoreCachedImage];
838           [[view window] flushWindow];
839           ns_unfocus (frame);
840         }
841       [pool release];
842       UNBLOCK_INPUT;
843     }
844   else
845     {
846       NSBeep ();
847     }
851 static void
852 ns_reset_terminal_modes (struct terminal *terminal)
853 /*  Externally called as hook */
855   NSTRACE (ns_reset_terminal_modes);
859 static void
860 ns_set_terminal_modes (struct terminal *terminal)
861 /*  Externally called as hook */
863   NSTRACE (ns_set_terminal_modes);
868 /* ==========================================================================
870     Frame / window manager related functions
872    ========================================================================== */
875 static void
876 ns_raise_frame (struct frame *f)
877 /* --------------------------------------------------------------------------
878      Bring window to foreground and make it active
879    -------------------------------------------------------------------------- */
881   NSView *view = FRAME_NS_VIEW (f);
882   check_ns ();
883   BLOCK_INPUT;
884   FRAME_SAMPLE_VISIBILITY (f);
885   if (FRAME_VISIBLE_P (f))
886     {
887       [[view window] makeKeyAndOrderFront: NSApp];
888     }
889   UNBLOCK_INPUT;
893 static void
894 ns_lower_frame (struct frame *f)
895 /* --------------------------------------------------------------------------
896      Send window to back
897    -------------------------------------------------------------------------- */
899   NSView *view = FRAME_NS_VIEW (f);
900   check_ns ();
901   BLOCK_INPUT;
902   [[view window] orderBack: NSApp];
903   UNBLOCK_INPUT;
907 static void
908 ns_frame_raise_lower (struct frame *f, int raise)
909 /* --------------------------------------------------------------------------
910      External (hook)
911    -------------------------------------------------------------------------- */
913   NSTRACE (ns_frame_raise_lower);
915   if (raise)
916     ns_raise_frame (f);
917   else
918     ns_lower_frame (f);
922 static void
923 ns_frame_rehighlight (struct frame *frame)
924 /* --------------------------------------------------------------------------
925      External (hook): called on things like window switching within frame
926    -------------------------------------------------------------------------- */
928   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
929   struct frame *old_highlight = dpyinfo->x_highlight_frame;
931   NSTRACE (ns_frame_rehighlight);
932   if (dpyinfo->x_focus_frame)
933     {
934       dpyinfo->x_highlight_frame
935         = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
936            ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
937            : dpyinfo->x_focus_frame);
938       if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
939         {
940           FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
941           dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
942         }
943     }
944   else
945       dpyinfo->x_highlight_frame = 0;
947   if (dpyinfo->x_highlight_frame &&
948          dpyinfo->x_highlight_frame != old_highlight)
949     {
950       if (old_highlight)
951         {
952           x_update_cursor (old_highlight, 1);
953           x_set_frame_alpha (old_highlight);
954         }
955       if (dpyinfo->x_highlight_frame)
956         {
957           x_update_cursor (dpyinfo->x_highlight_frame, 1);
958           x_set_frame_alpha (dpyinfo->x_highlight_frame);
959         }
960     }
964 void
965 x_make_frame_visible (struct frame *f)
966 /* --------------------------------------------------------------------------
967      External: Show the window (X11 semantics)
968    -------------------------------------------------------------------------- */
970   NSTRACE (x_make_frame_visible);
971   /* XXX: at some points in past this was not needed, as the only place that
972      called this (frame.c:Fraise_frame ()) also called raise_lower;
973      if this ends up the case again, comment this out again. */
974   if (!FRAME_VISIBLE_P (f))
975     {
976       f->async_visible = 1;
977       ns_raise_frame (f);
978     }
982 void
983 x_make_frame_invisible (struct frame *f)
984 /* --------------------------------------------------------------------------
985      External: Hide the window (X11 semantics)
986    -------------------------------------------------------------------------- */
988   NSView * view = FRAME_NS_VIEW (f);
989   NSTRACE (x_make_frame_invisible);
990   check_ns ();
991   [[view window] orderOut: NSApp];
992   f->async_visible = 0;
993   f->async_iconified = 0;
997 void
998 x_iconify_frame (struct frame *f)
999 /* --------------------------------------------------------------------------
1000      External: Iconify window
1001    -------------------------------------------------------------------------- */
1003   NSView * view = FRAME_NS_VIEW (f);
1004   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1005   NSTRACE (x_iconify_frame);
1006   check_ns ();
1008   if (dpyinfo->x_highlight_frame == f)
1009     dpyinfo->x_highlight_frame = 0;
1011   if ([[view window] windowNumber] <= 0)
1012     {
1013       /* the window is still deferred.  Make it very small, bring it
1014          on screen and order it out. */
1015       NSRect s = { { 100, 100}, {0, 0} };
1016       NSRect t;
1017       t = [[view window] frame];
1018       [[view window] setFrame: s display: NO];
1019       [[view window] orderBack: NSApp];
1020       [[view window] orderOut: NSApp];
1021       [[view window] setFrame: t display: NO];
1022     }
1023   [[view window] miniaturize: NSApp];
1027 void
1028 x_destroy_window (struct frame *f)
1029 /* --------------------------------------------------------------------------
1030      External: Delete the window
1031    -------------------------------------------------------------------------- */
1033   NSView *view = FRAME_NS_VIEW (f);
1034   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1035   NSTRACE (x_destroy_window);
1036   check_ns ();
1038   [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1040   BLOCK_INPUT;
1042   free_frame_menubar (f);
1044   if (FRAME_FACE_CACHE (f))
1045     free_frame_faces (f);
1047   if (f == dpyinfo->x_focus_frame)
1048     dpyinfo->x_focus_frame = 0;
1049   if (f == dpyinfo->x_highlight_frame)
1050     dpyinfo->x_highlight_frame = 0;
1051   if (f == dpyinfo->mouse_face_mouse_frame)
1052     {
1053       dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
1054       dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
1055       dpyinfo->mouse_face_window = Qnil;
1056       dpyinfo->mouse_face_deferred_gc = 0;
1057       dpyinfo->mouse_face_mouse_frame = 0;
1058     }
1060   xfree (f->output_data.ns);
1062   [[view window] close];
1063   [view release];
1065   ns_window_num--;
1066   UNBLOCK_INPUT;
1070 void
1071 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1072 /* --------------------------------------------------------------------------
1073      External: Position the window
1074    -------------------------------------------------------------------------- */
1076   NSScreen *screen;
1077   NSView *view = FRAME_NS_VIEW (f);
1079   NSTRACE (x_set_offset);
1081   BLOCK_INPUT;
1083   f->left_pos = xoff;
1084   f->top_pos = yoff;
1086   if (view != nil && (screen = [[view window] screen]))
1087     {
1088       f->left_pos = f->size_hint_flags & XNegative
1089         ? [screen visibleFrame].size.width + f->left_pos - FRAME_PIXEL_WIDTH (f)
1090         : f->left_pos;
1091       /* We use visibleFrame here to take menu bar into account.
1092          Ideally we should also adjust left/top with visibleFrame.offset.  */
1093          
1094       f->top_pos = f->size_hint_flags & YNegative
1095         ? ([screen visibleFrame].size.height + f->top_pos
1096            - FRAME_PIXEL_HEIGHT (f) - FRAME_NS_TITLEBAR_HEIGHT (f)
1097            - FRAME_TOOLBAR_HEIGHT (f))
1098         : f->top_pos;
1099 #ifdef NS_IMPL_GNUSTEP
1100       if (f->left_pos < 100)
1101         f->left_pos = 100;  /* don't overlap menu */
1102 #endif
1103       [[view window] setFrameTopLeftPoint:
1104                        NSMakePoint (SCREENMAXBOUND (f->left_pos),
1105                                     SCREENMAXBOUND ([screen frame].size.height
1106                                                     - NS_TOP_POS (f)))];
1107       f->size_hint_flags &= ~(XNegative|YNegative);
1108     }
1110   UNBLOCK_INPUT;
1114 void
1115 x_set_window_size (struct frame *f, int change_grav, int cols, int rows)
1116 /* --------------------------------------------------------------------------
1117      Adjust window pixel size based on given character grid size
1118      Impl is a bit more complex than other terms, need to do some
1119      internal clipping and also pay attention to screen constraints.
1120    -------------------------------------------------------------------------- */
1122   EmacsView *view = FRAME_NS_VIEW (f);
1123   EmacsToolbar *toolbar = [view toolbar];
1124   NSWindow *window = [view window];
1125   NSScreen *screen = [window screen];
1126   NSRect wr = [window frame];
1127   int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1128   int pixelwidth, pixelheight;
1129   static int oldRows, oldCols, oldFontWidth, oldFontHeight;
1130   static int oldTB;
1131   static struct frame *oldF;
1133   NSTRACE (x_set_window_size);
1135   if (view == nil ||
1136       (f == oldF
1137        && rows == oldRows && cols == oldCols
1138        && oldFontWidth == FRAME_COLUMN_WIDTH (f)
1139        && oldFontHeight == FRAME_LINE_HEIGHT (f)
1140        && oldTB == tb))
1141     return;
1143 /*fprintf (stderr, "\tsetWindowSize: %d x %d, font size %d x %d\n", cols, rows, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f)); */
1145   BLOCK_INPUT;
1147   check_frame_size (f, &rows, &cols);
1148   oldF = f;
1149   oldRows = rows;
1150   oldCols = cols;
1151   oldFontWidth = FRAME_COLUMN_WIDTH (f);
1152   oldFontHeight = FRAME_LINE_HEIGHT (f);
1153   oldTB = tb;
1155   f->scroll_bar_actual_width = NS_SCROLL_BAR_WIDTH (f);
1156   compute_fringe_widths (f, 0);
1158   pixelwidth =  FRAME_TEXT_COLS_TO_PIXEL_WIDTH   (f, cols);
1159   pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
1161   /* If we have a toolbar, take its height into account. */
1162   if (tb)
1163     /* NOTE: previously this would generate wrong result if toolbar not
1164              yet displayed and fixing toolbar_height=32 helped, but
1165              now (200903) seems no longer needed */
1166     FRAME_TOOLBAR_HEIGHT (f) =
1167       NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1168         - FRAME_NS_TITLEBAR_HEIGHT (f);
1169   else
1170     FRAME_TOOLBAR_HEIGHT (f) = 0;
1172   wr.size.width = pixelwidth + f->border_width;
1173   wr.size.height = pixelheight + FRAME_NS_TITLEBAR_HEIGHT (f) 
1174                   + FRAME_TOOLBAR_HEIGHT (f);
1176   /* constrain to screen if we can */
1177   if (screen)
1178     {
1179       NSSize sz = [screen visibleFrame].size;
1180       NSSize ez = { wr.size.width - sz.width, wr.size.height - sz.height };
1181       if (ez.width > 0)
1182         {
1183           int cr = ez.width / FRAME_COLUMN_WIDTH (f) + 1;
1184           cols -= cr;
1185           oldCols = cols;
1186           wr.size.width -= cr * FRAME_COLUMN_WIDTH (f);
1187           pixelwidth -= cr * FRAME_COLUMN_WIDTH (f);
1188         }
1189       if (ez.height > 0)
1190         {
1191           int rr = ez.height / FRAME_LINE_HEIGHT (f) + 1;
1192           rows -= rr;
1193           oldRows = rows;
1194           wr.size.height -= rr * FRAME_LINE_HEIGHT (f);
1195           pixelheight -= rr * FRAME_LINE_HEIGHT (f);
1196         }
1197       wr.origin.x = f->left_pos;
1198       wr.origin.y = [screen frame].size.height - NS_TOP_POS (f)
1199         - wr.size.height;
1200     }
1202   [view setRows: rows andColumns: cols];
1203   [window setFrame: wr display: YES];
1205 /*fprintf (stderr, "\tx_set_window_size %d, %d\t%d, %d\n", cols, rows, pixelwidth, pixelheight); */
1207   /* This is a trick to compensate for Emacs' managing the scrollbar area
1208      as a fixed number of standard character columns.  Instead of leaving
1209      blank space for the extra, we chopped it off above.  Now for
1210      left-hand scrollbars, we shift all rendering to the left by the
1211      difference between the real width and Emacs' imagined one.  For
1212      right-hand bars, don't worry about it since the extra is never used.
1213      (Obviously doesn't work for vertically split windows tho..) */
1214   NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1215     ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1216                   - NS_SCROLL_BAR_WIDTH (f), 0)
1217     : NSMakePoint (0, 0);
1218   [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1219   [view setBoundsOrigin: origin];
1221   change_frame_size (f, rows, cols, 0, 1, 0); /* pretend, delay, safe */
1222   FRAME_PIXEL_WIDTH (f) = pixelwidth;
1223   FRAME_PIXEL_HEIGHT (f) = pixelheight;
1224 /*  SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */
1226   mark_window_cursors_off (XWINDOW (f->root_window));
1227   cancel_mouse_face (f);
1229   UNBLOCK_INPUT;
1234 /* ==========================================================================
1236     Color management
1238    ========================================================================== */
1241 NSColor *
1242 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1244   struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1245   if (idx < 1 || idx >= color_table->avail)
1246     return nil;
1247   return color_table->colors[idx];
1251 unsigned long
1252 ns_index_color (NSColor *color, struct frame *f)
1254   struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1255   int idx;
1256   NSNumber *index;
1258   if (!color_table->colors)
1259     {
1260       color_table->size = NS_COLOR_CAPACITY;
1261       color_table->avail = 1; /* skip idx=0 as marker */
1262       color_table->colors
1263         = (NSColor **)xmalloc (color_table->size * sizeof (NSColor *));
1264       color_table->colors[0] = nil;
1265       color_table->empty_indices = [[NSMutableSet alloc] init];
1266     }
1268   /* do we already have this color ? */
1269   {
1270     int i;
1271     for (i = 1; i < color_table->avail; i++)
1272       {
1273         if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1274           {
1275             [color_table->colors[i] retain];
1276             return i;
1277           }
1278       }
1279   }
1281   if ([color_table->empty_indices count] > 0)
1282     {
1283       index = [color_table->empty_indices anyObject];
1284       [color_table->empty_indices removeObject: index];
1285       idx = [index unsignedIntValue];
1286     }
1287   else
1288     {
1289       if (color_table->avail == color_table->size)
1290         {
1291           color_table->size += NS_COLOR_CAPACITY;
1292           color_table->colors
1293             = (NSColor **)xrealloc (color_table->colors,
1294                                     color_table->size * sizeof (NSColor *));
1295         }
1296       idx = color_table->avail++;
1297     }
1299   color_table->colors[idx] = color;
1300   [color retain];
1301 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1302   return idx;
1306 void
1307 ns_free_indexed_color (unsigned long idx, struct frame *f)
1309   struct ns_color_table *color_table;
1310   NSColor *color;
1311   NSNumber *index;
1313   if (!f)
1314     return;
1316   color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1318   if (idx <= 0 || idx >= color_table->size) {
1319     message1("ns_free_indexed_color: Color index out of range.\n");
1320     return;
1321   }
1323   index = [NSNumber numberWithUnsignedInt: idx];
1324   if ([color_table->empty_indices containsObject: index]) {
1325     message1("ns_free_indexed_color: attempt to free already freed color.\n");
1326     return;
1327   }
1329   color = color_table->colors[idx];
1330   [color release];
1331   color_table->colors[idx] = nil;
1332   [color_table->empty_indices addObject: [NSNumber numberWithUnsignedInt: idx]];
1333 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1337 static int
1338 ns_get_color (const char *name, NSColor **col)
1339 /* --------------------------------------------------------------------------
1340      Parse a color name
1341    -------------------------------------------------------------------------- */
1342 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1343    X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1344    See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1346   NSColor *new = nil;
1347   static char hex[20];
1348   int scaling;
1349   float r = -1.0, g, b;
1350   NSString *nsname = [NSString stringWithUTF8String: name];
1352 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1353   BLOCK_INPUT;
1355   if ([nsname isEqualToString: @"ns_selection_color"])
1356     {
1357       nsname = ns_selection_color;
1358       name = [ns_selection_color UTF8String];
1359     }
1361   /* First, check for some sort of numeric specification. */
1362   hex[0] = '\0';
1364   if (name[0] == '0' || name[0] == '1' || name[0] == '.')  /* RGB decimal */
1365     {
1366       NSScanner *scanner = [NSScanner scannerWithString: nsname];
1367       [scanner scanFloat: &r];
1368       [scanner scanFloat: &g];
1369       [scanner scanFloat: &b];
1370     }
1371   else if (!strncmp(name, "rgb:", 4))  /* A newer X11 format -- rgb:r/g/b */
1372     {
1373       strncpy (hex, name + 4, 19);
1374       hex[19] = '\0';
1375       scaling = (strlen(hex) - 2) / 3;
1376     }
1377   else if (name[0] == '#')        /* An old X11 format; convert to newer */
1378     {
1379       int len = (strlen(name) - 1);
1380       int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1381       int i;
1382       scaling = strlen(name+start) / 3;
1383       for (i=0; i<3; i++) {
1384         strncpy(hex + i * (scaling + 1), name + start + i * scaling, scaling);
1385         hex[(i+1) * (scaling + 1) - 1] = '/';
1386       }
1387       hex[3 * (scaling + 1) - 1] = '\0';
1388     }
1390   if (hex[0])
1391     {
1392       int rr, gg, bb;
1393       float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1394       if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1395         {
1396           r = rr / fscale;
1397           g = gg / fscale;
1398           b = bb / fscale;
1399         }
1400     }
1402   if (r >= 0.0)
1403     {
1404       *col = [NSColor colorWithCalibratedRed: r green: g blue: b alpha: 1.0];
1405       UNBLOCK_INPUT;
1406       return 0;
1407     }
1409   /* Otherwise, color is expected to be from a list */
1410   {
1411     NSEnumerator *lenum, *cenum;
1412     NSString *name;
1413     NSColorList *clist;
1415 #ifdef NS_IMPL_GNUSTEP
1416     /* XXX: who is wrong, the requestor or the implementation? */
1417     if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1418         == NSOrderedSame)
1419       nsname = @"highlightColor";
1420 #endif
1422     lenum = [[NSColorList availableColorLists] objectEnumerator];
1423     while ( (clist = [lenum nextObject]) && new == nil)
1424       {
1425         cenum = [[clist allKeys] objectEnumerator];
1426         while ( (name = [cenum nextObject]) && new == nil )
1427           {
1428             if ([name compare: nsname
1429                       options: NSCaseInsensitiveSearch] == NSOrderedSame )
1430               new = [clist colorWithKey: name];
1431           }
1432       }
1433   }
1435   if (new)
1436     *col = [new colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1437   UNBLOCK_INPUT;
1438   return new ? 0 : 1;
1442 static NSColor *
1443 ns_get_color_default (const char *name, NSColor *dflt)
1444 /* --------------------------------------------------------------------------
1445      Parse a color or use a default value
1446    -------------------------------------------------------------------------- */
1448   NSColor * col;
1450   if (ns_get_color (name, &col))
1451     return dflt;
1452   else
1453     return col;
1458 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1459 /* --------------------------------------------------------------------------
1460      Convert a Lisp string object to a NS color
1461    -------------------------------------------------------------------------- */
1463   NSTRACE (ns_lisp_to_color);
1464   if (STRINGP (color))
1465     return ns_get_color (SDATA (color), col);
1466   else if (SYMBOLP (color))
1467     return ns_get_color (SDATA (SYMBOL_NAME (color)), col);
1468   return 1;
1472 Lisp_Object
1473 ns_color_to_lisp (NSColor *col)
1474 /* --------------------------------------------------------------------------
1475      Convert a color to a lisp string with the RGB equivalent
1476    -------------------------------------------------------------------------- */
1478   CGFloat red, green, blue, alpha, gray;
1479   char buf[1024];
1480   const char *str;
1481   NSTRACE (ns_color_to_lisp);
1483   BLOCK_INPUT;
1484   if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1486       if ((str =[[col colorNameComponent] UTF8String]))
1487         {
1488           UNBLOCK_INPUT;
1489           return build_string ((char *)str);
1490         }
1492     [[col colorUsingColorSpaceName: NSCalibratedRGBColorSpace]
1493         getRed: &red green: &green blue: &blue alpha: &alpha];
1494   if (red ==green && red ==blue)
1495     {
1496       [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1497             getWhite: &gray alpha: &alpha];
1498       snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1499                 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1500       UNBLOCK_INPUT;
1501       return build_string (buf);
1502     }
1504   snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1505             lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1507   UNBLOCK_INPUT;
1508   return build_string (buf);
1512 void
1513 ns_query_color(void *col, XColor *color_def, int setPixel)
1514 /* --------------------------------------------------------------------------
1515          Get ARGB values out of NSColor col and put them into color_def.
1516          If setPixel, set the pixel to a concatenated version.
1517          and set color_def pixel to the resulting index.
1518    -------------------------------------------------------------------------- */
1520   CGFloat r, g, b, a;
1522   [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1523   color_def->red   = r * 65535;
1524   color_def->green = g * 65535;
1525   color_def->blue  = b * 65535;
1527   if (setPixel == YES)
1528     color_def->pixel
1529       = ARGB_TO_ULONG((int)(a*255),
1530                       (int)(r*255), (int)(g*255), (int)(b*255));
1535 ns_defined_color (struct frame *f, char *name, XColor *color_def, int alloc,
1536                   char makeIndex)
1537 /* --------------------------------------------------------------------------
1538          Return 1 if named color found, and set color_def rgb accordingly.
1539          If makeIndex and alloc are nonzero put the color in the color_table,
1540          and set color_def pixel to the resulting index.
1541          If makeIndex is zero, set color_def pixel to ARGB.
1542          Return 0 if not found
1543    -------------------------------------------------------------------------- */
1545   NSColor *col;
1546   NSTRACE (ns_defined_color);
1548   BLOCK_INPUT;
1549   if (ns_get_color (name, &col) != 0) /* Color not found  */
1550     {
1551       UNBLOCK_INPUT;
1552       return 0;
1553     }
1554   if (makeIndex && alloc)
1555     color_def->pixel = ns_index_color (col, f);
1556   ns_query_color (col, color_def, !makeIndex);
1557   UNBLOCK_INPUT;
1558   return 1;
1562 unsigned long
1563 ns_get_rgb_color (struct frame *f, float r, float g, float b, float a)
1564 /* --------------------------------------------------------------------------
1565     return an autoreleased RGB color
1566    -------------------------------------------------------------------------- */
1568 /*static int c = 1; fprintf (stderr, "color request %d\n", c++); */
1569   if (r < 0.0) r = 0.0;
1570   else if (r > 1.0) r = 1.0;
1571   if (g < 0.0) g = 0.0;
1572   else if (g > 1.0) g = 1.0;
1573   if (b < 0.0) b = 0.0;
1574   else if (b > 1.0) b = 1.0;
1575   if (a < 0.0) a = 0.0;
1576   else if (a > 1.0) a = 1.0;
1577   return (unsigned long) ns_index_color(
1578     [NSColor colorWithCalibratedRed: r green: g blue: b alpha: a], f);
1582 void
1583 x_set_frame_alpha (struct frame *f)
1584 /* --------------------------------------------------------------------------
1585      change the entire-frame transparency
1586    -------------------------------------------------------------------------- */
1588   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1589   EmacsView *view = FRAME_NS_VIEW (f);
1590   double alpha = 1.0;
1591   double alpha_min = 1.0;
1593   if (dpyinfo->x_highlight_frame == f)
1594     alpha = f->alpha[0];
1595   else
1596     alpha = f->alpha[1];
1598   if (FLOATP (Vframe_alpha_lower_limit))
1599     alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1600   else if (INTEGERP (Vframe_alpha_lower_limit))
1601     alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1603   if (alpha < 0.0)
1604     return;
1605   else if (1.0 < alpha)
1606     alpha = 1.0;
1607   else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1608     alpha = alpha_min;
1610 #ifdef NS_IMPL_COCOA
1611   [[view window] setAlphaValue: alpha];
1612 #endif
1616 /* ==========================================================================
1618     Mouse handling
1620    ========================================================================== */
1623 void
1624 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1625 /* --------------------------------------------------------------------------
1626      Programmatically reposition mouse pointer in pixel coordinates
1627    -------------------------------------------------------------------------- */
1629   NSTRACE (x_set_mouse_pixel_position);
1630   ns_raise_frame (f);
1631 #if 0
1632   /* FIXME: this does not work, and what about GNUstep? */
1633 #ifdef NS_IMPL_COCOA
1634   [FRAME_NS_VIEW (f) lockFocus];
1635   PSsetmouse ((float)pix_x, (float)pix_y);
1636   [FRAME_NS_VIEW (f) unlockFocus];
1637 #endif
1638 #endif
1642 void
1643 x_set_mouse_position (struct frame *f, int h, int v)
1644 /* --------------------------------------------------------------------------
1645      Programmatically reposition mouse pointer in character coordinates
1646    -------------------------------------------------------------------------- */
1648   int pix_x, pix_y;
1650   pix_x = FRAME_COL_TO_PIXEL_X (f, h) + FRAME_COLUMN_WIDTH (f) / 2;
1651   pix_y = FRAME_LINE_TO_PIXEL_Y (f, v) + FRAME_LINE_HEIGHT (f) / 2;
1653   if (pix_x < 0) pix_x = 0;
1654   if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
1656   if (pix_y < 0) pix_y = 0;
1657   if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
1659   x_set_mouse_pixel_position (f, pix_x, pix_y);
1663 static int
1664 note_mouse_movement (struct frame *frame, float x, float y)
1665 /*   ------------------------------------------------------------------------
1666      Called by EmacsView on mouseMovement events.  Passes on
1667      to emacs mainstream code if we moved off of a rect of interest
1668      known as last_mouse_glyph.
1669      ------------------------------------------------------------------------ */
1671 //  NSTRACE (note_mouse_movement);
1673   XSETFRAME (last_mouse_motion_frame, frame);
1675   /* Note, this doesn't get called for enter/leave, since we don't have a
1676      position.  Those are taken care of in the corresponding NSView methods. */
1678   /* has movement gone beyond last rect we were tracking? */
1679   if (x < last_mouse_glyph.origin.x ||
1680       x >= (last_mouse_glyph.origin.x + last_mouse_glyph.size.width) ||
1681       y < last_mouse_glyph.origin.y ||
1682       y >= (last_mouse_glyph.origin.y + last_mouse_glyph.size.height))
1683     {
1684       ns_update_begin(frame);
1685       frame->mouse_moved = 1;
1686       note_mouse_highlight (frame, x, y);
1687       remember_mouse_glyph (frame, x, y, &last_mouse_glyph);
1688       ns_update_end(frame);
1689       return 1;
1690     }
1692   return 0;
1696 static void
1697 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1698                    enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1699                    unsigned long *time)
1700 /* --------------------------------------------------------------------------
1701     External (hook): inform emacs about mouse position and hit parts.
1702     If a scrollbar is being dragged, set bar_window, part, x, y, time.
1703     x & y should be position in the scrollbar (the whole bar, not the handle)
1704     and length of scrollbar respectively
1705    -------------------------------------------------------------------------- */
1707   id view;
1708   NSPoint position;
1709   int xchar, ychar;
1710   Lisp_Object frame, tail;
1711   struct frame *f;
1712   struct ns_display_info *dpyinfo;
1714   NSTRACE (ns_mouse_position);
1716   if (*fp == NULL)
1717     {
1718       fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1719       return;
1720     }
1722   dpyinfo = FRAME_NS_DISPLAY_INFO (*fp);
1724   BLOCK_INPUT;
1726   if (last_mouse_scroll_bar != nil && insist == 0)
1727     {
1728       /* TODO: we do not use this path at the moment because drag events will
1729            go directly to the EmacsScroller.  Leaving code in for now. */
1730       [last_mouse_scroll_bar getMouseMotionPart: (int *)part window: bar_window
1731                                               x: x y: y];
1732       if (time) *time = last_mouse_movement_time;
1733       last_mouse_scroll_bar = nil;
1734     }
1735   else
1736     {
1737       /* Clear the mouse-moved flag for every frame on this display.  */
1738       FOR_EACH_FRAME (tail, frame)
1739         if (FRAME_NS_P (XFRAME (frame))
1740             && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1741           XFRAME (frame)->mouse_moved = 0;
1743       last_mouse_scroll_bar = nil;
1744       if (last_mouse_frame && FRAME_LIVE_P (last_mouse_frame))
1745         f = last_mouse_frame;
1746       else
1747         f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame
1748                                     : SELECTED_FRAME ();
1750       if (f && f->output_data.ns)  /* TODO: 2nd check no longer needed? */
1751         {
1752           view = FRAME_NS_VIEW (*fp);
1754           position = [[view window] mouseLocationOutsideOfEventStream];
1755           position = [view convertPoint: position fromView: nil];
1756           remember_mouse_glyph (f, position.x, position.y, &last_mouse_glyph);
1757 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1759           if (bar_window) *bar_window = Qnil;
1760           if (part) *part = 0; /*scroll_bar_handle; */
1762           if (x) XSETINT (*x, lrint (position.x));
1763           if (y) XSETINT (*y, lrint (position.y));
1764           if (time) *time = last_mouse_movement_time;
1765           *fp = f;
1766         }
1767     }
1769   UNBLOCK_INPUT;
1773 static void
1774 ns_frame_up_to_date (struct frame *f)
1775 /* --------------------------------------------------------------------------
1776     External (hook): Fix up mouse highlighting right after a full update.
1777     Some highlighting was deferred if GC was happening during
1778     note_mouse_highlight (), while other highlighting was deferred for update.
1779    -------------------------------------------------------------------------- */
1781   NSTRACE (ns_frame_up_to_date);
1783   if (FRAME_NS_P (f))
1784     {
1785       struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1786       if ((dpyinfo->mouse_face_deferred_gc||f ==dpyinfo->mouse_face_mouse_frame)
1787       /*&& dpyinfo->mouse_face_mouse_frame*/)
1788         {
1789           BLOCK_INPUT;
1790          ns_update_begin(f);
1791           if (dpyinfo->mouse_face_mouse_frame)
1792             note_mouse_highlight (dpyinfo->mouse_face_mouse_frame,
1793                                   dpyinfo->mouse_face_mouse_x,
1794                                   dpyinfo->mouse_face_mouse_y);
1795           dpyinfo->mouse_face_deferred_gc = 0;
1796          ns_update_end(f);
1797           UNBLOCK_INPUT;
1798         }
1799     }
1803 void
1804 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1805 /* --------------------------------------------------------------------------
1806     External (RIF): set frame mouse pointer type.
1807    -------------------------------------------------------------------------- */
1809   NSTRACE (ns_define_frame_cursor);
1810   if (FRAME_POINTER_TYPE (f) != cursor)
1811     {
1812       EmacsView *view = FRAME_NS_VIEW (f);
1813       FRAME_POINTER_TYPE (f) = cursor;
1814       [[view window] invalidateCursorRectsForView: view];
1815     }
1820 /* ==========================================================================
1822     Keyboard handling
1824    ========================================================================== */
1827 static unsigned
1828 ns_convert_key (unsigned code)
1829 /* --------------------------------------------------------------------------
1830     Internal call used by NSView-keyDown.
1831    -------------------------------------------------------------------------- */
1833   const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym)
1834                                 / sizeof (convert_ns_to_X_keysym[0]));
1835   unsigned keysym;
1836   /* An array would be faster, but less easy to read. */
1837   for (keysym = 0; keysym < last_keysym; keysym += 2)
1838     if (code == convert_ns_to_X_keysym[keysym])
1839       return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
1840   return 0;
1841 /* if decide to use keyCode and Carbon table, use this line:
1842      return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
1846 char *
1847 x_get_keysym_name (int keysym)
1848 /* --------------------------------------------------------------------------
1849     Called by keyboard.c.  Not sure if the return val is important, except
1850     that it be unique.
1851    -------------------------------------------------------------------------- */
1853   static char value[16];
1854   NSTRACE (x_get_keysym_name);
1855   sprintf (value, "%d", keysym);
1856   return value;
1861 /* ==========================================================================
1863     Block drawing operations
1865    ========================================================================== */
1868 static void
1869 ns_redraw_scroll_bars (struct frame *f)
1871   int i;
1872   id view;
1873   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
1874   NSTRACE (ns_judge_scroll_bars);
1875   for (i =[subviews count]-1; i >= 0; i--)
1876     {
1877       view = [subviews objectAtIndex: i];
1878       if (![view isKindOfClass: [EmacsScroller class]]) continue;
1879       [view display];
1880     }
1884 void
1885 ns_clear_frame (struct frame *f)
1886 /* --------------------------------------------------------------------------
1887       External (hook): Erase the entire frame
1888    -------------------------------------------------------------------------- */
1890   NSView *view = FRAME_NS_VIEW (f);
1891   NSRect r;
1893   NSTRACE (ns_clear_frame);
1894   if (ns_in_resize)
1895     return;
1897  /* comes on initial frame because we have
1898     after-make-frame-functions = select-frame */
1899  if (!FRAME_DEFAULT_FACE (f))
1900    return;
1902   mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
1904   output_cursor.hpos = output_cursor.vpos = 0;
1905   output_cursor.x = -1;
1907   r = [view bounds];
1909   BLOCK_INPUT;
1910   ns_focus (f, &r, 1);
1911   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
1912   NSRectFill (r);
1913   ns_unfocus (f);
1915 #ifdef NS_IMPL_COCOA
1916   [[view window] display];  /* redraw resize handle */
1917 #endif
1919   /* as of 2006/11 or so this is now needed */
1920   ns_redraw_scroll_bars (f);
1921   UNBLOCK_INPUT;
1925 void
1926 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
1927 /* --------------------------------------------------------------------------
1928     External (RIF):  Clear section of frame
1929    -------------------------------------------------------------------------- */
1931   NSRect r = NSMakeRect (x, y, width, height);
1932   NSView *view = FRAME_NS_VIEW (f);
1933   struct face *face = FRAME_DEFAULT_FACE (f);
1935   if (!view || !face)
1936     return;
1938   NSTRACE (ns_clear_frame_area);
1940   r = NSIntersectionRect (r, [view frame]);
1941   ns_focus (f, &r, 1);
1942   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
1944 #ifdef NS_IMPL_COCOA
1945   {
1946     /* clip out the resize handle */
1947     NSWindow *window = [FRAME_NS_VIEW (f) window];
1948     NSRect ir
1949       = [view convertRect: ns_resize_handle_rect (window) fromView: nil];
1951     ir = NSIntersectionRect (r, ir);
1952     if (NSIsEmptyRect (ir))
1953       {
1954 #endif
1956   NSRectFill (r);
1958 #ifdef NS_IMPL_COCOA
1959       }
1960     else
1961       {
1962         NSRect r1 = r, r2 = r; /* upper and lower non-intersecting */
1963         r1.size.height -= ir.size.height;
1964         r2.origin.y += r1.size.height;
1965         r2.size.width -= ir.size.width;
1966         r2.size.height = ir.size.height;
1967         NSRectFill (r1);
1968         NSRectFill (r2);
1969       }
1970   }
1971 #endif
1973   ns_unfocus (f);
1974   return;
1978 static void
1979 ns_scroll_run (struct window *w, struct run *run)
1980 /* --------------------------------------------------------------------------
1981     External (RIF):  Insert or delete n lines at line vpos
1982    -------------------------------------------------------------------------- */
1984   struct frame *f = XFRAME (w->frame);
1985   int x, y, width, height, from_y, to_y, bottom_y;
1987   NSTRACE (ns_scroll_run);
1989   /* begin copy from other terms */
1990   /* Get frame-relative bounding box of the text display area of W,
1991      without mode lines.  Include in this box the left and right
1992      fringe of W.  */
1993   window_box (w, -1, &x, &y, &width, &height);
1995   from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
1996   to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
1997   bottom_y = y + height;
1999   if (to_y < from_y)
2000     {
2001       /* Scrolling up.  Make sure we don't copy part of the mode
2002          line at the bottom.  */
2003       if (from_y + run->height > bottom_y)
2004         height = bottom_y - from_y;
2005       else
2006         height = run->height;
2007     }
2008   else
2009     {
2010       /* Scolling down.  Make sure we don't copy over the mode line.
2011          at the bottom.  */
2012       if (to_y + run->height > bottom_y)
2013         height = bottom_y - to_y;
2014       else
2015         height = run->height;
2016     }
2017   /* end copy from other terms */
2019   if (height == 0)
2020       return;
2022   BLOCK_INPUT;
2024   updated_window = w;
2025   x_clear_cursor (w);
2027   {
2028     NSRect srcRect = NSMakeRect (x, from_y, width, height);
2029     NSRect dstRect = NSMakeRect (x, to_y, width, height);
2030     NSPoint dstOrigin = NSMakePoint (x, to_y);
2032     ns_focus (f, &dstRect, 1);
2033     NSCopyBits (0, srcRect , dstOrigin);
2034     ns_unfocus (f);
2035   }
2037   UNBLOCK_INPUT;
2041 static void
2042 ns_after_update_window_line (struct glyph_row *desired_row)
2043 /* --------------------------------------------------------------------------
2044     External (RIF): preparatory to fringe update after text was updated
2045    -------------------------------------------------------------------------- */
2047   struct window *w = updated_window;
2048   struct frame *f;
2049   int width, height;
2051   NSTRACE (ns_after_update_window_line);
2053   /* begin copy from other terms */
2054   xassert (w);
2056   if (!desired_row->mode_line_p && !w->pseudo_window_p)
2057     desired_row->redraw_fringe_bitmaps_p = 1;
2059   /* When a window has disappeared, make sure that no rest of
2060      full-width rows stays visible in the internal border.
2061      Under NS this is drawn inside the fringes. */
2062   if (windows_or_buffers_changed
2063       && (f = XFRAME (w->frame),
2064           width = FRAME_INTERNAL_BORDER_WIDTH (f),
2065           width != 0)
2066       && (height = desired_row->visible_height,
2067           height > 0))
2068     {
2069       int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2071       /* Internal border is drawn below the tool bar.  */
2072       if (WINDOWP (f->tool_bar_window)
2073           && w == XWINDOW (f->tool_bar_window))
2074         y -= width;
2075       /* end copy from other terms */
2077       BLOCK_INPUT;
2078       if (!desired_row->full_width_p)
2079         {
2080           int x1 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2081             + WINDOW_LEFT_FRINGE_WIDTH (w);
2082           int x2 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2083             + FRAME_PIXEL_WIDTH (f) - NS_SCROLL_BAR_WIDTH (f)
2084             - WINDOW_RIGHT_FRINGE_WIDTH (w)
2085             - FRAME_INTERNAL_BORDER_WIDTH (f);
2086           ns_clear_frame_area (f, x1, y, width, height);
2087           ns_clear_frame_area (f, x2, y, width, height);
2088         }
2089       UNBLOCK_INPUT;
2090     }
2094 static void
2095 ns_shift_glyphs_for_insert (struct frame *f,
2096                            int x, int y, int width, int height,
2097                            int shift_by)
2098 /* --------------------------------------------------------------------------
2099     External (RIF): copy an area horizontally, don't worry about clearing src
2100    -------------------------------------------------------------------------- */
2102   NSRect srcRect = NSMakeRect (x, y, width, height);
2103   NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2104   NSPoint dstOrigin = dstRect.origin;
2106   NSTRACE (ns_shift_glyphs_for_insert);
2108   ns_focus (f, &dstRect, 1);
2109   NSCopyBits (0, srcRect, dstOrigin);
2110   ns_unfocus (f);
2115 /* ==========================================================================
2117     Character encoding and metrics
2119    ========================================================================== */
2122 static inline void
2123 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2124 /* --------------------------------------------------------------------------
2125      External (RIF); compute left/right overhang of whole string and set in s
2126    -------------------------------------------------------------------------- */
2128   struct face *face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2129   struct font *font = s->font; /*face->font; */
2131   if (s->char2b)
2132     {
2133       struct font_metrics metrics;
2134       unsigned int codes[2];
2135       codes[0] = *(s->char2b);
2136       codes[1] = *(s->char2b + s->nchars - 1);
2138       font->driver->text_extents (font, codes, 2, &metrics);
2139       s->left_overhang = -metrics.lbearing;
2140       s->right_overhang
2141         = metrics.rbearing > metrics.width
2142         ? metrics.rbearing - metrics.width : 0;
2143     }
2144   else
2145     {
2146       s->left_overhang = 0;
2147       s->right_overhang = ((struct nsfont_info *)font)->ital ?
2148         FONT_HEIGHT (font) * 0.2 : 0;
2149     }
2154 /* ==========================================================================
2156     Fringe and cursor drawing
2158    ========================================================================== */
2161 extern int max_used_fringe_bitmap;
2162 static void
2163 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2164                       struct draw_fringe_bitmap_params *p)
2165 /* --------------------------------------------------------------------------
2166     External (RIF); fringe-related
2167    -------------------------------------------------------------------------- */
2169   struct frame *f = XFRAME (WINDOW_FRAME (w));
2170   struct face *face = p->face;
2171   int rowY;
2172   static EmacsImage **bimgs = NULL;
2173   static int nBimgs = 0;
2174   /* NS-specific: move internal border inside fringe */
2175   int x = p->bx < 0 ? p->x : p->bx;
2176   int wd = p->bx < 0 ? p->wd : p->nx;
2177   BOOL fringeOnVeryLeft
2178     = x - WINDOW_LEFT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w)
2179       - FRAME_INTERNAL_BORDER_WIDTH (f) < 10;
2180   BOOL fringeOnVeryRight
2181     = FRAME_PIXEL_WIDTH (f) - x - wd - FRAME_INTERNAL_BORDER_WIDTH (f)
2182       - WINDOW_RIGHT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w) < 10;
2183   int xAdjust = FRAME_INTERNAL_BORDER_WIDTH (f) *
2184     (fringeOnVeryLeft ? -1 : (fringeOnVeryRight ? 1 : 0));
2186   /* grow bimgs if needed */
2187   if (nBimgs < max_used_fringe_bitmap)
2188     {
2189       EmacsImage **newBimgs
2190         = xmalloc (max_used_fringe_bitmap * sizeof (EmacsImage *));
2191       bzero (newBimgs, max_used_fringe_bitmap * sizeof (EmacsImage *));
2193       if (nBimgs)
2194         {
2195           bcopy (bimgs, newBimgs, nBimgs * sizeof (EmacsImage *));
2196           xfree (bimgs);
2197         }
2199       bimgs = newBimgs;
2200       nBimgs = max_used_fringe_bitmap;
2201     }
2203   /* Must clip because of partially visible lines.  */
2204   rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
2205   ns_clip_to_row (w, row, -1, YES);
2207   if (p->bx >= 0 && !p->overlay_p)
2208     {
2209       int yAdjust = rowY - FRAME_INTERNAL_BORDER_WIDTH (f) < 5 ?
2210         -FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2211       int yIncr = FRAME_PIXEL_HEIGHT (f) - (p->by+yAdjust + p->ny) < 5 ?
2212         FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2213       if (yAdjust)
2214         yIncr += FRAME_INTERNAL_BORDER_WIDTH (f);
2215       NSRect r = NSMakeRect (p->bx+xAdjust, p->by+yAdjust, p->nx, p->ny+yIncr);
2216       NSRectClip (r);
2217       [ns_lookup_indexed_color(face->background, f) set];
2218       NSRectFill (r);
2219     }
2221   if (p->which)
2222     {
2223       NSRect r = NSMakeRect (p->x+xAdjust, p->y, p->wd, p->h);
2224       NSPoint pt = r.origin;
2225       EmacsImage *img = bimgs[p->which - 1];
2227       if (!img)
2228         {
2229           unsigned short *bits = p->bits + p->dh;
2230           int len = 8 * p->h/8;
2231           int i;
2232           unsigned char *cbits = xmalloc (len);
2234           for (i =0; i<len; i++)
2235             cbits[i] = ~(bits[i] & 0xff);
2236           img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2237                                            flip: NO];
2238           bimgs[p->which - 1] = img;
2239           xfree (cbits);
2240         }
2242       NSRectClip (r);
2243       /* Since we composite the bitmap instead of just blitting it, we need
2244          to erase the whole background. */
2245       [ns_lookup_indexed_color(face->background, f) set];
2246       NSRectFill (r);
2247       pt.y += p->h;
2248       [img setXBMColor: ns_lookup_indexed_color(face->foreground, f)];
2249       [img compositeToPoint: pt operation: NSCompositeSourceOver];
2250     }
2251   ns_unfocus (f);
2255 void
2256 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2257                        int x, int y, int cursor_type, int cursor_width,
2258                        int on_p, int active_p)
2259 /* --------------------------------------------------------------------------
2260      External call (RIF): draw cursor
2261      (modeled after x_draw_window_cursor
2262      FIXME: cursor_width is effectively bogus -- it sometimes gets set
2263      in xdisp.c set_frame_cursor_types, sometimes left uninitialized;
2264      DON'T USE IT (no other terms do)
2265    -------------------------------------------------------------------------- */
2267   NSRect r, s;
2268   int fx, fy, h;
2269   struct frame *f = WINDOW_XFRAME (w);
2270   struct glyph *phys_cursor_glyph;
2271   int overspill;
2273   NSTRACE (dumpcursor);
2274 //fprintf(stderr, "drawcursor (%d,%d) activep = %d\tonp = %d\tc_type = %d\twidth = %d\n",x,y, active_p,on_p,cursor_type,cursor_width);
2276   if (!on_p)
2277         return;
2279   w->phys_cursor_type = cursor_type;
2280   w->phys_cursor_on_p = on_p;
2282   if (cursor_type == NO_CURSOR)
2283     {
2284       w->phys_cursor_width = 0;
2285       return;
2286     }
2288   if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2289     {
2290       if (glyph_row->exact_window_width_line_p
2291           && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2292         {
2293           glyph_row->cursor_in_fringe_p = 1;
2294           draw_fringe_bitmap (w, glyph_row, 0);
2295         }
2296       return;
2297     }
2299   get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2301   r.origin.x = fx, r.origin.y = fy;
2302   r.size.height = h;
2303   r.size.width = w->phys_cursor_width;
2305   /* FIXME: if we overwrite the internal border area, it does not get erased;
2306      fix by truncating cursor, but better would be to erase properly */
2307   overspill = r.origin.x + r.size.width -
2308     WINDOW_TEXT_TO_FRAME_PIXEL_X (w, WINDOW_BOX_RIGHT_EDGE_X (w) 
2309       - WINDOW_TOTAL_FRINGE_WIDTH (w) - FRAME_INTERNAL_BORDER_WIDTH (f));
2310   if (overspill > 0)
2311     r.size.width -= overspill;
2313   /* TODO: only needed in rare cases with last-resort font in HELLO..
2314      should we do this more efficiently? */
2315   ns_clip_to_row (w, glyph_row, -1, NO); /* do ns_focus(f, &r, 1); if remove */
2316   [FRAME_CURSOR_COLOR (f) set];
2318 #ifdef NS_IMPL_COCOA
2319   /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2320            atomic.  Cleaner ways of doing this should be investigated.
2321            One way would be to set a global variable DRAWING_CURSOR
2322            when making the call to draw_phys..(), don't focus in that
2323            case, then move the ns_unfocus() here after that call. */
2324   NSDisableScreenUpdates ();
2325 #endif
2327   switch (cursor_type)
2328     {
2329     case NO_CURSOR:
2330       break;
2331     case FILLED_BOX_CURSOR:
2332       NSRectFill (r);
2333       break;
2334     case HOLLOW_BOX_CURSOR:
2335       NSRectFill (r);
2336       [FRAME_BACKGROUND_COLOR (f) set];
2337       NSRectFill (NSInsetRect (r, 1, 1));
2338       [FRAME_CURSOR_COLOR (f) set];
2339       break;
2340     case HBAR_CURSOR:
2341       s = r;
2342       s.origin.y += lrint (0.75 * s.size.height);
2343       s.size.height = lrint (s.size.height * 0.25);
2344       NSRectFill (s);
2345       break;
2346     case BAR_CURSOR:
2347       s = r;
2348       s.size.width = min (cursor_width, 2); //FIXME(see above)
2349       NSRectFill (s);
2350       break;
2351     }
2352   ns_unfocus (f);
2354   /* draw the character under the cursor */
2355   if (cursor_type != NO_CURSOR)
2356     draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2358 #ifdef NS_IMPL_COCOA
2359   NSEnableScreenUpdates ();
2360 #endif
2365 static void
2366 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2367 /* --------------------------------------------------------------------------
2368      External (RIF): Draw a vertical line.
2369    -------------------------------------------------------------------------- */
2371   struct frame *f = XFRAME (WINDOW_FRAME (w));
2372   struct face *face;
2373   NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2375   NSTRACE (ns_draw_vertical_window_border);
2377   face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2378   if (face)
2379       [ns_lookup_indexed_color(face->foreground, f) set];
2381   ns_focus (f, &r, 1);
2382   NSRectFill(r);
2383   ns_unfocus (f);
2387 void
2388 show_hourglass (struct atimer *timer)
2390   if (hourglass_shown_p)
2391     return;
2393   BLOCK_INPUT;
2395   /* TODO: add NSProgressIndicator to selected frame (see macfns.c) */
2397   hourglass_shown_p = 1;
2398   UNBLOCK_INPUT;
2402 void
2403 hide_hourglass ()
2405   if (!hourglass_shown_p)
2406     return;
2408   BLOCK_INPUT;
2410   /* TODO: remove NSProgressIndicator from all frames */
2412   hourglass_shown_p = 0;
2413   UNBLOCK_INPUT;
2418 /* ==========================================================================
2420     Glyph drawing operations
2422    ========================================================================== */
2425 static inline NSRect
2426 ns_fix_rect_ibw (NSRect r, int fibw, int frame_pixel_width)
2427 /* --------------------------------------------------------------------------
2428     Under NS we draw internal borders inside fringes, and want full-width
2429     rendering to go all the way to edge.  This function makes that correction.
2430    -------------------------------------------------------------------------- */
2432   if (r.origin.y <= fibw+1)
2433     {
2434       r.size.height += r.origin.y;
2435       r.origin.y = 0;
2436     }
2437   if (r.origin.x <= fibw+1)
2438     {
2439       r.size.width += r.origin.x;
2440       r.origin.x = 0;
2441     }
2442   if (frame_pixel_width - (r.origin.x+r.size.width) <= fibw+1)
2443     r.size.width += fibw;
2445   return r;
2449 static int
2450 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2451 /* --------------------------------------------------------------------------
2452     Wrapper utility to account for internal border width on full-width lines,
2453     and allow top full-width rows to hit the frame top.  nr should be pointer
2454     to two successive NSRects.  Number of rects actually used is returned.
2455    -------------------------------------------------------------------------- */
2457   int n = get_glyph_string_clip_rects (s, nr, 2);
2458   if (s->row->full_width_p)
2459     {
2460       *nr = ns_fix_rect_ibw (*nr, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2461                             FRAME_PIXEL_WIDTH (s->f));
2462       if (n == 2)
2463         *nr = ns_fix_rect_ibw (*(nr+1), FRAME_INTERNAL_BORDER_WIDTH (s->f),
2464                               FRAME_PIXEL_WIDTH (s->f));
2465     }
2466   return n;
2470 static void
2471 ns_draw_box (NSRect r, float thickness, NSColor *col, char left_p, char right_p)
2472 /* --------------------------------------------------------------------------
2473     Draw an unfilled rect inside r, optionally leaving left and/or right open.
2474     Note we can't just use an NSDrawRect command, because of the possibility
2475     of some sides not being drawn, and because the rect will be filled.
2476    -------------------------------------------------------------------------- */
2478   NSRect s = r;
2479   [col set];
2481   /* top, bottom */
2482   s.size.height = thickness;
2483   NSRectFill (s);
2484   s.origin.y += r.size.height - thickness;
2485   NSRectFill (s);
2487   s.size.height = r.size.height;
2488   s.origin.y = r.origin.y;
2490   /* left, right (optional) */
2491   s.size.width = thickness;
2492   if (left_p)
2493     NSRectFill (s);
2494   if (right_p)
2495     {
2496       s.origin.x += r.size.width - thickness;
2497       NSRectFill (s);
2498     }
2502 static void
2503 ns_draw_relief (NSRect r, int thickness, char raised_p,
2504                char top_p, char bottom_p, char left_p, char right_p,
2505                struct glyph_string *s)
2506 /* --------------------------------------------------------------------------
2507     Draw a relief rect inside r, optionally leaving some sides open.
2508     Note we can't just use an NSDrawBezel command, because of the possibility
2509     of some sides not being drawn, and because the rect will be filled.
2510    -------------------------------------------------------------------------- */
2512   static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2513   NSColor *newBaseCol = nil;
2514   NSRect sr = r;
2516   NSTRACE (ns_draw_relief);
2518   /* set up colors */
2520   if (s->face->use_box_color_for_shadows_p)
2521     {
2522       newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2523     }
2524 /*     else if (s->first_glyph->type == IMAGE_GLYPH
2525            && s->img->pixmap
2526            && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2527        {
2528          newBaseCol = IMAGE_BACKGROUND  (s->img, s->f, 0);
2529        } */
2530   else
2531     {
2532       newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2533     }
2535   if (newBaseCol == nil)
2536     newBaseCol = [NSColor grayColor];
2538   if (newBaseCol != baseCol)  /* TODO: better check */
2539     {
2540       [baseCol release];
2541       baseCol = [newBaseCol retain];
2542       [lightCol release];
2543       lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2544       [darkCol release];
2545       darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2546     }
2548   [(raised_p ? lightCol : darkCol) set];
2550   /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2552   /* top */
2553   sr.size.height = thickness;
2554   if (top_p) NSRectFill (sr);
2556   /* left */
2557   sr.size.height = r.size.height;
2558   sr.size.width = thickness;
2559   if (left_p) NSRectFill (sr);
2561   [(raised_p ? darkCol : lightCol) set];
2563   /* bottom */
2564   sr.size.width = r.size.width;
2565   sr.size.height = thickness;
2566   sr.origin.y += r.size.height - thickness;
2567   if (bottom_p) NSRectFill (sr);
2569   /* right */
2570   sr.size.height = r.size.height;
2571   sr.origin.y = r.origin.y;
2572   sr.size.width = thickness;
2573   sr.origin.x += r.size.width - thickness;
2574   if (right_p) NSRectFill (sr);
2578 static void
2579 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2580 /* --------------------------------------------------------------------------
2581       Function modeled after x_draw_glyph_string_box ().
2582       Sets up parameters for drawing.
2583    -------------------------------------------------------------------------- */
2585   int right_x, last_x;
2586   char left_p, right_p;
2587   struct glyph *last_glyph;
2588   NSRect r;
2589   int thickness;
2590   struct face *face;
2592   if (s->hl == DRAW_MOUSE_FACE)
2593     {
2594       face = FACE_FROM_ID
2595         (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2596       if (!face)
2597         face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2598     }
2599   else
2600     face = s->face;
2602   thickness = face->box_line_width;
2604   NSTRACE (ns_dumpglyphs_box_or_relief);
2606   last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2607             ? WINDOW_RIGHT_EDGE_X (s->w)
2608             : window_box_right (s->w, s->area));
2609   last_glyph = (s->cmp || s->img
2610                 ? s->first_glyph : s->first_glyph + s->nchars-1);
2612   right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2613               ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2615   left_p = (s->first_glyph->left_box_line_p
2616             || (s->hl == DRAW_MOUSE_FACE
2617                 && (s->prev == NULL || s->prev->hl != s->hl)));
2618   right_p = (last_glyph->right_box_line_p
2619              || (s->hl == DRAW_MOUSE_FACE
2620                  && (s->next == NULL || s->next->hl != s->hl)));
2622   r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2624   /* expand full-width row over internal borders */
2625   if (s->row->full_width_p)
2626     r = ns_fix_rect_ibw (r, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2627                         FRAME_PIXEL_WIDTH (s->f));
2629   /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
2630   if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
2631     {
2632       ns_draw_box (r, abs (thickness),
2633                    ns_lookup_indexed_color (face->box_color, s->f),
2634                   left_p, right_p);
2635     }
2636   else
2637     {
2638       ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2639                      1, 1, left_p, right_p, s);
2640     }
2644 static void
2645 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2646 /* --------------------------------------------------------------------------
2647       Modeled after x_draw_glyph_string_background, which draws BG in
2648       certain cases.  Others are left to the text rendering routine.
2649    -------------------------------------------------------------------------- */
2651   NSTRACE (ns_maybe_dumpglyphs_background);
2653   if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2654     {
2655       int box_line_width = max (s->face->box_line_width, 0);
2656       if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2657           || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2658         {
2659           struct face *face;
2660           if (s->hl == DRAW_MOUSE_FACE)
2661             {
2662               face = FACE_FROM_ID
2663                 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2664               if (!face)
2665                 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2666             }
2667           else
2668             face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2669           if (!face->stipple)
2670             [(NS_FACE_BACKGROUND (face) != 0
2671               ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2672               : FRAME_BACKGROUND_COLOR (s->f)) set];
2673           else
2674             {
2675               struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (s->f);
2676               [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2677             }
2679           if (s->hl != DRAW_CURSOR)
2680             {
2681               NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2682                                     s->background_width,
2683                                     s->height-2*box_line_width);
2685               /* expand full-width row over internal borders */
2686               if (s->row->full_width_p)
2687                 {
2688                   int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2689                   if (r.origin.y <= fibw+1 + box_line_width)
2690                     {
2691                       r.size.height += r.origin.y;
2692                       r.origin.y = 0;
2693                     }
2694                   if (r.origin.x <= fibw+1)
2695                     {
2696                       r.size.width += 2*r.origin.x;
2697                       r.origin.x = 0;
2698                     }
2699                   if (FRAME_PIXEL_WIDTH (s->f) - (r.origin.x + r.size.width)
2700                       <= fibw+1)
2701                     r.size.width += fibw;
2702                 }
2704               NSRectFill (r);
2705             }
2707           s->background_filled_p = 1;
2708         }
2709     }
2713 static void
2714 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2715 /* --------------------------------------------------------------------------
2716       Renders an image and associated borders.
2717    -------------------------------------------------------------------------- */
2719   EmacsImage *img = s->img->pixmap;
2720   int box_line_vwidth = max (s->face->box_line_width, 0);
2721   int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2722   int bg_x, bg_y, bg_height;
2723   int th;
2724   char raised_p;
2725   NSRect br;
2726   struct face *face;
2728   NSTRACE (ns_dumpglyphs_image);
2730   if (s->face->box != FACE_NO_BOX
2731       && s->first_glyph->left_box_line_p && s->slice.x == 0)
2732     x += abs (s->face->box_line_width);
2734   bg_x = x;
2735   bg_y =  s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2736   bg_height = s->height;
2737   /* other terms have this, but was causing problems w/tabbar mode */
2738   /* - 2 * box_line_vwidth; */
2740   if (s->slice.x == 0) x += s->img->hmargin;
2741   if (s->slice.y == 0) y += s->img->vmargin;
2743   /* Draw BG: if we need larger area than image itself cleared, do that,
2744      otherwise, since we composite the image under NS (instead of mucking
2745      with its background color), we must clear just the image area. */
2746   if (s->hl == DRAW_MOUSE_FACE)
2747     {
2748       face = FACE_FROM_ID
2749        (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2750       if (!face)
2751        face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2752     }
2753   else
2754     face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2756   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
2758   if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
2759       || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
2760     {
2761       br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
2762       s->background_filled_p = 1;
2763     }
2764   else
2765     {
2766       br = NSMakeRect (x, y, s->slice.width, s->slice.height);
2767     }
2769   /* expand full-width row over internal borders */
2770   if (s->row->full_width_p)
2771     {
2772       int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2773       if (br.origin.y <= fibw+1 + box_line_vwidth)
2774         {
2775           br.size.height += br.origin.y;
2776           br.origin.y = 0;
2777         }
2778       if (br.origin.x <= fibw+1 + box_line_vwidth)
2779         {
2780           br.size.width += br.origin.x;
2781           br.origin.x = 0;
2782         }
2783       if (FRAME_PIXEL_WIDTH (s->f) - (br.origin.x + br.size.width) <= fibw+1)
2784         br.size.width += fibw;
2785     }
2787   NSRectFill (br);
2789   /* Draw the image.. do we need to draw placeholder if img ==nil? */
2790   if (img != nil)
2791     [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
2792                 operation: NSCompositeSourceOver];
2794   /* Draw relief, if requested */
2795   if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
2796     {
2797       if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
2798         {
2799           th = tool_bar_button_relief >= 0 ?
2800             tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2801           raised_p = (s->hl == DRAW_IMAGE_RAISED);
2802         }
2803       else
2804         {
2805           th = abs (s->img->relief);
2806           raised_p = (s->img->relief > 0);
2807         }
2809       r.origin.x = x - th;
2810       r.origin.y = y - th;
2811       r.size.width = s->slice.width + 2*th-1;
2812       r.size.height = s->slice.height + 2*th-1;
2813       ns_draw_relief (r, th, raised_p,
2814                       s->slice.y == 0,
2815                       s->slice.y + s->slice.height == s->img->height,
2816                       s->slice.x == 0,
2817                       s->slice.x + s->slice.width == s->img->width, s);
2818     }
2822 static void
2823 ns_dumpglyphs_stretch (struct glyph_string *s)
2825   NSRect r[2];
2826   int n, i;
2827   struct face *face;
2829   if (!s->background_filled_p)
2830     {
2831       n = ns_get_glyph_string_clip_rect (s, r);
2832       *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
2834       for (i=0; i<n; i++)
2835         {
2836           if (!s->row->full_width_p)
2837             {
2838               /* truncate to avoid overwriting fringe and/or scrollbar */
2839               int overrun = max (0, (s->x + s->background_width)
2840                                   - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
2841                                     - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
2842               r[i].size.width -= overrun;
2844               /* XXX: Try to work between problem where a stretch glyph on
2845                  a partially-visible bottom row will clear part of the
2846                  modeline, and another where list-buffers headers and similar
2847                  rows erroneously have visible_height set to 0.  Not sure
2848                  where this is coming from as other terms seem not to show. */
2849               r[i].size.height = min (s->height, s->row->visible_height);
2850             }
2852           /* expand full-width rows over internal borders */
2853           else
2854             {
2855               r[i] = ns_fix_rect_ibw (r[i], FRAME_INTERNAL_BORDER_WIDTH (s->f),
2856                                       FRAME_PIXEL_WIDTH (s->f));
2857             }
2859           /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
2860              overwriting cursor (usually when cursor on a tab) */
2861           if (s->hl == DRAW_CURSOR)
2862             {
2863               r[i].origin.x += s->width;
2864               r[i].size.width -= s->width;
2865             }
2866         }
2868       ns_focus (s->f, r, n);
2870       if (s->hl == DRAW_MOUSE_FACE)
2871        {
2872          face = FACE_FROM_ID
2873            (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2874          if (!face)
2875            face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2876        }
2877       else
2878        face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2880       [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
2882       NSRectFill (r[0]);
2883       NSRectFill (r[1]);
2884       ns_unfocus (s->f);
2885       s->background_filled_p = 1;
2886     }
2890 static void
2891 ns_draw_glyph_string (struct glyph_string *s)
2892 /* --------------------------------------------------------------------------
2893       External (RIF): Main draw-text call.
2894    -------------------------------------------------------------------------- */
2896   /* TODO (optimize): focus for box and contents draw */
2897   NSRect r[2];
2898   int n;
2899   char box_drawn_p = 0;
2901   NSTRACE (ns_draw_glyph_string);
2903   if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
2904     {
2905       int width;
2906       struct glyph_string *next;
2908       for (width = 0, next = s->next;
2909            next && width < s->right_overhang;
2910            width += next->width, next = next->next)
2911         if (next->first_glyph->type != IMAGE_GLYPH)
2912           {
2913             if (next->first_glyph->type != STRETCH_GLYPH)
2914               {
2915                 n = ns_get_glyph_string_clip_rect (s->next, r);
2916                 ns_focus (s->f, r, n);
2917                 ns_maybe_dumpglyphs_background (s->next, 1);
2918                 ns_unfocus (s->f);
2919               }
2920             else
2921               {
2922                 ns_dumpglyphs_stretch (s->next);
2923               }
2924             next->num_clips = 0;
2925           }
2926     }
2928   if (!s->for_overlaps && s->face->box != FACE_NO_BOX
2929         && (s->first_glyph->type == CHAR_GLYPH
2930             || s->first_glyph->type == COMPOSITE_GLYPH))
2931     {
2932       n = ns_get_glyph_string_clip_rect (s, r);
2933       ns_focus (s->f, r, n);
2934       ns_maybe_dumpglyphs_background (s, 1);
2935       ns_dumpglyphs_box_or_relief (s);
2936       ns_unfocus (s->f);
2937       box_drawn_p = 1;
2938     }
2940   switch (s->first_glyph->type)
2941     {
2943     case IMAGE_GLYPH:
2944       n = ns_get_glyph_string_clip_rect (s, r);
2945       ns_focus (s->f, r, n);
2946       ns_dumpglyphs_image (s, r[0]);
2947       ns_unfocus (s->f);
2948       break;
2950     case STRETCH_GLYPH:
2951       ns_dumpglyphs_stretch (s);
2952       break;
2954     case CHAR_GLYPH:
2955     case COMPOSITE_GLYPH:
2956       n = ns_get_glyph_string_clip_rect (s, r);
2957       ns_focus (s->f, r, n);
2959       if (s->for_overlaps || (s->cmp_from > 0
2960                               && ! s->first_glyph->u.cmp.automatic))
2961         s->background_filled_p = 1;
2962       else
2963         ns_maybe_dumpglyphs_background
2964           (s, s->first_glyph->type == COMPOSITE_GLYPH);
2966       ns_tmp_flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
2967                     (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
2968                      (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
2969                       NS_DUMPGLYPH_NORMAL));
2970       ns_tmp_font = (struct nsfont_info *)s->face->font;
2971       if (ns_tmp_font == NULL)
2972           ns_tmp_font = (struct nsfont_info *)FRAME_FONT (s->f);
2974       ns_tmp_font->font.driver->draw
2975         (s, 0, s->nchars, s->x, s->y,
2976          (ns_tmp_flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
2977          || ns_tmp_flags == NS_DUMPGLYPH_MOUSEFACE);
2979       ns_unfocus (s->f);
2980       break;
2982     default:
2983       abort ();
2984     }
2986   /* Draw box if not done already. */
2987   if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
2988     {
2989       n = ns_get_glyph_string_clip_rect (s, r);
2990       ns_focus (s->f, r, n);
2991       ns_dumpglyphs_box_or_relief (s);
2992       ns_unfocus (s->f);
2993     }
2995   s->num_clips = 0;
3000 /* ==========================================================================
3002     Event loop
3004    ========================================================================== */
3007 static void
3008 ns_send_appdefined (int value)
3009 /* --------------------------------------------------------------------------
3010     Internal: post an appdefined event which EmacsApp-sendEvent will
3011               recognize and take as a command to halt the event loop.
3012    -------------------------------------------------------------------------- */
3014   /*NSTRACE (ns_send_appdefined); */
3016   /* Only post this event if we haven't already posted one.  This will end
3017        the [NXApp run] main loop after having processed all events queued at
3018        this moment.  */
3019   if (send_appdefined)
3020     {
3021       NSEvent *nxev;
3023       /* We only need one NX_APPDEFINED event to stop NXApp from running.  */
3024       send_appdefined = NO;
3026       /* Don't need wakeup timer any more */
3027       if (timed_entry)
3028         {
3029           [timed_entry invalidate];
3030           [timed_entry release];
3031           timed_entry = nil;
3032         }
3034       /* Ditto for file descriptor poller */
3035       if (fd_entry)
3036         {
3037           [fd_entry invalidate];
3038           [fd_entry release];
3039           fd_entry = nil;
3040         }
3042       nxev = [NSEvent otherEventWithType: NSApplicationDefined
3043                                 location: NSMakePoint (0, 0)
3044                            modifierFlags: 0
3045                                timestamp: 0
3046                             windowNumber: [[NSApp mainWindow] windowNumber]
3047                                  context: [NSApp context]
3048                                  subtype: 0
3049                                    data1: value
3050                                    data2: 0];
3052       /* Post an application defined event on the event queue.  When this is
3053          received the [NXApp run] will return, thus having processed all
3054          events which are currently queued.  */
3055       [NSApp postEvent: nxev atStart: NO];
3056     }
3060 static int
3061 ns_read_socket (struct terminal *terminal, int expected,
3062                 struct input_event *hold_quit)
3063 /* --------------------------------------------------------------------------
3064      External (hook): Post an event to ourself and keep reading events until
3065      we read it back again.  In effect process all events which were waiting.
3066      From 21+ we have to manage the event buffer ourselves.
3067    -------------------------------------------------------------------------- */
3069   struct input_event ev;
3070   int nevents;
3072 /* NSTRACE (ns_read_socket); */
3074   if (interrupt_input_blocked)
3075     {
3076       interrupt_input_pending = 1;
3077 #ifdef SYNC_INPUT
3078       pending_signals = 1;
3079 #endif
3080       return -1;
3081     }
3083   interrupt_input_pending = 0;
3084 #ifdef SYNC_INPUT
3085   pending_signals = pending_atimers;
3086 #endif
3088   BLOCK_INPUT;
3089   n_emacs_events_pending = 0;
3090   EVENT_INIT (ev);
3091   emacs_event = &ev;
3092   q_event_ptr = hold_quit;
3094   /* we manage autorelease pools by allocate/reallocate each time around
3095      the loop; strict nesting is occasionally violated but seems not to
3096      matter.. earlier methods using full nesting caused major memory leaks */
3097   [outerpool release];
3098   outerpool = [[NSAutoreleasePool alloc] init];
3100   /* If have pending open-file requests, attend to the next one of those. */
3101   if (ns_pending_files && [ns_pending_files count] != 0
3102       && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3103     {
3104       [ns_pending_files removeObjectAtIndex: 0];
3105     }
3106   /* Deal with pending service requests. */
3107   else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3108     && [(EmacsApp *)
3109          NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3110                       withArg: [ns_pending_service_args objectAtIndex: 0]])
3111     {
3112       [ns_pending_service_names removeObjectAtIndex: 0];
3113       [ns_pending_service_args removeObjectAtIndex: 0];
3114     }
3115   else
3116     {
3117       /* Run and wait for events.  We must always send one NX_APPDEFINED event
3118          to ourself, otherwise [NXApp run] will never exit.  */
3119       send_appdefined = YES;
3121       /* If called via ns_select, this is called once with expected=1,
3122          because we expect either the timeout or file descriptor activity.
3123          In this case the first event through will either be real input or
3124          one of these.  read_avail_input() then calls once more with expected=0
3125          and in that case we need to return quickly if there is nothing.
3126          If we're being called outside of that, it's also OK to return quickly
3127          after one iteration through the event loop, since other terms do
3128          this and emacs expects it. */
3129       if (!(inNsSelect && expected))
3130         {
3131           /* Post an application defined event on the event queue.  When this is
3132              received the [NXApp run] will return, thus having processed all
3133              events which are currently queued, if any.  */
3134           ns_send_appdefined (-1);
3135         }
3137       [NSApp run];
3138     }
3140   nevents = n_emacs_events_pending;
3141   n_emacs_events_pending = 0;
3142   emacs_event = q_event_ptr = NULL;
3143   UNBLOCK_INPUT;
3145   return nevents;
3150 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3151            fd_set *exceptfds, struct timeval *timeout)
3152 /* --------------------------------------------------------------------------
3153      Replacement for select, checking for events
3154    -------------------------------------------------------------------------- */
3156   int result;
3157   double time;
3158   NSEvent *ev;
3159 /*  NSTRACE (ns_select); */
3161   if (NSApp == nil || inNsSelect == 1 /* || ([NSApp isActive] == NO &&
3162                       [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
3163  inMode:NSDefaultRunLoopMode dequeue:NO] == nil) */)
3164     return select (nfds, readfds, writefds, exceptfds, timeout);
3166   /* Save file descriptor set, which gets overwritten in calls to select ()
3167      Note, this is called from process.c, and only readfds is ever set */
3168   if (readfds)
3169     {
3170       memcpy (&select_readfds, readfds, sizeof (fd_set));
3171       select_nfds = nfds;
3172     }
3173   else
3174     select_nfds = 0;
3176     /* Try an initial select for pending data on input files */
3177   select_timeout.tv_sec = select_timeout.tv_usec = 0;
3178   result = select (nfds, readfds, writefds, exceptfds, &select_timeout);
3179   if (result)
3180     return result;
3182   /* if (!timeout || timed_entry || fd_entry)
3183        fprintf (stderr, "assertion failed: timeout null or timed_entry/fd_entry non-null in ns_select\n"); */
3185     /* set a timeout and run the main AppKit event loop while continuing
3186        to monitor the files */
3187   time = ((double) timeout->tv_sec) + ((double) timeout->tv_usec)/1000000.0;
3188   timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3189                                            target: NSApp
3190                                          selector: @selector (timeout_handler:)
3191                                          userInfo: 0
3192                                           repeats: YES] /* for safe removal */
3193                                                          retain];
3195   /* set a periodic task to try the select () again */
3196   fd_entry = [[NSTimer scheduledTimerWithTimeInterval: 0.1
3197                                                target: NSApp
3198                                              selector: @selector (fd_handler:)
3199                                              userInfo: 0
3200                                               repeats: YES]
3201                retain];
3203   /* Let Application dispatch events until it receives an event of the type
3204      NX_APPDEFINED, which should only be sent by timeout_handler.
3205      We tell read_avail_input() that input is "expected" because we do expect
3206      either the timeout or fd handler to fire, and if they don't, the original
3207      call from process.c that got us here expects us to wait until some input
3208      comes. */
3209   inNsSelect = 1;
3210   gobble_input (1);
3211   ev = last_appdefined_event;
3212   inNsSelect = 0;
3214   if (ev)
3215     {
3216       int t;
3217       if ([ev type] != NSApplicationDefined)
3218         abort ();
3220       t = [ev data1];
3221       last_appdefined_event = 0;
3223       if (t == -2)
3224         {
3225           /* The NX_APPDEFINED event we received was a timeout. */
3226           return 0;
3227         }
3228       else if (t == -1)
3229         {
3230           /* The NX_APPDEFINED event we received was the result of
3231              at least one real input event arriving.  */
3232           errno = EINTR;
3233           return -1;
3234         }
3235       else
3236         {
3237           /* Received back from select () in fd_handler; copy the results */
3238           if (readfds)
3239             memcpy (readfds, &select_readfds, sizeof (fd_set));
3240           return t;
3241         }
3242     }
3243   /* never reached, shut compiler up */
3244   return 0;
3249 /* ==========================================================================
3251     Scrollbar handling
3253    ========================================================================== */
3256 static void
3257 ns_set_vertical_scroll_bar (struct window *window,
3258                            int portion, int whole, int position)
3259 /* --------------------------------------------------------------------------
3260       External (hook): Update or add scrollbar
3261    -------------------------------------------------------------------------- */
3263   Lisp_Object win;
3264   NSRect r, v;
3265   struct frame *f = XFRAME (WINDOW_FRAME (window));
3266   EmacsView *view = FRAME_NS_VIEW (f);
3267   int window_y, window_height;
3268   BOOL barOnVeryLeft, barOnVeryRight;
3269   int top, left, height, width, sb_width, sb_left;
3270   EmacsScroller *bar;
3271 static int count = 0;
3273   /* optimization; display engine sends WAY too many of these.. */
3274   if (!NILP (window->vertical_scroll_bar))
3275     {
3276       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3277       if ([bar checkSamePosition: position portion: portion whole: whole])
3278         {
3279           if (view->scrollbarsNeedingUpdate == 0)
3280             {
3281               if (!windows_or_buffers_changed)
3282                   return;
3283             }
3284           else
3285             view->scrollbarsNeedingUpdate--;
3286         }
3287     }
3289   NSTRACE (ns_set_vertical_scroll_bar);
3291   /* Get dimensions.  */
3292   window_box (window, -1, 0, &window_y, 0, &window_height);
3293   top = window_y;
3294   height = window_height;
3295   width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3296   left = WINDOW_SCROLL_BAR_AREA_X (window);
3298   if (top < 5) /* top scrollbar adjustment */
3299     {
3300       top -= FRAME_INTERNAL_BORDER_WIDTH (f);
3301       height += FRAME_INTERNAL_BORDER_WIDTH (f);
3302     }
3304   /* allow for displaying a skinnier scrollbar than char area allotted */
3305   sb_width = (WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) > 0) ?
3306     WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) : width;
3308   barOnVeryLeft = left < 5;
3309   barOnVeryRight = FRAME_PIXEL_WIDTH (f) - left - width < 5;
3310   sb_left = left + FRAME_INTERNAL_BORDER_WIDTH (f)
3311       * (barOnVeryLeft ? -1 : (barOnVeryRight ? 1 : 0));
3313   r = NSMakeRect (sb_left, top, sb_width, height);
3314   /* the parent view is flipped, so we need to flip y value */
3315   v = [view frame];
3316   r.origin.y = (v.size.height - r.size.height - r.origin.y);
3318   XSETWINDOW (win, window);
3319   BLOCK_INPUT;
3321   /* we want at least 5 lines to display a scrollbar */
3322   if (WINDOW_TOTAL_LINES (window) < 5)
3323     {
3324       if (!NILP (window->vertical_scroll_bar))
3325         {
3326           bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3327           [bar removeFromSuperview];
3328           window->vertical_scroll_bar = Qnil;
3329         }
3330       ns_clear_frame_area (f, sb_left, top, width, height);
3331       UNBLOCK_INPUT;
3332       return;
3333     }
3335   if (NILP (window->vertical_scroll_bar))
3336     {
3337       ns_clear_frame_area (f, sb_left, top, width, height);
3338       bar = [[EmacsScroller alloc] initFrame: r window: win];
3339       window->vertical_scroll_bar = make_save_value (bar, 0);
3340     }
3341   else
3342     {
3343       NSRect oldRect;
3344       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3345       oldRect = [bar frame];
3346       r.size.width = oldRect.size.width;
3347       if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3348         {
3349           if (oldRect.origin.x != r.origin.x)
3350               ns_clear_frame_area (f, sb_left, top, width, height);
3351           [bar setFrame: r];
3352         }
3353     }
3355   [bar setPosition: position portion: portion whole: whole];
3356   UNBLOCK_INPUT;
3360 static void
3361 ns_condemn_scroll_bars (struct frame *f)
3362 /* --------------------------------------------------------------------------
3363      External (hook): arrange for all frame's scrollbars to be removed
3364      at next call to judge_scroll_bars, except for those redeemed.
3365    -------------------------------------------------------------------------- */
3367   int i;
3368   id view;
3369   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3371   NSTRACE (ns_condemn_scroll_bars);
3373   for (i =[subviews count]-1; i >= 0; i--)
3374     {
3375       view = [subviews objectAtIndex: i];
3376       if ([view isKindOfClass: [EmacsScroller class]])
3377         [view condemn];
3378     }
3382 static void
3383 ns_redeem_scroll_bar (struct window *window)
3384 /* --------------------------------------------------------------------------
3385      External (hook): arrange to spare this window's scrollbar
3386      at next call to judge_scroll_bars.
3387    -------------------------------------------------------------------------- */
3389   id bar;
3390   NSTRACE (ns_redeem_scroll_bar);
3391   if (!NILP (window->vertical_scroll_bar))
3392     {
3393       bar =XNS_SCROLL_BAR (window->vertical_scroll_bar);
3394       [bar reprieve];
3395     }
3399 static void
3400 ns_judge_scroll_bars (struct frame *f)
3401 /* --------------------------------------------------------------------------
3402      External (hook): destroy all scrollbars on frame that weren't
3403      redeemed after call to condemn_scroll_bars.
3404    -------------------------------------------------------------------------- */
3406   int i;
3407   id view;
3408   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3409   NSTRACE (ns_judge_scroll_bars);
3410   for (i =[subviews count]-1; i >= 0; i--)
3411     {
3412       view = [subviews objectAtIndex: i];
3413       if (![view isKindOfClass: [EmacsScroller class]]) continue;
3414       [view judge];
3415     }
3419 void
3420 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
3422   /* XXX irrelevant under NS */
3427 /* ==========================================================================
3429     Initialization
3431    ========================================================================== */
3434 x_display_pixel_height (dpyinfo)
3435      struct ns_display_info *dpyinfo;
3437   NSScreen *screen = [NSScreen mainScreen];
3438   return [screen frame].size.height;
3442 x_display_pixel_width (dpyinfo)
3443      struct ns_display_info *dpyinfo;
3445   NSScreen *screen = [NSScreen mainScreen];
3446   return [screen frame].size.width;
3450 static Lisp_Object ns_string_to_lispmod (const char *s)
3451 /* --------------------------------------------------------------------------
3452      Convert modifier name to lisp symbol
3453    -------------------------------------------------------------------------- */
3455   if (!strncmp (SDATA (SYMBOL_NAME (Qmeta)), s, 10))
3456     return Qmeta;
3457   else if (!strncmp (SDATA (SYMBOL_NAME (Qsuper)), s, 10))
3458     return Qsuper;
3459   else if (!strncmp (SDATA (SYMBOL_NAME (Qcontrol)), s, 10))
3460     return Qcontrol;
3461   else if (!strncmp (SDATA (SYMBOL_NAME (Qalt)), s, 10))
3462     return Qalt;
3463   else if (!strncmp (SDATA (SYMBOL_NAME (Qhyper)), s, 10))
3464     return Qhyper;
3465   else if (!strncmp (SDATA (SYMBOL_NAME (Qnone)), s, 10))
3466     return Qnone;
3467   else
3468     return Qnil;
3472 static Lisp_Object ns_mod_to_lisp (int m)
3473 /* --------------------------------------------------------------------------
3474      Convert modifier code (see lisp.h) to lisp symbol
3475    -------------------------------------------------------------------------- */
3477   if (m == CHAR_META)
3478     return Qmeta;
3479   else if (m == CHAR_SUPER)
3480     return Qsuper;
3481   else if (m == CHAR_CTL)
3482     return Qcontrol;
3483   else if (m == CHAR_ALT)
3484     return Qalt;
3485   else if (m == CHAR_HYPER)
3486     return Qhyper;
3487   else /* if (m == 0) */
3488     return Qnone;
3492 static void
3493 ns_default (const char *parameter, Lisp_Object *result,
3494            Lisp_Object yesval, Lisp_Object noval,
3495            BOOL is_float, BOOL is_modstring)
3496 /* --------------------------------------------------------------------------
3497       Check a parameter value in user's preferences
3498    -------------------------------------------------------------------------- */
3500   const char *value;
3502   if ( (value =[[[NSUserDefaults standardUserDefaults]
3503                    stringForKey: [NSString stringWithUTF8String: parameter]]
3504                 UTF8String]) )
3505     {
3506       double f;
3507       char *pos;
3508       if (strcasecmp (value, "YES") == 0)
3509         *result = yesval;
3510       else if (strcasecmp (value, "NO") == 0)
3511         *result = noval;
3512       else if (is_float && (f = strtod (value, &pos), pos != value))
3513         *result = make_float (f);
3514       else if (is_modstring && value)
3515         *result = ns_string_to_lispmod (value);
3516       else fprintf (stderr,
3517                    "Bad value for default \"%s\": \"%s\"\n", parameter, value);
3518     }
3522 void
3523 ns_initialize_display_info (struct ns_display_info *dpyinfo)
3524 /* --------------------------------------------------------------------------
3525       Initialize global info and storage for display.
3526    -------------------------------------------------------------------------- */
3528     NSScreen *screen = [NSScreen mainScreen];
3529     NSWindowDepth depth = [screen depth];
3531     dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
3532     dpyinfo->resy = 72.27;
3533     dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
3534                                                   NSColorSpaceFromDepth (depth)]
3535                 && ![NSCalibratedWhiteColorSpace isEqualToString:
3536                                                  NSColorSpaceFromDepth (depth)];
3537     dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
3538     dpyinfo->image_cache = make_image_cache ();
3539     dpyinfo->color_table
3540       = (struct ns_color_table *)xmalloc (sizeof (struct ns_color_table));
3541     dpyinfo->color_table->colors = NULL;
3542     dpyinfo->root_window = 42; /* a placeholder.. */
3544     dpyinfo->mouse_face_mouse_frame = NULL;
3545     dpyinfo->mouse_face_deferred_gc = 0;
3546     dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
3547     dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
3548     dpyinfo->mouse_face_face_id = DEFAULT_FACE_ID;
3549     dpyinfo->mouse_face_window = dpyinfo->mouse_face_overlay = Qnil;
3550     dpyinfo->mouse_face_hidden = 0;
3552     dpyinfo->mouse_face_mouse_x = dpyinfo->mouse_face_mouse_y = 0;
3553     dpyinfo->mouse_face_defer = 0;
3555     dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
3557     dpyinfo->n_fonts = 0;
3558     dpyinfo->smallest_font_height = 1;
3559     dpyinfo->smallest_char_width = 1;
3563 /* This and next define (many of the) public functions in this file. */
3564 /* x_... are generic versions in xdisp.c that we, and other terms, get away
3565          with using despite presence in the "system dependent" redisplay
3566          interface.  In addition, many of the ns_ methods have code that is
3567          shared with all terms, indicating need for further refactoring. */
3568 extern frame_parm_handler ns_frame_parm_handlers[];
3569 static struct redisplay_interface ns_redisplay_interface =
3571   ns_frame_parm_handlers,
3572   x_produce_glyphs,
3573   x_write_glyphs,
3574   x_insert_glyphs,
3575   x_clear_end_of_line,
3576   ns_scroll_run,
3577   ns_after_update_window_line,
3578   ns_update_window_begin,
3579   ns_update_window_end,
3580   x_cursor_to,
3581   ns_flush,
3582   0, /* flush_display_optional */
3583   x_clear_window_mouse_face,
3584   x_get_glyph_overhangs,
3585   x_fix_overlapping_area,
3586   ns_draw_fringe_bitmap,
3587   0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
3588   0, /* destroy_fringe_bitmap */
3589   ns_compute_glyph_string_overhangs,
3590   ns_draw_glyph_string, /* interface to nsfont.m */
3591   ns_define_frame_cursor,
3592   ns_clear_frame_area,
3593   ns_draw_window_cursor,
3594   ns_draw_vertical_window_border,
3595   ns_shift_glyphs_for_insert
3599 static void
3600 ns_delete_display (struct ns_display_info *dpyinfo)
3602   /* TODO... */
3606 /* This function is called when the last frame on a display is deleted. */
3607 static void
3608 ns_delete_terminal (struct terminal *terminal)
3610   struct ns_display_info *dpyinfo = terminal->display_info.ns;
3611   int i;
3613   /* Protect against recursive calls.  delete_frame in
3614      delete_terminal calls us back when it deletes our last frame.  */
3615   if (!terminal->name)
3616     return;
3618   BLOCK_INPUT;
3620   x_destroy_all_bitmaps (dpyinfo);
3621   ns_delete_display (dpyinfo);
3622   UNBLOCK_INPUT;
3626 static struct terminal *
3627 ns_create_terminal (struct ns_display_info *dpyinfo)
3628 /* --------------------------------------------------------------------------
3629       Set up use of NS before we make the first connection.
3630    -------------------------------------------------------------------------- */
3632   struct terminal *terminal;
3634   NSTRACE (ns_create_terminal);
3636   terminal = create_terminal ();
3638   terminal->type = output_ns;
3639   terminal->display_info.ns = dpyinfo;
3640   dpyinfo->terminal = terminal;
3642   terminal->rif = &ns_redisplay_interface;
3644   terminal->clear_frame_hook = ns_clear_frame;
3645   terminal->ins_del_lines_hook = 0; /* XXX vestigial? */
3646   terminal->delete_glyphs_hook = 0; /* XXX vestigial? */
3647   terminal->ring_bell_hook = ns_ring_bell;
3648   terminal->reset_terminal_modes_hook = ns_reset_terminal_modes;
3649   terminal->set_terminal_modes_hook = ns_set_terminal_modes;
3650   terminal->update_begin_hook = ns_update_begin;
3651   terminal->update_end_hook = ns_update_end;
3652   terminal->set_terminal_window_hook = NULL; /* XXX vestigial? */
3653   terminal->read_socket_hook = ns_read_socket;
3654   terminal->frame_up_to_date_hook = ns_frame_up_to_date;
3655   terminal->mouse_position_hook = ns_mouse_position;
3656   terminal->frame_rehighlight_hook = ns_frame_rehighlight;
3657   terminal->frame_raise_lower_hook = ns_frame_raise_lower;
3659   terminal->fullscreen_hook = 0; /* see XTfullscreen_hook */
3661   terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
3662   terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
3663   terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
3664   terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
3666   terminal->delete_frame_hook = x_destroy_window;
3667   terminal->delete_terminal_hook = ns_delete_terminal;
3669   terminal->scroll_region_ok = 1;
3670   terminal->char_ins_del_ok = 1;
3671   terminal->line_ins_del_ok = 1;
3672   terminal->fast_clear_end_of_line = 1;
3673   terminal->memory_below_frame = 0;
3675   return terminal;
3679 struct ns_display_info *
3680 ns_term_init (Lisp_Object display_name)
3681 /* --------------------------------------------------------------------------
3682      Start the Application and get things rolling.
3683    -------------------------------------------------------------------------- */
3685   struct terminal *terminal;
3686   struct ns_display_info *dpyinfo;
3687   static int ns_initialized = 0;
3688   Lisp_Object tmp;
3690   NSTRACE (ns_term_init);
3692   /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
3693   /*GSDebugAllocationActive (YES); */
3694   BLOCK_INPUT;
3695   handling_signal = 0;
3697   if (!ns_initialized)
3698     {
3699       baud_rate = 38400;
3700       Fset_input_interrupt_mode (Qnil);
3701       ns_initialized = 1;
3702     }
3704   ns_pending_files = [[NSMutableArray alloc] init];
3705   ns_pending_service_names = [[NSMutableArray alloc] init];
3706   ns_pending_service_args = [[NSMutableArray alloc] init];
3708   /* Start app and create the main menu, window, view.
3709      Needs to be here because ns_initialize_display_info () uses AppKit classes.
3710      The view will then ask the NSApp to stop and return to Emacs. */
3711   [EmacsApp sharedApplication];
3712   if (NSApp == nil)
3713     return NULL;
3714   [NSApp setDelegate: NSApp];
3716   /* debugging: log all notifications */
3717   /*   [[NSNotificationCenter defaultCenter] addObserver: NSApp
3718                                          selector: @selector (logNotification:)
3719                                              name: nil object: nil]; */
3721   dpyinfo = (struct ns_display_info *)xmalloc (sizeof (struct ns_display_info));
3722   bzero (dpyinfo, sizeof (struct ns_display_info));
3724   ns_initialize_display_info (dpyinfo);
3725   terminal = ns_create_terminal (dpyinfo);
3727   terminal->kboard = (KBOARD *) xmalloc (sizeof (KBOARD));
3728   init_kboard (terminal->kboard);
3729   terminal->kboard->Vwindow_system = Qns;
3730   terminal->kboard->next_kboard = all_kboards;
3731   all_kboards = terminal->kboard;
3732   /* Don't let the initial kboard remain current longer than necessary.
3733      That would cause problems if a file loaded on startup tries to
3734      prompt in the mini-buffer.  */
3735   if (current_kboard == initial_kboard)
3736     current_kboard = terminal->kboard;
3737   terminal->kboard->reference_count++;
3739   dpyinfo->next = x_display_list;
3740   x_display_list = dpyinfo;
3742   /* Put it on ns_display_name_list */
3743   ns_display_name_list = Fcons (Fcons (display_name, Qnil),
3744                                 ns_display_name_list);
3745   dpyinfo->name_list_element = XCAR (ns_display_name_list);
3747   /* Set the name of the terminal. */
3748   terminal->name = (char *) xmalloc (SBYTES (display_name) + 1);
3749   strncpy (terminal->name, SDATA (display_name), SBYTES (display_name));
3750   terminal->name[SBYTES (display_name)] = 0;
3752   UNBLOCK_INPUT; 
3754   if (!inhibit_x_resources)
3755     {
3756       ns_default ("GSFontAntiAlias", &ns_antialias_text,
3757                  Qt, Qnil, NO, NO);
3758       tmp = Qnil;
3759       /* this is a standard variable */
3760       ns_default ("AppleAntiAliasingThreshold", &tmp,
3761                  make_float (10.0), make_float (6.0), YES, NO);
3762       ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
3763     }
3765   ns_selection_color = [[NSUserDefaults standardUserDefaults]
3766                          stringForKey: @"AppleHighlightColor"];
3767   if (ns_selection_color == nil)
3768     ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
3769   
3770   {
3771     NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
3773     if ( cl == nil )
3774       {
3775         Lisp_Object color_file, color_map, color;
3776         int r,g,b;
3777         unsigned long c;
3778         char *name;
3780         color_file = Fexpand_file_name (build_string ("rgb.txt"),
3781                          Fsymbol_value (intern ("data-directory")));
3782         if (NILP (Ffile_readable_p (color_file)))
3783           fatal ("Could not find %s.\n", SDATA (color_file));
3785         color_map = Fx_load_color_file (color_file);
3786         if (NILP (color_map))
3787           fatal ("Could not read %s.\n", SDATA (color_file));
3789         cl = [[NSColorList alloc] initWithName: @"Emacs"];
3790         for ( ; CONSP (color_map); color_map = XCDR (color_map))
3791           {
3792             color = XCAR (color_map);
3793             name = SDATA (XCAR (color));
3794             c = XINT (XCDR (color));
3795             [cl setColor:
3796                   [NSColor colorWithCalibratedRed: RED_FROM_ULONG (c) / 255.0
3797                                             green: GREEN_FROM_ULONG (c) / 255.0
3798                                              blue: BLUE_FROM_ULONG (c) / 255.0
3799                                             alpha: 1.0]
3800                   forKey: [NSString stringWithUTF8String: name]];
3801           }
3802         [cl writeToFile: nil];
3803       }
3804   }
3806   {
3807     char c[128];
3808 #ifdef NS_IMPL_GNUSTEP
3809     strncpy (c, gnustep_base_version, sizeof (c));
3810 #else
3811     /*PSnextrelease (128, c); */
3812     snprintf (c, sizeof (c), "%g", NSAppKitVersionNumber);
3813 #endif
3814     Vwindow_system_version = build_string (c);
3815   }
3817   delete_keyboard_wait_descriptor (0);
3819   ns_app_name = [[NSProcessInfo processInfo] processName];
3821 /* Set up OS X app menu */
3822 #ifdef NS_IMPL_COCOA
3823   {
3824     NSMenu *appMenu;
3825     NSMenuItem *item;
3826     /* set up the application menu */
3827     svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
3828     [svcsMenu setAutoenablesItems: NO];
3829     appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
3830     [appMenu setAutoenablesItems: NO];
3831     mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
3832     dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
3834     [appMenu insertItemWithTitle: @"About Emacs"
3835                           action: @selector (orderFrontStandardAboutPanel:)
3836                    keyEquivalent: @""
3837                          atIndex: 0];
3838     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
3839     [appMenu insertItemWithTitle: @"Preferences..."
3840                           action: @selector (showPreferencesWindow:)
3841                    keyEquivalent: @","
3842                          atIndex: 2];
3843     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
3844     item = [appMenu insertItemWithTitle: @"Services"
3845                                  action: @selector (menuDown:)
3846                           keyEquivalent: @""
3847                                 atIndex: 4];
3848     [appMenu setSubmenu: svcsMenu forItem: item];
3849     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
3850     [appMenu insertItemWithTitle: @"Hide Emacs"
3851                           action: @selector (hide:)
3852                    keyEquivalent: @"h"
3853                          atIndex: 6];
3854     item =  [appMenu insertItemWithTitle: @"Hide Others"
3855                           action: @selector (hideOtherApplications:)
3856                    keyEquivalent: @"h"
3857                          atIndex: 7];
3858     [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
3859     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
3860     [appMenu insertItemWithTitle: @"Quit Emacs"
3861                           action: @selector (terminate:)
3862                    keyEquivalent: @"q"
3863                          atIndex: 9];
3865     item = [mainMenu insertItemWithTitle: ns_app_name                       
3866                                   action: @selector (menuDown:)
3867                            keyEquivalent: @""
3868                                  atIndex: 0];
3869     [mainMenu setSubmenu: appMenu forItem: item];
3870     [dockMenu insertItemWithTitle: @"New Frame"
3871                            action: @selector (newFrame:)
3872                     keyEquivalent: @""
3873                           atIndex: 0];
3875     [NSApp setMainMenu: mainMenu];
3876     [NSApp setAppleMenu: appMenu];
3877     [NSApp setServicesMenu: svcsMenu];
3878     /* Needed at least on Cocoa, to get dock menu to show windows */
3879     [NSApp setWindowsMenu: [[NSMenu alloc] init]];
3880   }
3881 #endif /* MAC OS X menu setup */
3883   [NSApp run];
3885   return dpyinfo;
3889 extern Lisp_Object Vauto_save_list_file_name;
3890 void
3891 ns_term_shutdown (int sig)
3893   /* code not reached in emacs.c after this is called by shut_down_emacs: */
3894   if (STRINGP (Vauto_save_list_file_name))
3895     unlink (SDATA (Vauto_save_list_file_name));
3897   if (sig == 0 || sig == SIGTERM)
3898     {
3899       [NSApp terminate: NSApp];
3900     }
3901   else // force a stack trace to happen
3902     {
3903       abort();
3904     }
3908 /* ==========================================================================
3910     EmacsApp implementation
3912    ========================================================================== */
3915 @implementation EmacsApp
3917 - (void)logNotification: (NSNotification *)notification
3919   const char *name = [[notification name] UTF8String];
3920   if (!strstr (name, "Update") && !strstr (name, "NSMenu")
3921       && !strstr (name, "WindowNumber"))
3922     NSLog (@"notification: '%@'", [notification name]);
3926 - (void)sendEvent: (NSEvent *)theEvent
3927 /* --------------------------------------------------------------------------
3928      Called when NSApp is running for each event received.  Used to stop
3929      the loop when we choose, since there's no way to just run one iteration.
3930    -------------------------------------------------------------------------- */
3932   int type = [theEvent type];
3933   NSWindow *window = [theEvent window];
3934 /*  NSTRACE (sendEvent); */
3935 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
3937   if (type == NSCursorUpdate && window == nil)
3938     {
3939       fprintf (stderr, "Dropping external cursor update event.\n");
3940       return;
3941     }
3943 #ifdef NS_IMPL_COCOA
3944   /* pass mouse down in resize handle and subsequent drags directly to
3945      EmacsWindow so we can generate continuous redisplays */
3946   if (ns_in_resize)
3947     {
3948       if (type == NSLeftMouseDragged)
3949         {
3950           [window mouseDragged: theEvent];
3951           return;
3952         }
3953       else if (type == NSLeftMouseUp)
3954         {
3955           [window mouseUp: theEvent];
3956           return;
3957         }
3958     }
3959   else if (type == NSLeftMouseDown)
3960     {
3961       NSRect r = ns_resize_handle_rect (window);
3962       if (NSPointInRect ([theEvent locationInWindow], r))
3963         {
3964           ns_in_resize = YES;
3965           [window mouseDown: theEvent];
3966           return;
3967         }
3968     }
3969 #endif
3971   if (type == NSApplicationDefined)
3972     {
3973       /* Events posted by ns_send_appdefined interrupt the run loop here.
3974          But, if a modal window is up, an appdefined can still come through,
3975          (e.g., from a makeKeyWindow event) but stopping self also stops the
3976          modal loop. Just defer it until later. */
3977       if ([NSApp modalWindow] == nil)
3978         {
3979           last_appdefined_event = theEvent;
3980           [self stop: self];
3981         }
3982       else
3983         {
3984           send_appdefined = YES;
3985         }
3986     }
3988   [super sendEvent: theEvent];
3992 - (void)showPreferencesWindow: (id)sender
3994   struct frame *emacsframe = SELECTED_FRAME ();
3995   NSEvent *theEvent = [NSApp currentEvent];
3997   if (!emacs_event)
3998     return;
3999   emacs_event->kind = NS_NONKEY_EVENT;
4000   emacs_event->code = KEY_NS_SHOW_PREFS;
4001   emacs_event->modifiers = 0;
4002   EV_TRAILER (theEvent);
4006 - (void)newFrame: (id)sender
4008   struct frame *emacsframe = SELECTED_FRAME ();
4009   NSEvent *theEvent = [NSApp currentEvent];
4011   if (!emacs_event)
4012     return;
4013   emacs_event->kind = NS_NONKEY_EVENT;
4014   emacs_event->code = KEY_NS_NEW_FRAME;
4015   emacs_event->modifiers = 0;
4016   EV_TRAILER (theEvent);
4020 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4021 - (BOOL) openFile: (NSString *)fileName
4023   struct frame *emacsframe = SELECTED_FRAME ();
4024   NSEvent *theEvent = [NSApp currentEvent];
4026   if (!emacs_event)
4027     return NO;
4029   emacs_event->kind = NS_NONKEY_EVENT;
4030   emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4031   ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4032   ns_input_line = Qnil; /* can be start or cons start,end */
4033   emacs_event->modifiers =0;
4034   EV_TRAILER (theEvent);
4036   return YES;
4040 /* **************************************************************************
4042       EmacsApp delegate implementation
4044    ************************************************************************** */
4046 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4047 /* --------------------------------------------------------------------------
4048      When application is loaded, terminate event loop in ns_term_init
4049    -------------------------------------------------------------------------- */
4051   NSTRACE (applicationDidFinishLaunching);
4052   [NSApp setServicesProvider: NSApp];
4053   ns_send_appdefined (-2);
4057 /* Termination sequences:
4058     C-x C-c:
4059     Cmd-Q:
4060     MenuBar | File | Exit:
4061     Select Quit from App menubar:
4062         -terminate
4063         KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4064         ns_term_shutdown()
4066     Select Quit from Dock menu:
4067     Logout attempt:
4068         -appShouldTerminate
4069           Cancel -> Nothing else
4070           Accept ->
4071           
4072           -terminate
4073           KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4074           ns_term_shutdown()
4078 - (void) terminate: (id)sender
4080   struct frame *emacsframe = SELECTED_FRAME ();
4081   
4082   if (!emacs_event)
4083     return;
4084   
4085   emacs_event->kind = NS_NONKEY_EVENT;
4086   emacs_event->code = KEY_NS_POWER_OFF;
4087   emacs_event->arg = Qt; /* mark as non-key event */
4088   EV_TRAILER ((id)nil);
4092 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4094   int ret;
4096   if (NILP (ns_confirm_quit)) //   || ns_shutdown_properly  --> TO DO
4097     return NSTerminateNow;
4099     ret = NSRunAlertPanel(ns_app_name,
4100                           [NSString stringWithUTF8String:"Exit requested.  Would you like to Save Buffers and Exit, or Cancel the request?"],
4101                           @"Save Buffers and Exit", @"Cancel", nil);
4103     if (ret == NSAlertDefaultReturn)
4104         return NSTerminateNow;
4105     else if (ret == NSAlertAlternateReturn)
4106         return NSTerminateCancel;
4107     return NSTerminateNow;  /* just in case */
4111 /*   Notification from the Workspace to open a file */
4112 - (BOOL)application: sender openFile: (NSString *)file
4114   [ns_pending_files addObject: file];
4115   return YES;
4119 /*   Open a file as a temporary file */
4120 - (BOOL)application: sender openTempFile: (NSString *)file
4122   [ns_pending_files addObject: file];
4123   return YES;
4127 /*   Notification from the Workspace to open a file noninteractively (?) */
4128 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4130   [ns_pending_files addObject: file];
4131   return YES;
4135 /*   Notification from the Workspace to open multiple files */
4136 - (void)application: sender openFiles: (NSArray *)fileList
4138   NSEnumerator *files = [fileList objectEnumerator];
4139   NSString *file;
4140   while ((file = [files nextObject]) != nil)
4141     [ns_pending_files addObject: file];
4143   [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4148 /* Handle dock menu requests.  */
4149 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4151   return dockMenu;
4155 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4156 - (void)applicationWillBecomeActive: (NSNotification *)notification
4158   //ns_app_active=YES;
4160 - (void)applicationDidBecomeActive: (NSNotification *)notification
4162   //ns_app_active=YES;
4164 - (void)applicationDidResignActive: (NSNotification *)notification
4166   //ns_app_active=NO;
4167   ns_send_appdefined (-1);
4172 /* ==========================================================================
4174     EmacsApp aux handlers for managing event loop
4176    ========================================================================== */
4179 - (void)timeout_handler: (NSTimer *)timedEntry
4180 /* --------------------------------------------------------------------------
4181      The timeout specified to ns_select has passed.
4182    -------------------------------------------------------------------------- */
4184   /*NSTRACE (timeout_handler); */
4185   ns_send_appdefined (-2);
4188 - (void)fd_handler: (NSTimer *) fdEntry
4189 /* --------------------------------------------------------------------------
4190      Check data waiting on file descriptors and terminate if so
4191    -------------------------------------------------------------------------- */
4193   int result;
4194   /* NSTRACE (fd_handler); */
4196   if (select_nfds == 0)
4197     return;
4199   memcpy (&t_readfds, &select_readfds, sizeof (fd_set));
4201   select_timeout.tv_sec = select_timeout.tv_usec = 0;
4202   result = select (select_nfds, &t_readfds, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
4203                   &select_timeout);
4204   if (result)
4205     {
4206       memcpy (&select_readfds, &t_readfds, sizeof (fd_set));
4207       ns_send_appdefined (result);
4208     }
4213 /* ==========================================================================
4215     Service provision
4217    ========================================================================== */
4219 /* called from system: queue for next pass through event loop */
4220 - (void)requestService: (NSPasteboard *)pboard
4221               userData: (NSString *)userData
4222                  error: (NSString **)error
4224   [ns_pending_service_names addObject: userData];
4225   [ns_pending_service_args addObject: [NSString stringWithUTF8String:
4226       SDATA (ns_string_from_pasteboard (pboard))]];
4230 /* called from ns_read_socket to clear queue */
4231 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
4233   struct frame *emacsframe = SELECTED_FRAME ();
4234   NSEvent *theEvent = [NSApp currentEvent];
4236   if (!emacs_event)
4237     return NO;
4239   emacs_event->kind = NS_NONKEY_EVENT;
4240   emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
4241   ns_input_spi_name = build_string ([name UTF8String]);
4242   ns_input_spi_arg = build_string ([arg UTF8String]);
4243   emacs_event->modifiers = EV_MODIFIERS (theEvent);
4244   EV_TRAILER (theEvent);
4246   return YES;
4250 @end  /* EmacsApp */
4254 /* ==========================================================================
4256     EmacsView implementation
4258    ========================================================================== */
4261 @implementation EmacsView
4263 /* needed to inform when window closed from LISP */
4264 - (void) setWindowClosing: (BOOL)closing
4266   windowClosing = closing;
4270 - (void)dealloc
4272   NSTRACE (EmacsView_dealloc);
4273   [toolbar release];
4274   [super dealloc];
4278 /* called on font panel selection */
4279 - (void)changeFont: (id)sender
4281   NSEvent *e =[[self window] currentEvent];
4282   struct face *face =FRAME_DEFAULT_FACE (emacsframe);
4283   id newFont;
4284   float size;
4286   NSTRACE (changeFont);
4287   if (!emacs_event)
4288     return;
4290   if (newFont = [sender convertFont:
4291                            ((struct nsfont_info *)face->font)->nsfont])
4292     {
4293       SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
4295       emacs_event->kind = NS_NONKEY_EVENT;
4296       emacs_event->modifiers = 0;
4297       emacs_event->code = KEY_NS_CHANGE_FONT;
4299       size = [newFont pointSize];
4300       ns_input_fontsize = make_number (lrint (size));
4301       ns_input_font = build_string ([[newFont familyName] UTF8String]);
4302       EV_TRAILER (e);
4303     }
4307 - (BOOL)acceptsFirstResponder
4309   NSTRACE (acceptsFirstResponder);
4310   return YES;
4314 - (void)resetCursorRects
4316   NSRect visible = [self visibleRect];
4317   NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
4318   NSTRACE (resetCursorRects);
4320   if (currentCursor == nil)
4321     currentCursor = [NSCursor arrowCursor];
4323   if (!NSIsEmptyRect (visible))
4324     [self addCursorRect: visible cursor: currentCursor];
4325   [currentCursor setOnMouseEntered: YES];
4330 /*****************************************************************************/
4331 /* Keyboard handling. */
4332 #define NS_KEYLOG 0
4334 - (void)keyDown: (NSEvent *)theEvent
4336   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4337   int code;
4338   unsigned fnKeysym = 0;
4339   int flags;
4340   static NSMutableArray *nsEvArray;
4341   static BOOL firstTime = YES;
4343   NSTRACE (keyDown);
4345   /* Rhapsody and OS X give up and down events for the arrow keys */
4346   if (ns_fake_keydown == YES)
4347     ns_fake_keydown = NO;
4348   else if ([theEvent type] != NSKeyDown)
4349     return;
4351   if (!emacs_event)
4352     return;
4354  if (![[self window] isKeyWindow]
4355      && [[theEvent window] isKindOfClass: [EmacsWindow class]]
4356      /* we must avoid an infinite loop here. */
4357      && (EmacsView *)[[theEvent window] delegate] != self)
4358    {
4359      /* XXX: There is an occasional condition in which, when Emacs display
4360          updates a different frame from the current one, and temporarily
4361          selects it, then processes some interrupt-driven input
4362          (dispnew.c:3878), OS will send the event to the correct NSWindow, but
4363          for some reason that window has its first responder set to the NSView
4364          most recently updated (I guess), which is not the correct one. */
4365      [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
4366      return;
4367    }
4369   if (nsEvArray == nil)
4370     nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
4372   [NSCursor setHiddenUntilMouseMoves: YES];
4374   if (dpyinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
4375     {
4376       clear_mouse_face (dpyinfo);
4377       dpyinfo->mouse_face_hidden = 1;
4378     }
4380   if (!processingCompose)
4381     {
4382       code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
4383         0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
4384       /* (Carbon way: [theEvent keyCode]) */
4386       /* is it a "function key"? */
4387       fnKeysym = ns_convert_key (code);
4388       if (fnKeysym)
4389         {
4390           /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
4391              because Emacs treats Delete and KP-Delete same (in simple.el). */
4392           if (fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
4393             code = 0xFF08; /* backspace */
4394           else
4395             code = fnKeysym;
4396         }
4398       /* are there modifiers? */
4399       emacs_event->modifiers = 0;
4400       flags = [theEvent modifierFlags];
4402       if (flags & NSHelpKeyMask)
4403           emacs_event->modifiers |= hyper_modifier;
4405       if (flags & NSShiftKeyMask)
4406         emacs_event->modifiers |= shift_modifier;
4408       if (flags & NSCommandKeyMask)
4409         {
4410           emacs_event->modifiers |= parse_solitary_modifier (ns_command_modifier);
4411           /* if super (default), take input manager's word so things like
4412              dvorak / qwerty layout work */
4413           if (EQ (ns_command_modifier, Qsuper)
4414               && !fnKeysym
4415               && [[theEvent characters] length] != 0)
4416             {
4417               /* XXX: the code we get will be unshifted, so if we have
4418                  a shift modifier, must convert ourselves */
4419               if (!(flags & NSShiftKeyMask))
4420                 code = [[theEvent characters] characterAtIndex: 0];
4421 #if 0
4422               /* this is ugly and also requires linking w/Carbon framework
4423                  (for LMGetKbdType) so for now leave this rare (?) case
4424                  undealt with.. in future look into CGEvent methods */
4425               else
4426                 {
4427                   long smv = GetScriptManagerVariable (smKeyScript);
4428                   Handle uchrHandle = GetResource
4429                     ('uchr', GetScriptVariable (smv, smScriptKeys));
4430                   UInt32 dummy = 0;
4431                   UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
4432                                  [[theEvent characters] characterAtIndex: 0],
4433                                  kUCKeyActionDisplay,
4434                                  (flags & ~NSCommandKeyMask) >> 8,
4435                                  LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
4436                                  &dummy, 1, &dummy, &code);
4437                   code &= 0xFF;
4438                 }
4439 #endif
4440             }
4441         }
4443       if (flags & NSControlKeyMask)
4444           emacs_event->modifiers |=
4445             parse_solitary_modifier (ns_control_modifier);
4447       if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
4448           emacs_event->modifiers |=
4449             parse_solitary_modifier (ns_function_modifier);
4451       if (!EQ (ns_right_alternate_modifier, Qleft)
4452           && ((flags & NSRightAlternateKeyMask) == NSRightAlternateKeyMask)) 
4453         {
4454           emacs_event->modifiers |= parse_solitary_modifier
4455             (ns_right_alternate_modifier);
4456         }
4457       else if (flags & NSAlternateKeyMask) /* default = meta */
4458         {
4459           if ((NILP (ns_alternate_modifier) || EQ (ns_alternate_modifier, Qnone))
4460               && !fnKeysym)
4461             {   /* accept pre-interp alt comb */
4462               if ([[theEvent characters] length] > 0)
4463                 code = [[theEvent characters] characterAtIndex: 0];
4464               /*HACK: clear lone shift modifier to stop next if from firing */
4465               if (emacs_event->modifiers == shift_modifier)
4466                 emacs_event->modifiers = 0;
4467             }
4468           else
4469               emacs_event->modifiers |=
4470                 parse_solitary_modifier (ns_alternate_modifier);
4471         }
4473   if (NS_KEYLOG)
4474     fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
4475              code, fnKeysym, flags, emacs_event->modifiers);
4477       /* if it was a function key or had modifiers, pass it directly to emacs */
4478       if (fnKeysym || (emacs_event->modifiers
4479                        && [[theEvent charactersIgnoringModifiers] length] > 0))
4480 /*[[theEvent characters] length] */
4481         {
4482           emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4483           if (code < 0x20)
4484             code |= (1<<28)|(3<<16);
4485           else if (code == 0x7f)
4486             code |= (1<<28)|(3<<16);
4487           else if (!fnKeysym)
4488             emacs_event->kind = code > 0xFF
4489               ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4491           emacs_event->code = code;
4492           EV_TRAILER (theEvent);
4493           return;
4494         }
4495     }
4497   /* if we get here we should send the key for input manager processing */
4498   if (firstTime && [[NSInputManager currentInputManager]
4499                      wantsToDelayTextChangeNotifications] == NO)
4500     fprintf (stderr,
4501           "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
4502   firstTime = NO;
4504   if (NS_KEYLOG && !processingCompose)
4505     fprintf (stderr, "keyDown: Begin compose sequence.\n");
4507   processingCompose = YES;
4508   [nsEvArray addObject: theEvent];
4509   [self interpretKeyEvents: nsEvArray];
4510   [nsEvArray removeObject: theEvent];
4514 #ifdef NS_IMPL_COCOA
4515 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
4516    decided not to send key-down for.
4517    See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
4518    This only applies on Tiger and earlier.
4519    If it matches one of these, send it on to keyDown. */
4520 -(void)keyUp: (NSEvent *)theEvent
4522   int flags = [theEvent modifierFlags];
4523   int code = [theEvent keyCode];
4524   if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
4525       code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
4526     {
4527       if (NS_KEYLOG)
4528         fprintf (stderr, "keyUp: passed test");
4529       ns_fake_keydown = YES;
4530       [self keyDown: theEvent];
4531     }
4533 #endif
4536 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
4539 /* <NSTextInput>: called when done composing;
4540    NOTE: also called when we delete over working text, followed immed.
4541          by doCommandBySelector: deleteBackward: */
4542 - (void)insertText: (id)aString
4544   int code;
4545   int len = [(NSString *)aString length];
4546   int i;
4548   if (NS_KEYLOG)
4549     NSLog (@"insertText '%@'\tlen = %d", aString, len);
4550   processingCompose = NO;
4552   if (!emacs_event)
4553     return;
4555   /* first, clear any working text */
4556   if (workingText != nil)
4557     [self deleteWorkingText];
4559   /* now insert the string as keystrokes */
4560   for (i =0; i<len; i++)
4561     {
4562       code = [aString characterAtIndex: i];
4563       /* TODO: still need this? */
4564       if (code == 0x2DC)
4565         code = '~'; /* 0x7E */
4566       emacs_event->modifiers = 0;
4567       emacs_event->kind
4568         = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4569       emacs_event->code = code;
4570       EV_TRAILER ((id)nil);
4571     }
4575 /* <NSTextInput>: inserts display of composing characters */
4576 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
4578   NSString *str = [aString respondsToSelector: @selector (string)] ?
4579     [aString string] : aString;
4580   if (NS_KEYLOG)
4581     NSLog (@"setMarkedText '%@' len =%d range %d from %d", str, [str length],
4582            selRange.length, selRange.location);
4584   if (workingText != nil)
4585     [self deleteWorkingText];
4586   if ([str length] == 0)
4587     return;
4589   if (!emacs_event)
4590     return;
4592   processingCompose = YES;
4593   workingText = [str copy];
4594   ns_working_text = build_string ([workingText UTF8String]);
4596   emacs_event->kind = NS_TEXT_EVENT;
4597   emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
4598   EV_TRAILER ((id)nil);
4602 /* delete display of composing characters [not in <NSTextInput>] */
4603 - (void)deleteWorkingText
4605   if (workingText == nil)
4606     return;
4607   if (NS_KEYLOG)
4608     NSLog(@"deleteWorkingText len =%d\n", [workingText length]);
4609   [workingText release];
4610   workingText = nil;
4611   processingCompose = NO;
4613   if (!emacs_event)
4614     return;
4616   emacs_event->kind = NS_TEXT_EVENT;
4617   emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
4618   EV_TRAILER ((id)nil);
4622 - (BOOL)hasMarkedText
4624   return workingText != nil;
4628 - (NSRange)markedRange
4630   NSRange rng = workingText != nil
4631     ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
4632   if (NS_KEYLOG)
4633     NSLog (@"markedRange request");
4634   return rng;
4638 - (void)unmarkText
4640   if (NS_KEYLOG)
4641     NSLog (@"unmark (accept) text");
4642   [self deleteWorkingText];
4643   processingCompose = NO;
4647 /* used to position char selection windows, etc. */
4648 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
4650   NSRect rect;
4651   NSPoint pt;
4652   struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
4653   if (NS_KEYLOG)
4654     NSLog (@"firstRectForCharRange request");
4656   rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
4657   rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
4658   pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
4659   pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
4660                                        +FRAME_LINE_HEIGHT (emacsframe));
4662   pt = [self convertPoint: pt toView: nil];
4663   pt = [[self window] convertBaseToScreen: pt];
4664   rect.origin = pt;
4665   return rect;
4669 - (long)conversationIdentifier
4671   return (long)self;
4675 - (void)doCommandBySelector: (SEL)aSelector
4677   if (NS_KEYLOG)
4678     NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
4680   if (aSelector == @selector (deleteBackward:))
4681     {
4682       /* happens when user backspaces over an ongoing composition:
4683          throw a 'delete' into the event queue */
4684       if (!emacs_event)
4685         return;
4686       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4687       emacs_event->code = 0xFF08;
4688       EV_TRAILER ((id)nil);
4689     }
4692 - (NSArray *)validAttributesForMarkedText
4694   static NSArray *arr = nil;
4695   if (arr == nil) arr = [NSArray new];
4696  /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
4697   return arr;
4700 - (NSRange)selectedRange
4702   if (NS_KEYLOG)
4703     NSLog (@"selectedRange request");
4704   return NSMakeRange (NSNotFound, 0);
4707 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
4709   if (NS_KEYLOG)
4710     NSLog (@"characterIndexForPoint request");
4711   return 0;
4714 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
4716   static NSAttributedString *str = nil;
4717   if (str == nil) str = [NSAttributedString new];
4718   if (NS_KEYLOG)
4719     NSLog (@"attributedSubstringFromRange request");
4720   return str;
4723 /* End <NSTextInput> impl. */
4724 /*****************************************************************************/
4727 /* This is what happens when the user presses a mouse button.  */
4728 - (void)mouseDown: (NSEvent *)theEvent
4730   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
4731   Lisp_Object window;
4733   NSTRACE (mouseDown);
4735   [self deleteWorkingText];
4737   if (!emacs_event)
4738     return;
4740   last_mouse_frame = emacsframe;
4741   /* appears to be needed to prevent spurious movement events generated on
4742      button clicks */
4743   last_mouse_frame->mouse_moved = 0;
4745   if ([theEvent type] == NSScrollWheel)
4746     {
4747       float delta = [theEvent deltaY];
4748       /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
4749       if (delta == 0)
4750         return;
4751       emacs_event->kind = WHEEL_EVENT;
4752       emacs_event->code = 0;
4753       emacs_event->modifiers = EV_MODIFIERS (theEvent) |
4754         ((delta > 0) ? up_modifier : down_modifier);
4755     }
4756   else
4757     {
4758       emacs_event->kind = MOUSE_CLICK_EVENT;
4759       emacs_event->code = EV_BUTTON (theEvent);
4760       emacs_event->modifiers = EV_MODIFIERS (theEvent)
4761                              | EV_UDMODIFIERS (theEvent);
4762     }
4763   XSETINT (emacs_event->x, lrint (p.x));
4764   XSETINT (emacs_event->y, lrint (p.y));
4765   EV_TRAILER (theEvent);
4769 - (void)rightMouseDown: (NSEvent *)theEvent
4771   NSTRACE (rightMouseDown);
4772   [self mouseDown: theEvent];
4776 - (void)otherMouseDown: (NSEvent *)theEvent
4778   NSTRACE (otherMouseDown);
4779   [self mouseDown: theEvent];
4783 - (void)mouseUp: (NSEvent *)theEvent
4785   NSTRACE (mouseUp);
4786   [self mouseDown: theEvent];
4790 - (void)rightMouseUp: (NSEvent *)theEvent
4792   NSTRACE (rightMouseUp);
4793   [self mouseDown: theEvent];
4797 - (void)otherMouseUp: (NSEvent *)theEvent
4799   NSTRACE (otherMouseUp);
4800   [self mouseDown: theEvent];
4804 - (void) scrollWheel: (NSEvent *)theEvent
4806   NSTRACE (scrollWheel);
4807   [self mouseDown: theEvent];
4811 /* Tell emacs the mouse has moved. */
4812 - (void)mouseMoved: (NSEvent *)e
4814   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4815   Lisp_Object frame;
4817 //  NSTRACE (mouseMoved);
4819   last_mouse_movement_time = EV_TIMESTAMP (e);
4820   last_mouse_motion_position
4821     = [self convertPoint: [e locationInWindow] fromView: nil];
4823   /* update any mouse face */
4824   if (dpyinfo->mouse_face_hidden)
4825     {
4826       dpyinfo->mouse_face_hidden = 0;
4827       clear_mouse_face (dpyinfo);
4828     }
4830   /* tooltip handling */
4831   previous_help_echo_string = help_echo_string;
4832   help_echo_string = Qnil;
4834   if (!note_mouse_movement (emacsframe, last_mouse_motion_position.x,
4835                             last_mouse_motion_position.y))
4836     help_echo_string = previous_help_echo_string;
4838   XSETFRAME (frame, emacsframe);
4839   if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
4840     {
4841       /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
4842          (note_mouse_highlight), which is called through the
4843          note_mouse_movement () call above */
4844       gen_help_event (help_echo_string, frame, help_echo_window,
4845                       help_echo_object, help_echo_pos);
4846     }
4847   else
4848     {
4849       help_echo_string = Qnil;
4850       gen_help_event (Qnil, frame, Qnil, Qnil, 0);
4851     }
4853   if (emacsframe->mouse_moved && send_appdefined)
4854     ns_send_appdefined (-1);
4858 - (void)mouseDragged: (NSEvent *)e
4860   NSTRACE (mouseDragged);
4861   [self mouseMoved: e];
4865 - (void)rightMouseDragged: (NSEvent *)e
4867   NSTRACE (rightMouseDragged);
4868   [self mouseMoved: e];
4872 - (void)otherMouseDragged: (NSEvent *)e
4874   NSTRACE (otherMouseDragged);
4875   [self mouseMoved: e];
4879 - (BOOL)windowShouldClose: (id)sender
4881   NSEvent *e =[[self window] currentEvent];
4883   NSTRACE (windowShouldClose);
4884   windowClosing = YES;
4885   if (!emacs_event)
4886     return NO;
4887   emacs_event->kind = DELETE_WINDOW_EVENT;
4888   emacs_event->modifiers = 0;
4889   emacs_event->code = 0;
4890   EV_TRAILER (e);
4891   /* Don't close this window, let this be done from lisp code.  */
4892   return NO;
4896 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
4897 /* normalize frame to gridded text size */
4899   NSTRACE (windowWillResize);
4900 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
4902   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe,
4903 #ifdef NS_IMPL_GNUSTEP
4904                                         frameSize.width + 3);
4905 #else
4906                                         frameSize.width);
4907 #endif
4908   if (cols < MINWIDTH)
4909     cols = MINWIDTH;
4910   frameSize.width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (emacsframe, cols);
4912   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, frameSize.height
4913 #ifdef NS_IMPL_GNUSTEP
4914       - FRAME_NS_TITLEBAR_HEIGHT (emacsframe) + 3
4915         - FRAME_TOOLBAR_HEIGHT (emacsframe));
4916 #else
4917       - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
4918         - FRAME_TOOLBAR_HEIGHT (emacsframe));
4919 #endif
4920   if (rows < MINHEIGHT)
4921     rows = MINHEIGHT;
4922   frameSize.height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows)
4923                        + FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
4924                        + FRAME_TOOLBAR_HEIGHT (emacsframe);
4925 #ifdef NS_IMPL_COCOA
4926   {
4927     /* this sets window title to have size in it; the wm does this under GS */
4928     NSRect r = [[self window] frame];
4929     if (r.size.height == frameSize.height && r.size.width == frameSize.width)
4930       {
4931         if (old_title != 0)
4932           {
4933             xfree (old_title);
4934             old_title = 0;
4935           }
4936       }
4937     else
4938       {
4939         char *size_title;
4940         NSWindow *window = [self window];
4941         if (old_title == 0)
4942           {
4943             const char *t = [[[self window] title] UTF8String];
4944             char *pos = strstr (t, "  â€”  ");
4945             if (pos)
4946               *pos = '\0';
4947             old_title = (char *) xmalloc (strlen (t) + 1);
4948             strcpy (old_title, t);
4949           }
4950         size_title = xmalloc (strlen (old_title) + 40);
4951         sprintf (size_title, "%s  â€”  (%d x %d)", old_title, cols, rows);
4952         [window setTitle: [NSString stringWithUTF8String: size_title]];
4953         [window display];
4954         xfree (size_title);
4955       }
4956   }
4957 #endif /* NS_IMPL_COCOA */
4958 /*fprintf (stderr,"    ...size became %.0f x %.0f  (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
4960   return frameSize;
4964 - (void)windowDidResize: (NSNotification *)notification
4966   NSWindow *theWindow = [notification object];
4968 #ifdef NS_IMPL_GNUSTEP
4969    /* in GNUstep, at least currently, it's possible to get a didResize
4970       without getting a willResize.. therefore we need to act as if we got
4971       the willResize now */
4972   NSSize sz = [theWindow frame].size;
4973   sz = [self windowWillResize: theWindow toSize: sz];
4974 #endif /* NS_IMPL_GNUSTEP */
4976   NSTRACE (windowDidResize);
4977 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
4979 #ifdef NS_IMPL_COCOA
4980   if (old_title != 0)
4981     {
4982       xfree (old_title);
4983       old_title = 0;
4984     }
4985 #endif /* NS_IMPL_COCOA */
4987   /* Avoid loop under GNUstep due to call at beginning of this function.
4988      (x_set_window_size causes a resize which causes
4989      a "windowDidResize" which calls x_set_window_size).  */
4990 #ifndef NS_IMPL_GNUSTEP
4991   if (cols > 0 && rows > 0)
4992      x_set_window_size (emacsframe, 0, cols, rows);
4993 #endif
4995   ns_send_appdefined (-1);
4999 - (void)windowDidBecomeKey: (NSNotification *)notification
5000 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5002   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5003   struct frame *old_focus = dpyinfo->x_focus_frame;
5005   NSTRACE (windowDidBecomeKey);
5007   if (emacsframe != old_focus)
5008     dpyinfo->x_focus_frame = emacsframe;
5010   ns_frame_rehighlight (emacsframe);
5012   if (emacs_event)
5013     {
5014       emacs_event->kind = FOCUS_IN_EVENT;
5015       EV_TRAILER ((id)nil);
5016     }
5020 - (void)windowDidResignKey: (NSNotification *)notification
5021 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5023   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5024   NSTRACE (windowDidResignKey);
5026   if (dpyinfo->x_focus_frame == emacsframe)
5027     dpyinfo->x_focus_frame = 0;
5029   ns_frame_rehighlight (emacsframe);
5031   /* FIXME: for some reason needed on second and subsequent clicks away
5032             from sole-frame Emacs to get hollow box to show */
5033   if (!windowClosing && [[self window] isVisible] == YES)
5034     {
5035       x_update_cursor (emacsframe, 1);
5036       x_set_frame_alpha (emacsframe);
5037     }
5039   if (emacs_event)
5040     {
5041       [self deleteWorkingText];
5042       emacs_event->kind = FOCUS_IN_EVENT;
5043       EV_TRAILER ((id)nil);
5044     }
5048 - (void)windowWillMiniaturize: sender
5050   NSTRACE (windowWillMiniaturize);
5054 - (BOOL)isFlipped
5056   return YES;
5060 - (BOOL)isOpaque
5062   return NO;
5066 - initFrameFromEmacs: (struct frame *)f
5068   NSRect r, wr;
5069   Lisp_Object tem;
5070   NSWindow *win;
5071   NSButton *toggleButton;
5072   int vbextra = NS_SCROLL_BAR_WIDTH (f);
5073   NSSize sz;
5074   NSColor *col;
5075   NSString *name;
5077   NSTRACE (initFrameFromEmacs);
5079   windowClosing = NO;
5080   processingCompose = NO;
5081   scrollbarsNeedingUpdate = 0;
5083 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
5085   r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
5086                  FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
5087   [self initWithFrame: r];
5088   [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
5090   FRAME_NS_VIEW (f) = self;
5091   emacsframe = f;
5092   old_title = 0;
5094   win = [[EmacsWindow alloc]
5095             initWithContentRect: r
5096                       styleMask: (NSResizableWindowMask |
5097                                   NSMiniaturizableWindowMask |
5098                                   NSClosableWindowMask)
5099                         backing: NSBackingStoreBuffered
5100                           defer: YES];
5102   wr = [win frame];
5103   f->border_width = wr.size.width - r.size.width;
5104   FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
5106   [win setAcceptsMouseMovedEvents: YES];
5107   [win setDelegate: self];
5108   [win useOptimizedDrawing: YES];
5110   sz.width = FRAME_COLUMN_WIDTH (f);
5111   sz.height = FRAME_LINE_HEIGHT (f);
5112   [win setResizeIncrements: sz];
5114   [[win contentView] addSubview: self];
5116   if (ns_drag_types)
5117     [self registerForDraggedTypes: ns_drag_types];
5119   tem = f->name;
5120   name = [NSString stringWithUTF8String:
5121                    NILP (tem) ? (unsigned char *)"Emacs" : SDATA (tem)];
5122   [win setTitle: name];
5124   /* toolbar support */
5125   toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
5126                          [NSString stringWithFormat: @"Emacs Frame %d",
5127                                    ns_window_num]];
5128   [win setToolbar: toolbar];
5129   [toolbar setVisible: NO];
5130 #ifdef NS_IMPL_COCOA
5131   toggleButton = [win standardWindowButton: NSWindowToolbarButton];
5132   [toggleButton setTarget: self];
5133   [toggleButton setAction: @selector (toggleToolbar: )];
5134 #endif
5135   FRAME_TOOLBAR_HEIGHT (f) = 0;
5137   tem = f->icon_name;
5138   if (!NILP (tem))
5139     [win setMiniwindowTitle:
5140            [NSString stringWithUTF8String: SDATA (tem)]];
5142   {
5143     NSScreen *screen = [win screen];
5145     if (screen != 0)
5146       [win setFrameTopLeftPoint: NSMakePoint
5147            (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
5148             IN_BOUND (-SCREENMAX,
5149                      [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
5150   }
5152   [win makeFirstResponder: self];
5154   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5155                                   (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
5156   [win setBackgroundColor: col];
5157   if ([col alphaComponent] != 1.0)
5158     [win setOpaque: NO];
5160   [self allocateGState];
5162   ns_window_num++;
5163   return self;
5167 - (void)windowDidMove: sender
5169   NSWindow *win = [self window];
5170   NSRect r = [win frame];
5171   NSScreen *screen = [win screen];
5173   NSTRACE (windowDidMove);
5175   if (!emacsframe->output_data.ns)
5176     return;
5177   if (screen != nil)
5178     {
5179       emacsframe->left_pos = r.origin.x;
5180       emacsframe->top_pos =
5181         [screen frame].size.height - (r.origin.y + r.size.height);
5182     }
5186 /* Called AFTER method below, but before our windowWillResize call there leads
5187    to windowDidResize -> x_set_window_size.  Update emacs' notion of frame
5188    location so set_window_size moves the frame. */
5189 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
5191   NSTRACE (windowShouldZoom);
5192   emacsframe->left_pos = (int)newFrame.origin.x;
5193   emacsframe->top_pos = [[sender screen] frame].size.height
5194                             - (newFrame.origin.y+newFrame.size.height);
5195   return YES;
5199 /* Override to do something slightly nonstandard, but nice.  First click on
5200    zoom button will zoom vertically.  Second will zoom completely.  Third
5201    returns to original. */
5202 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
5203                         defaultFrame:(NSRect)defaultFrame
5205   NSRect result = [sender frame];
5206   static NSRect ns_userRect = { 0, 0, 0, 0 };
5208   NSTRACE (windowWillUseStandardFrame);
5210   if (abs (defaultFrame.size.height - result.size.height)
5211       > FRAME_LINE_HEIGHT (emacsframe))
5212     {
5213       /* first click */
5214       ns_userRect = result;
5215       result.size.height = defaultFrame.size.height;
5216       result.origin.y = defaultFrame.origin.y;
5217     }
5218   else
5219     {
5220       if (abs (defaultFrame.size.width - result.size.width)
5221           > FRAME_COLUMN_WIDTH (emacsframe))
5222         result = defaultFrame;  /* second click */
5223       else
5224         result = ns_userRect.size.height ? ns_userRect : result;  /* restore */
5225     }
5227   [self windowWillResize: sender toSize: result.size];
5228   return result;
5232 - (void)windowDidDeminiaturize: sender
5234   NSTRACE (windowDidDeminiaturize);
5235   if (!emacsframe->output_data.ns)
5236     return;
5237   emacsframe->async_iconified = 0;
5238   emacsframe->async_visible   = 1;
5239   windows_or_buffers_changed++;
5241   if (emacs_event)
5242     {
5243       emacs_event->kind = ICONIFY_EVENT;
5244       EV_TRAILER ((id)nil);
5245     }
5249 - (void)windowDidExpose: sender
5251   NSTRACE (windowDidExpose);
5252   if (!emacsframe->output_data.ns)
5253     return;
5254   emacsframe->async_visible = 1;
5255   SET_FRAME_GARBAGED (emacsframe);
5257   if (send_appdefined)
5258     ns_send_appdefined (-1);
5262 - (void)windowDidMiniaturize: sender
5264   NSTRACE (windowDidMiniaturize);
5265   if (!emacsframe->output_data.ns)
5266     return;
5268   emacsframe->async_iconified = 1;
5269   emacsframe->async_visible = 0;
5271   if (emacs_event)
5272     {
5273       emacs_event->kind = ICONIFY_EVENT;
5274       EV_TRAILER ((id)nil);
5275     }
5279 - (void)mouseEntered: (NSEvent *)theEvent
5281   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5282   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5283   NSTRACE (mouseEntered);
5285   last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5289 - (void)mouseExited: (NSEvent *)theEvent
5291   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5292   NSRect r;
5293   struct ns_display_info *dpyinfo
5294     = emacsframe ? FRAME_NS_DISPLAY_INFO (emacsframe) : NULL;
5296   NSTRACE (mouseExited);
5298   if (dpyinfo || !emacsframe)
5299     return;
5301   last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5303   if (emacsframe == dpyinfo->mouse_face_mouse_frame)
5304     {
5305       clear_mouse_face (dpyinfo);
5306       dpyinfo->mouse_face_mouse_frame = 0;
5307     }
5311 - menuDown: sender
5313   NSTRACE (menuDown);
5314   if (context_menu_value == -1)
5315     context_menu_value = [sender tag];
5316   else
5317     find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
5318                                   emacsframe->menu_bar_vector,
5319                                   (void *)[sender tag]);
5320   ns_send_appdefined (-1);
5321   return self;
5325 - (EmacsToolbar *)toolbar
5327   return toolbar;
5331 /* this gets called on toolbar button click */
5332 - toolbarClicked: (id)item
5334   NSEvent *theEvent;
5335   int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
5337   NSTRACE (toolbarClicked);
5339   if (!emacs_event)
5340     return self;
5342   /* send first event (for some reason two needed) */
5343   theEvent = [[self window] currentEvent];
5344   emacs_event->kind = TOOL_BAR_EVENT;
5345   XSETFRAME (emacs_event->arg, emacsframe);
5346   EV_TRAILER (theEvent);
5348   emacs_event->kind = TOOL_BAR_EVENT;
5349 /*   XSETINT (emacs_event->code, 0); */
5350   emacs_event->arg = AREF (emacsframe->tool_bar_items,
5351                           idx + TOOL_BAR_ITEM_KEY);
5352   emacs_event->modifiers = EV_MODIFIERS (theEvent);
5353   EV_TRAILER (theEvent);
5354   return self;
5358 - toggleToolbar: (id)sender
5360   if (!emacs_event)
5361     return self;
5363   emacs_event->kind = NS_NONKEY_EVENT;
5364   emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
5365   EV_TRAILER ((id)nil);
5366   return self;
5370 - (void)drawRect: (NSRect)rect
5372   int x = NSMinX (rect), y = NSMinY (rect);
5373   int width = NSWidth (rect), height = NSHeight (rect);
5375   NSTRACE (drawRect);
5377   if (!emacsframe || !emacsframe->output_data.ns || ns_in_resize)
5378     return;
5380   ns_clear_frame_area (emacsframe, x, y, width, height);
5381   expose_frame (emacsframe, x, y, width, height);
5383   /*
5384     drawRect: may be called (at least in OS X 10.5) for invisible
5385     views as well for some reason.  Thus, do not infer visibility 
5386     here.
5388     emacsframe->async_visible = 1;
5389     emacsframe->async_iconified = 0;
5390   */
5394 /* NSDraggingDestination protocol methods.  Actually this is not really a
5395    protocol, but a category of Object.  O well...  */
5397 -(NSUInteger) draggingEntered: (id <NSDraggingInfo>) sender
5399   NSTRACE (draggingEntered);
5400   return NSDragOperationGeneric;
5404 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
5406   return YES;
5410 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
5412   id pb;
5413   int x, y;
5414   NSString *type;
5415   NSEvent *theEvent = [[self window] currentEvent];
5416   NSPoint position;
5418   NSTRACE (performDragOperation);
5420   if (!emacs_event)
5421     return;
5423   position = [self convertPoint: [sender draggingLocation] fromView: nil];
5424   x = lrint (position.x);  y = lrint (position.y);
5426   pb = [sender draggingPasteboard];
5427   type = [pb availableTypeFromArray: ns_drag_types];
5428   if (type == 0)
5429     {
5430       return NO;
5431     }
5432   else if ([type isEqualToString: NSFilenamesPboardType])
5433     {
5434       NSArray *files;
5435       NSEnumerator *fenum;
5436       NSString *file;
5438       if (!(files = [pb propertyListForType: type]))
5439         return NO;
5441       fenum = [files objectEnumerator];
5442       while ( (file = [fenum nextObject]) )
5443         {
5444           emacs_event->kind = NS_NONKEY_EVENT;
5445           emacs_event->code = KEY_NS_DRAG_FILE;
5446           XSETINT (emacs_event->x, x);
5447           XSETINT (emacs_event->y, y);
5448           ns_input_file = append2 (ns_input_file,
5449                                    build_string ([file UTF8String]));
5450           emacs_event->modifiers = EV_MODIFIERS (theEvent);
5451           EV_TRAILER (theEvent);
5452         }
5453       return YES;
5454     }
5455   else if ([type isEqualToString: NSURLPboardType])
5456     {
5457       NSString *file;
5458       NSURL *fileURL;
5460       if (!(fileURL = [NSURL URLFromPasteboard: pb]) ||
5461           [fileURL isFileURL] == NO)
5462         return NO;
5464       file = [fileURL path];
5465       emacs_event->kind = NS_NONKEY_EVENT;
5466       emacs_event->code = KEY_NS_DRAG_FILE;
5467       XSETINT (emacs_event->x, x);
5468       XSETINT (emacs_event->y, y);
5469       ns_input_file = append2 (ns_input_file, build_string ([file UTF8String]));
5470       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5471       EV_TRAILER (theEvent);
5472       return YES;
5473     }
5474   else if ([type isEqualToString: NSStringPboardType]
5475            || [type isEqualToString: NSTabularTextPboardType])
5476     {
5477       NSString *data;
5479       if (! (data = [pb stringForType: type]))
5480         return NO;
5482       emacs_event->kind = NS_NONKEY_EVENT;
5483       emacs_event->code = KEY_NS_DRAG_TEXT;
5484       XSETINT (emacs_event->x, x);
5485       XSETINT (emacs_event->y, y);
5486       ns_input_text = build_string ([data UTF8String]);
5487       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5488       EV_TRAILER (theEvent);
5489       return YES;
5490     }
5491   else if ([type isEqualToString: NSColorPboardType])
5492     {
5493       NSColor *c = [NSColor colorFromPasteboard: pb];
5494       emacs_event->kind = NS_NONKEY_EVENT;
5495       emacs_event->code = KEY_NS_DRAG_COLOR;
5496       XSETINT (emacs_event->x, x);
5497       XSETINT (emacs_event->y, y);
5498       ns_input_color = ns_color_to_lisp (c);
5499       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5500       EV_TRAILER (theEvent);
5501       return YES;
5502     }
5503   else if ([type isEqualToString: NSFontPboardType])
5504     {
5505       /* impl based on GNUstep NSTextView.m */
5506       NSData *data = [pb dataForType: NSFontPboardType];
5507       NSDictionary *dict = [NSUnarchiver unarchiveObjectWithData: data];
5508       NSFont *font = [dict objectForKey: NSFontAttributeName];
5509       char fontSize[10];
5511       if (font == nil)
5512         return NO;
5514       emacs_event->kind = NS_NONKEY_EVENT;
5515       emacs_event->code = KEY_NS_CHANGE_FONT;
5516       XSETINT (emacs_event->x, x);
5517       XSETINT (emacs_event->y, y);
5518       ns_input_font = build_string ([[font fontName] UTF8String]);
5519       snprintf (fontSize, 10, "%f", [font pointSize]);
5520       ns_input_fontsize = build_string (fontSize);
5521       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5522       EV_TRAILER (theEvent);
5523       return YES;
5524     }
5525   else
5526     {
5527       error ("Invalid data type in dragging pasteboard.");
5528       return NO;
5529     }
5533 - validRequestorForSendType: (NSString *)typeSent
5534                  returnType: (NSString *)typeReturned
5536   NSTRACE (validRequestorForSendType);
5537   if ([ns_send_types indexOfObjectIdenticalTo: typeSent] != NSNotFound &&
5538       [ns_return_types indexOfObjectIdenticalTo: typeSent] != NSNotFound)
5539     return self;
5541   return [super validRequestorForSendType: typeSent
5542                                returnType: typeReturned];
5546 /* The next two methods are part of NSServicesRequests informal protocol,
5547    supposedly called when a services menu item is chosen from this app.
5548    But this should not happen because we override the services menu with our
5549    own entries which call ns-perform-service.
5550    Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
5551    So let's at least stub them out until further investigation can be done. */
5553 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
5555   /* we could call ns_string_from_pasteboard(pboard) here but then it should
5556      be written into the buffer in place of the existing selection..
5557      ordinary service calls go through functions defined in ns-win.el */
5558   return NO;
5561 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
5563   /* supposed to write for as many of types as we are able */
5564   return NO;
5568 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
5569    (gives a miniaturized version of the window); currently we use the latter for
5570    frames whose active buffer doesn't correspond to any file
5571    (e.g., '*scratch*') */
5572 - setMiniwindowImage: (BOOL) setMini
5574   id image = [[self window] miniwindowImage];
5575   NSTRACE (setMiniwindowImage);
5577   /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
5578      about "AppleDockIconEnabled" notwithstanding, however the set message
5579      below has its effect nonetheless. */
5580   if (image != emacsframe->output_data.ns->miniimage)
5581     {
5582       if (image && [image isKindOfClass: [EmacsImage class]])
5583         [image release];
5584       [[self window] setMiniwindowImage:
5585                        setMini ? emacsframe->output_data.ns->miniimage : nil];
5586     }
5588   return self;
5592 - (void) setRows: (int) r andColumns: (int) c
5594   rows = r;
5595   cols = c;
5598 @end  /* EmacsView */
5602 /* ==========================================================================
5604     EmacsWindow implementation
5606    ========================================================================== */
5608 @implementation EmacsWindow
5610 /* called only on resize clicks by special case in EmacsApp-sendEvent */
5611 - (void)mouseDown: (NSEvent *)theEvent
5613   if (ns_in_resize)
5614     {
5615       NSSize size = [[theEvent window] frame].size;
5616       grabOffset = [theEvent locationInWindow];
5617       grabOffset.x = size.width - grabOffset.x;
5618     }
5619   else
5620     [super mouseDown: theEvent];
5624 /* stop resizing */
5625 - (void)mouseUp: (NSEvent *)theEvent
5627   if (ns_in_resize)
5628     {
5629       struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
5630       ns_in_resize = NO;
5631       ns_set_name_as_filename (f);
5632       [self display];
5633       ns_send_appdefined (-1);
5634     }
5635   else
5636     [super mouseUp: theEvent];
5640 /* send resize events */
5641 - (void)mouseDragged: (NSEvent *)theEvent
5643   if (ns_in_resize)
5644     {
5645       NSPoint p = [theEvent locationInWindow];
5646       NSSize size, vettedSize, origSize = [self frame].size;
5648       size.width = p.x + grabOffset.x;
5649       size.height = origSize.height - p.y + grabOffset.y;
5651       if (size.width == origSize.width && size.height == origSize.height)
5652         return;
5654       vettedSize = [[self delegate] windowWillResize: self toSize: size];
5655       if (vettedSize.width != size.width || vettedSize.height != size.height)
5656         {
5657           [[NSNotificationCenter defaultCenter]
5658             postNotificationName: NSWindowDidResizeNotification
5659                           object: self];
5660         }
5661     }
5662   else
5663     [super mouseDragged: theEvent];
5666 @end /* EmacsWindow */
5669 /* ==========================================================================
5671     EmacsScroller implementation
5673    ========================================================================== */
5676 @implementation EmacsScroller
5678 /* for repeat button push */
5679 #define SCROLL_BAR_FIRST_DELAY 0.5
5680 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
5682 + (CGFloat) scrollerWidth
5684   /* TODO: if we want to allow variable widths, this is the place to do it,
5685            however neither GNUstep nor Cocoa support it very well */
5686   return [NSScroller scrollerWidth];
5690 - initFrame: (NSRect )r window: (Lisp_Object)nwin
5692   NSTRACE (EmacsScroller_initFrame);
5694   r.size.width = [EmacsScroller scrollerWidth];
5695   [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
5696   [self setContinuous: YES];
5697   [self setEnabled: YES];
5699   /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
5700      locked against the top and bottom edges, and right edge on OS X, where
5701      scrollers are on right. */
5702 #ifdef NS_IMPL_GNUSTEP
5703   [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
5704 #else
5705   [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
5706 #endif
5708   win = nwin;
5709   condemned = NO;
5710   pixel_height = NSHeight (r);
5711   min_portion = 20 / pixel_height;
5713   frame = XFRAME (XWINDOW (win)->frame);
5714   if (FRAME_LIVE_P (frame))
5715     {
5716       int i;
5717       EmacsView *view = FRAME_NS_VIEW (frame);
5718       NSView *sview = [[view window] contentView];
5719       NSArray *subs = [sview subviews];
5721       /* disable optimization stopping redraw of other scrollbars */
5722       view->scrollbarsNeedingUpdate = 0;
5723       for (i =[subs count]-1; i >= 0; i--)
5724         if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
5725           view->scrollbarsNeedingUpdate++;
5726       [sview addSubview: self];
5727     }
5729 /*  [self setFrame: r]; */
5731   return self;
5735 - (void)setFrame: (NSRect)newRect
5737   NSTRACE (EmacsScroller_setFrame);
5738 /*  BLOCK_INPUT; */
5739   pixel_height = NSHeight (newRect);
5740   min_portion = 20 / pixel_height;
5741   [super setFrame: newRect];
5742   [self display];
5743 /*  UNBLOCK_INPUT; */
5747 - (void)dealloc
5749   NSTRACE (EmacsScroller_dealloc);
5750   if (!NILP (win))
5751     XWINDOW (win)->vertical_scroll_bar = Qnil;
5752   [super dealloc];
5756 - condemn
5758   NSTRACE (condemn);
5759   condemned =YES;
5760   return self;
5764 - reprieve
5766   NSTRACE (reprieve);
5767   condemned =NO;
5768   return self;
5772 - judge
5774   NSTRACE (judge);
5775   if (condemned)
5776     {
5777       BLOCK_INPUT;
5778       /* ensure other scrollbar updates after deletion */
5779       EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
5780       if (view != nil)
5781         view->scrollbarsNeedingUpdate++;
5782       [self removeFromSuperview];
5783       [self release];
5784       UNBLOCK_INPUT;
5785     }
5786   return self;
5790 - (void)resetCursorRects
5792   NSRect visible = [self visibleRect];
5793   NSTRACE (resetCursorRects);
5795   if (!NSIsEmptyRect (visible))
5796     [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
5797   [[NSCursor arrowCursor] setOnMouseEntered: YES];
5801 - (int) checkSamePosition: (int) position portion: (int) portion
5802                     whole: (int) whole
5804   return em_position ==position && em_portion ==portion && em_whole ==whole
5805     && portion != whole; /* needed for resize empty buf */
5809 - setPosition: (int)position portion: (int)portion whole: (int)whole
5811   NSTRACE (setPosition);
5813   em_position = position;
5814   em_portion = portion;
5815   em_whole = whole;
5817   if (portion >= whole)
5818     [self setFloatValue: 0.0 knobProportion: 1.0];
5819   else
5820     {
5821       float pos, por;
5822       portion = max ((float)whole*min_portion/pixel_height, portion);
5823       pos = (float)position / (whole - portion);
5824       por = (float)portion/whole;
5825       [self setFloatValue: pos knobProportion: por];
5826     }
5827   return self;
5830 /* FIXME: unused at moment (see ns_mouse_position) at the moment because
5831      drag events will go directly to the EmacsScroller.  Leaving in for now. */
5832 -(void)getMouseMotionPart: (int *)part window: (Lisp_Object *)window
5833                         x: (Lisp_Object *)x y: ( Lisp_Object *)y
5835   *part = last_hit_part;
5836   *window = win;
5837   XSETINT (*y, pixel_height);
5838   if ([self floatValue] > 0.999)
5839     XSETINT (*x, pixel_height);
5840   else
5841     XSETINT (*x, pixel_height * [self floatValue]);
5845 /* set up emacs_event */
5846 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
5848   if (!emacs_event)
5849     return;
5851   emacs_event->part = last_hit_part;
5852   emacs_event->code = 0;
5853   emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
5854   emacs_event->frame_or_window = win;
5855   emacs_event->timestamp = EV_TIMESTAMP (e);
5856   emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
5857   emacs_event->arg = Qnil;
5858   XSETINT (emacs_event->x, loc * pixel_height);
5859   XSETINT (emacs_event->y, pixel_height-20);
5861   n_emacs_events_pending++;
5862   kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
5863   EVENT_INIT (*emacs_event);
5864   ns_send_appdefined (-1);
5868 /* called manually thru timer to implement repeated button action w/hold-down */
5869 - repeatScroll: (NSTimer *)scrollEntry
5871   NSEvent *e = [[self window] currentEvent];
5872   NSPoint p =  [[self window] mouseLocationOutsideOfEventStream];
5873   BOOL inKnob = [self testPart: p] == NSScrollerKnob;
5875   /* clear timer if need be */
5876   if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
5877     {
5878         [scroll_repeat_entry invalidate];
5879         [scroll_repeat_entry release];
5880         scroll_repeat_entry = nil;
5882         if (inKnob)
5883           return self;
5885         scroll_repeat_entry
5886           = [[NSTimer scheduledTimerWithTimeInterval:
5887                         SCROLL_BAR_CONTINUOUS_DELAY
5888                                             target: self
5889                                           selector: @selector (repeatScroll:)
5890                                           userInfo: 0
5891                                            repeats: YES]
5892               retain];
5893     }
5895   [self sendScrollEventAtLoc: 0 fromEvent: e];
5896   return self;
5900 /* Asynchronous mouse tracking for scroller.  This allows us to dispatch
5901    mouseDragged events without going into a modal loop. */
5902 - (void)mouseDown: (NSEvent *)e
5904   NSRect sr, kr;
5905   /* hitPart is only updated AFTER event is passed on */
5906   NSScrollerPart part = [self testPart: [e locationInWindow]];
5907   double inc = 0.0, loc, kloc, pos;
5908   int edge = 0;
5910   NSTRACE (EmacsScroller_mouseDown);
5912   switch (part)
5913     {
5914     case NSScrollerDecrementPage:
5915         last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
5916     case NSScrollerIncrementPage:
5917         last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
5918     case NSScrollerDecrementLine:
5919       last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
5920     case NSScrollerIncrementLine:
5921       last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
5922     case NSScrollerKnob:
5923       last_hit_part = scroll_bar_handle; break;
5924     case NSScrollerKnobSlot:  /* GNUstep-only */
5925       last_hit_part = scroll_bar_move_ratio; break;
5926     default:  /* NSScrollerNoPart? */
5927       fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
5928                (long) part);
5929       return;
5930     }
5932   if (inc != 0.0)
5933     {
5934       pos = 0;      /* ignored */
5936       /* set a timer to repeat, as we can't let superclass do this modally */
5937       scroll_repeat_entry
5938         = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
5939                                             target: self
5940                                           selector: @selector (repeatScroll:)
5941                                           userInfo: 0
5942                                            repeats: YES]
5943             retain];
5944     }
5945   else
5946     {
5947       /* handle, or on GNUstep possibly slot */
5948       NSEvent *fake_event;
5950       /* compute float loc in slot and mouse offset on knob */
5951       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
5952                       toView: nil];
5953       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
5954       if (loc <= 0.0)
5955         {
5956           loc = 0.0;
5957           edge = -1;
5958         }
5959       else if (loc >= NSHeight (sr))
5960         {
5961           loc = NSHeight (sr);
5962           edge = 1;
5963         }
5965       if (edge)
5966         kloc = 0.5 * edge;
5967       else
5968         {
5969           kr = [self convertRect: [self rectForPart: NSScrollerKnob]
5970                           toView: nil];
5971           kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
5972         }
5973       last_mouse_offset = kloc;
5975       /* if knob, tell emacs a location offset by knob pos
5976          (to indicate top of handle) */
5977       if (part == NSScrollerKnob)
5978           pos = (loc - last_mouse_offset) / NSHeight (sr);
5979       else
5980         /* else this is a slot click on GNUstep: go straight there */
5981         pos = loc / NSHeight (sr);
5983       /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
5984       fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
5985                                       location: [e locationInWindow]
5986                                  modifierFlags: [e modifierFlags]
5987                                      timestamp: [e timestamp]
5988                                   windowNumber: [e windowNumber]
5989                                        context: [e context]
5990                                    eventNumber: [e eventNumber]
5991                                     clickCount: [e clickCount]
5992                                       pressure: [e pressure]];
5993       [super mouseUp: fake_event];
5994     }
5996   if (part != NSScrollerKnob)
5997     [self sendScrollEventAtLoc: pos fromEvent: e];
6001 /* Called as we manually track scroller drags, rather than superclass. */
6002 - (void)mouseDragged: (NSEvent *)e
6004     NSRect sr;
6005     double loc, pos;
6006     int edge = 0;
6008     NSTRACE (EmacsScroller_mouseDragged);
6010       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6011                       toView: nil];
6012       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6014       if (loc <= 0.0)
6015         {
6016           loc = 0.0;
6017           edge = -1;
6018         }
6019       else if (loc >= NSHeight (sr) + last_mouse_offset)
6020         {
6021           loc = NSHeight (sr) + last_mouse_offset;
6022           edge = 1;
6023         }
6025       pos = /*(edge ? loc :*/ (loc - last_mouse_offset) / NSHeight (sr);
6026       [self sendScrollEventAtLoc: pos fromEvent: e];
6030 - (void)mouseUp: (NSEvent *)e
6032   if (scroll_repeat_entry)
6033     {
6034       [scroll_repeat_entry invalidate];
6035       [scroll_repeat_entry release];
6036       scroll_repeat_entry = nil;
6037     }
6038   last_hit_part = 0;
6042 /* treat scrollwheel events in the bar as though they were in the main window */
6043 - (void) scrollWheel: (NSEvent *)theEvent
6045   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
6046   [view mouseDown: theEvent];
6049 @end  /* EmacsScroller */
6054 /* ==========================================================================
6056    Font-related functions; these used to be in nsfaces.m
6058    ========================================================================== */
6061 Lisp_Object
6062 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
6064   struct font *font = XFONT_OBJECT (font_object);
6066   if (fontset < 0)
6067     fontset = fontset_from_font (font_object);
6068   FRAME_FONTSET (f) = fontset;
6070   if (FRAME_FONT (f) == font)
6071     /* This font is already set in frame F.  There's nothing more to
6072        do.  */
6073     return font_object;
6075   FRAME_FONT (f) = font;
6077   FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
6078   FRAME_COLUMN_WIDTH (f) = font->average_width;
6079   FRAME_SPACE_WIDTH (f) = font->space_width;
6080   FRAME_LINE_HEIGHT (f) = font->height;
6082   compute_fringe_widths (f, 1);
6084   /* Compute the scroll bar width in character columns.  */
6085   if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
6086     {
6087       int wid = FRAME_COLUMN_WIDTH (f);
6088       FRAME_CONFIG_SCROLL_BAR_COLS (f)
6089         = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
6090     }
6091   else
6092     {
6093       int wid = FRAME_COLUMN_WIDTH (f);
6094       FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
6095     }
6097   /* Now make the frame display the given font.  */
6098   if (FRAME_NS_WINDOW (f) != 0)
6099         x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
6101   return font_object;
6105 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
6106 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
6107          in 1.43. */
6109 const char *
6110 ns_xlfd_to_fontname (const char *xlfd)
6111 /* --------------------------------------------------------------------------
6112     Convert an X font name (XLFD) to an NS font name.
6113     Only family is used.
6114     The string returned is temporarily allocated.
6115    -------------------------------------------------------------------------- */
6117   char *name = xmalloc (180);
6118   int i, len;
6119   const char *ret;
6121   if (!strncmp (xlfd, "--", 2))
6122     sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
6123   else
6124     sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
6126   /* stopgap for malformed XLFD input */
6127   if (strlen (name) == 0)
6128     strcpy (name, "Monaco");
6130   /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
6131      also uppercase after '-' or ' ' */
6132   name[0] = toupper (name[0]);
6133   for (len =strlen (name), i =0; i<len; i++)
6134     {
6135       if (name[i] == '$')
6136         {
6137           name[i] = '-';
6138           if (i+1<len)
6139             name[i+1] = toupper (name[i+1]);
6140         }
6141       else if (name[i] == '_')
6142         {
6143           name[i] = ' ';
6144           if (i+1<len)
6145             name[i+1] = toupper (name[i+1]);
6146         }
6147     }
6148 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name);  */
6149   ret = [[NSString stringWithUTF8String: name] UTF8String];
6150   xfree (name);
6151   return ret;
6155 void
6156 syms_of_nsterm ()
6158   NSTRACE (syms_of_nsterm);
6160   ns_antialias_threshold = 10.0;
6162   /* from 23+ we need to tell emacs what modifiers there are.. */
6163   DEFSYM (Qmodifier_value, "modifier-value");
6164   DEFSYM (Qalt, "alt");
6165   DEFSYM (Qhyper, "hyper");
6166   DEFSYM (Qmeta, "meta");
6167   DEFSYM (Qsuper, "super");
6168   DEFSYM (Qcontrol, "control");
6169   DEFSYM (Qnone, "none");
6170   Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
6171   Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
6172   Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
6173   Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
6174   Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
6176   DEFVAR_LISP ("ns-input-file", &ns_input_file,
6177               "The file specified in the last NS event.");
6178   ns_input_file =Qnil;
6180   DEFVAR_LISP ("ns-input-text", &ns_input_text,
6181               "The data received in the last NS text drag event.");
6182   ns_input_text =Qnil;
6184   DEFVAR_LISP ("ns-working-text", &ns_working_text,
6185               "String for visualizing working composition sequence.");
6186   ns_working_text =Qnil;
6188   DEFVAR_LISP ("ns-input-font", &ns_input_font,
6189               "The font specified in the last NS event.");
6190   ns_input_font =Qnil;
6192   DEFVAR_LISP ("ns-input-fontsize", &ns_input_fontsize,
6193               "The fontsize specified in the last NS event.");
6194   ns_input_fontsize =Qnil;
6196   DEFVAR_LISP ("ns-input-line", &ns_input_line,
6197                "The line specified in the last NS event.");
6198   ns_input_line =Qnil;
6200   DEFVAR_LISP ("ns-input-color", &ns_input_color,
6201                "The color specified in the last NS event.");
6202   ns_input_color =Qnil;
6204   DEFVAR_LISP ("ns-input-spi-name", &ns_input_spi_name,
6205                "The service name specified in the last NS event.");
6206   ns_input_spi_name =Qnil;
6208   DEFVAR_LISP ("ns-input-spi-arg", &ns_input_spi_arg,
6209                "The service argument specified in the last NS event.");
6210   ns_input_spi_arg =Qnil;
6212   DEFVAR_LISP ("ns-alternate-modifier", &ns_alternate_modifier,
6213                "This variable describes the behavior of the alternate or option key.\n\
6214 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6215 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6216 at all, allowing it to be used at a lower level for accented character entry.");
6217   ns_alternate_modifier = Qmeta;
6219   DEFVAR_LISP ("ns-right-alternate-modifier", &ns_right_alternate_modifier,
6220                "This variable describes the behavior of the right alternate or option key.\n\
6221 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6222 Set to left means be the same key as `ns-alternate-modifier'.\n\
6223 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6224 at all, allowing it to be used at a lower level for accented character entry.");
6225   ns_right_alternate_modifier = Qleft;
6227   DEFVAR_LISP ("ns-command-modifier", &ns_command_modifier,
6228                "This variable describes the behavior of the command key.\n\
6229 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6230   ns_command_modifier = Qsuper;
6232   DEFVAR_LISP ("ns-control-modifier", &ns_control_modifier,
6233                "This variable describes the behavior of the control key.\n\
6234 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6235   ns_control_modifier = Qcontrol;
6237   DEFVAR_LISP ("ns-function-modifier", &ns_function_modifier,
6238                "This variable describes the behavior of the function key (on laptops).\n\
6239 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6240 Set to none means that the function key is not interpreted by Emacs at all,\n\
6241 allowing it to be used at a lower level for accented character entry.");
6242   ns_function_modifier = Qnone;
6244   DEFVAR_LISP ("ns-antialias-text", &ns_antialias_text,
6245                "Non-nil (the default) means to render text antialiased. Only has an effect on OS X Panther and above.");
6246   ns_antialias_text = Qt;
6248   DEFVAR_LISP ("ns-confirm-quit", &ns_confirm_quit,
6249                "Whether to confirm application quit using dialog.");
6250   ns_confirm_quit = Qnil;
6252   staticpro (&ns_display_name_list);
6253   ns_display_name_list = Qnil;
6255   staticpro (&last_mouse_motion_frame);
6256   last_mouse_motion_frame = Qnil;
6258   /* TODO: move to common code */
6259   DEFVAR_LISP ("x-toolkit-scroll-bars", &Vx_toolkit_scroll_bars,
6260                doc: /* If not nil, Emacs uses toolkit scroll bars.  */);
6261 #ifdef USE_TOOLKIT_SCROLL_BARS
6262   Vx_toolkit_scroll_bars = Qt;
6263 #else
6264   Vx_toolkit_scroll_bars = Qnil;
6265 #endif
6267   /* these are unsupported but we need the declarations to avoid whining
6268      messages from cus-start.el */
6269   DEFVAR_BOOL ("x-use-underline-position-properties",
6270                &x_use_underline_position_properties,
6271      doc: /* NOT SUPPORTED UNDER NS.
6272 *Non-nil means make use of UNDERLINE_POSITION font properties.
6273 A value of nil means ignore them.  If you encounter fonts with bogus
6274 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
6275 to 4.1, set this to nil.
6277 NOTE: Not supported on Mac yet.  */);
6278   x_use_underline_position_properties = 0;
6280   DEFVAR_BOOL ("x-underline-at-descent-line",
6281                &x_underline_at_descent_line,
6282      doc: /* NOT SUPPORTED UNDER NS.
6283 *Non-nil means to draw the underline at the same place as the descent line.
6284 A value of nil means to draw the underline according to the value of the
6285 variable `x-use-underline-position-properties', which is usually at the
6286 baseline level.  The default value is nil.  */);
6287   x_underline_at_descent_line = 0;
6289   /* Tell emacs about this window system. */
6290   Fprovide (intern ("ns"), Qnil);
6294 // arch-tag: 6eaa8f7d-a69b-4e1c-b43d-ab31defbe0d2