* mark.texi (Mark): Clarify introduction.
[emacs.git] / src / nsterm.m
blob4a9a192835919aceaf1606e6f7af1704d7ff3b4b
1 /* NeXT/Open/GNUstep / MacOSX communication module.
2    Copyright (C) 1989, 1993, 1994, 2005, 2006, 2008, 2009
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>
38 #include "lisp.h"
39 #include "blockinput.h"
40 #include "sysselect.h"
41 #include "nsterm.h"
42 #include "systime.h"
43 #include "character.h"
44 #include "fontset.h"
45 #include "composite.h"
46 #include "ccl.h"
48 #include "termhooks.h"
49 #include "termopts.h"
50 #include "termchar.h"
52 #include "window.h"
53 #include "keyboard.h"
55 #include "font.h"
57 /* call tracing */
58 #if 0
59 int term_trace_num = 0;
60 #define NSTRACE(x)        fprintf (stderr, "%s:%d: [%d] " #x "\n",         \
61                                 __FILE__, __LINE__, ++term_trace_num)
62 #else
63 #define NSTRACE(x)
64 #endif
67 /* ==========================================================================
69     Local declarations
71    ========================================================================== */
73 /* Convert a symbol indexed with an NSxxx value to a value as defined
74    in keyboard.c (lispy_function_key). I hope this is a correct way
75    of doing things... */
76 static unsigned convert_ns_to_X_keysym[] =
78   NSHomeFunctionKey,            0x50,
79   NSLeftArrowFunctionKey,       0x51,
80   NSUpArrowFunctionKey,         0x52,
81   NSRightArrowFunctionKey,      0x53,
82   NSDownArrowFunctionKey,       0x54,
83   NSPageUpFunctionKey,          0x55,
84   NSPageDownFunctionKey,        0x56,
85   NSEndFunctionKey,             0x57,
86   NSBeginFunctionKey,           0x58,
87   NSSelectFunctionKey,          0x60,
88   NSPrintFunctionKey,           0x61,
89   NSExecuteFunctionKey,         0x62,
90   NSInsertFunctionKey,          0x63,
91   NSUndoFunctionKey,            0x65,
92   NSRedoFunctionKey,            0x66,
93   NSMenuFunctionKey,            0x67,
94   NSFindFunctionKey,            0x68,
95   NSHelpFunctionKey,            0x6A,
96   NSBreakFunctionKey,           0x6B,
98   NSF1FunctionKey,              0xBE,
99   NSF2FunctionKey,              0xBF,
100   NSF3FunctionKey,              0xC0,
101   NSF4FunctionKey,              0xC1,
102   NSF5FunctionKey,              0xC2,
103   NSF6FunctionKey,              0xC3,
104   NSF7FunctionKey,              0xC4,
105   NSF8FunctionKey,              0xC5,
106   NSF9FunctionKey,              0xC6,
107   NSF10FunctionKey,             0xC7,
108   NSF11FunctionKey,             0xC8,
109   NSF12FunctionKey,             0xC9,
110   NSF13FunctionKey,             0xCA,
111   NSF14FunctionKey,             0xCB,
112   NSF15FunctionKey,             0xCC,
113   NSF16FunctionKey,             0xCD,
114   NSF17FunctionKey,             0xCE,
115   NSF18FunctionKey,             0xCF,
116   NSF19FunctionKey,             0xD0,
117   NSF20FunctionKey,             0xD1,
118   NSF21FunctionKey,             0xD2,
119   NSF22FunctionKey,             0xD3,
120   NSF23FunctionKey,             0xD4,
121   NSF24FunctionKey,             0xD5,
123   NSBackspaceCharacter,         0x08,  /* 8: Not on some KBs. */
124   NSDeleteCharacter,            0xFF,  /* 127: Big 'delete' key upper right. */
125   NSDeleteFunctionKey,          0x9F,  /* 63272: Del forw key off main array. */
127   NSTabCharacter,               0x09,
128   0x19,                         0x09,  /* left tab->regular since pass shift */
129   NSCarriageReturnCharacter,    0x0D,
130   NSNewlineCharacter,           0x0D,
131   NSEnterCharacter,             0x8D,
133   0x1B,                         0x1B   /* escape */
137 /* Lisp communications */
138 Lisp_Object ns_input_file, ns_input_font, ns_input_fontsize, ns_input_line;
139 Lisp_Object ns_input_color, ns_input_text, ns_working_text;
140 Lisp_Object ns_input_spi_name, ns_input_spi_arg;
141 Lisp_Object Vx_toolkit_scroll_bars;
142 static Lisp_Object Qmodifier_value;
143 /* TODO: unsure why these defined in term files, anyway we need in keymap.c */
144 Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper;
145 extern Lisp_Object Qcursor_color, Qcursor_type, Qns;
148 /* Some preferences equivalent to those set by X resources under X are
149    managed through the OpenStep defaults system. We depart from X
150    behavior and refuse to read defaults when started under these
151    options. */
153 /* Set in emacs.c. */
154 char ns_no_defaults;
156 /* Specifies which emacs modifier should be generated when NS receives
157    the Alternate modifer.  May be Qnone or any of the modifier lisp symbols. */
158 Lisp_Object ns_alternate_modifier;
160 /* Specifies which emacs modifier should be generated when NS receives
161    the Command modifer.  May be any of the modifier lisp symbols. */
162 Lisp_Object ns_command_modifier;
164 /* Specifies which emacs modifier should be generated when NS receives
165    the Control modifer.  May be any of the modifier lisp symbols. */
166 Lisp_Object ns_control_modifier;
168 /* Specifies which emacs modifier should be generated when NS receives
169    the Function modifer (laptops).  May be any of the modifier lisp symbols. */
170 Lisp_Object ns_function_modifier;
172 /* Control via default 'GSFontAntiAlias' on OS X and GNUstep. */
173 Lisp_Object ns_antialias_text;
175 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
176    the maximum font size to NOT antialias.  On GNUstep there is currently
177    no way to control this behavior. */
178 float ns_antialias_threshold;
180 /* Controls use of an undocumented CG function to do Quickdraw-style font
181    smoothing (less heavy) instead of regular Quartz smoothing. */
182 Lisp_Object ns_use_qd_smoothing;
184 /* Used to pick up AppleHighlightColor on OS X */
185 Lisp_Object ns_use_system_highlight_color;
186 NSString *ns_selection_color;
188 /* Confirm on exit. */
189 Lisp_Object ns_confirm_quit;
191 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
193 /* Display variables */
194 struct ns_display_info *x_display_list; /* Chain of existing displays */
195 Lisp_Object ns_display_name_list;
196 long context_menu_value = 0;
198 /* display update */
199 NSPoint last_mouse_motion_position;
200 static NSRect last_mouse_glyph;
201 static unsigned long last_mouse_movement_time = 0;
202 static Lisp_Object last_mouse_motion_frame;
203 static EmacsScroller *last_mouse_scroll_bar = nil;
204 static struct frame *ns_updating_frame;
205 static NSView *focus_view = NULL;
206 static int ns_window_num =0;
207 static NSRect uRect;
208 static BOOL gsaved = NO;
209 BOOL ns_in_resize = NO;
210 static BOOL ns_fake_keydown = NO;
211 int ns_tmp_flags; /* FIXME */
212 struct nsfont_info *ns_tmp_font; /* FIXME */
213 /*static int debug_lock = 0; */
215 #ifdef NS_IMPL_COCOA
216 /* This undocumented Quartz function controls how fonts are anti-aliased.
217    (Found from code in Mac wxWindows impl, discovered by running `nm' on
218    the "QD" framework.)
219    Mode 0 is normal anti-aliasing, mode 1 is no anti-aliasing, and mode 2 is
220    4-bit pixel-aligned anti-aliasing (the old QuickDraw standard). */
221 extern void CGContextSetFontRenderingMode (CGContextRef cg, int v);
222 #endif
225 /* event loop */
226 static BOOL send_appdefined = YES;
227 static NSEvent *last_appdefined_event = 0;
228 static NSTimer *timed_entry = 0;
229 static NSTimer *fd_entry = nil;
230 static NSTimer *scroll_repeat_entry = nil;
231 static fd_set select_readfds, t_readfds;
232 static struct timeval select_timeout;
233 static int select_nfds;
234 static NSAutoreleasePool *outerpool;
235 static struct input_event *emacs_event = NULL;
236 static struct input_event *q_event_ptr = NULL;
237 static int n_emacs_events_pending = 0;
238 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
239   *ns_pending_service_args;
240 static BOOL inNsSelect = 0;
242 /* Convert modifiers in a NeXTSTEP event to emacs style modifiers.  */
243 #define NS_FUNCTION_KEY_MASK 0x800000
244 #define EV_MODIFIERS(e)                               \
245     ((([e modifierFlags] & NSHelpKeyMask) ?           \
246            hyper_modifier : 0)                        \
247      | (([e modifierFlags] & NSAlternateKeyMask) ?    \
248            parse_solitary_modifier (ns_alternate_modifier) : 0)   \
249      | (([e modifierFlags] & NSShiftKeyMask) ?        \
250            shift_modifier : 0)                        \
251      | (([e modifierFlags] & NSControlKeyMask) ?      \
252            parse_solitary_modifier (ns_control_modifier) : 0)     \
253      | (([e modifierFlags] & NS_FUNCTION_KEY_MASK) ?  \
254            parse_solitary_modifier (ns_function_modifier) : 0)    \
255      | (([e modifierFlags] & NSCommandKeyMask) ?      \
256            parse_solitary_modifier (ns_command_modifier):0))
258 #define EV_UDMODIFIERS(e)                                      \
259     ((([e type] == NSLeftMouseDown) ? down_modifier : 0)       \
260      | (([e type] == NSRightMouseDown) ? down_modifier : 0)    \
261      | (([e type] == NSOtherMouseDown) ? down_modifier : 0)    \
262      | (([e type] == NSLeftMouseDragged) ? down_modifier : 0)  \
263      | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
264      | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
265      | (([e type] == NSLeftMouseUp)   ? up_modifier   : 0)     \
266      | (([e type] == NSRightMouseUp)   ? up_modifier   : 0)    \
267      | (([e type] == NSOtherMouseUp)   ? up_modifier   : 0))
269 #define EV_BUTTON(e)                                                         \
270     ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 :    \
271       (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
272      [e buttonNumber] - 1)
274 /* Convert the time field to a timestamp in milliseconds. */
275 #ifdef NS_IMPL_GNUSTEP
276 /* Apple says timestamp is in seconds, but GNUstep seems to be returning msec */
277 #define EV_TIMESTAMP(e) ([e timestamp])
278 #else
279 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
280 #endif /* not gnustep */
282 /* This is a piece of code which is common to all the event handling
283    methods.  Maybe it should even be a function.  */
284 #define EV_TRAILER(e)                                         \
285   {                                                           \
286   XSETFRAME (emacs_event->frame_or_window, emacsframe);       \
287   if (e) emacs_event->timestamp = EV_TIMESTAMP (e);           \
288   n_emacs_events_pending++;                                   \
289   kbd_buffer_store_event_hold (emacs_event, q_event_ptr);     \
290   EVENT_INIT (*emacs_event);                                  \
291   ns_send_appdefined (-1);                                    \
292   }
294 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
296 /* TODO: get rid of need for these forward declarations */
297 static void ns_condemn_scroll_bars (struct frame *f);
298 static void ns_judge_scroll_bars (struct frame *f);
299 void x_set_frame_alpha (struct frame *f);
301 /* unused variables needed for compatibility reasons */
302 int x_use_underline_position_properties, x_underline_at_descent_line;
303 /* FIXME: figure out what to do with underline_minimum_offset. */
306 /* ==========================================================================
308     Utilities
310    ========================================================================== */
313 static Lisp_Object
314 append2 (Lisp_Object list, Lisp_Object item)
315 /* --------------------------------------------------------------------------
316    Utility to append to a list
317    -------------------------------------------------------------------------- */
319   Lisp_Object array[2];
320   array[0] = list;
321   array[1] = Fcons (item, Qnil);
322   return Fnconc (2, &array[0]);
326 void
327 ns_init_paths ()
328 /* --------------------------------------------------------------------------
329    Used to allow emacs to find its resources under Emacs.app
330    Called from emacs.c at startup.
331    -------------------------------------------------------------------------- */
333   NSBundle *bundle = [NSBundle mainBundle];
334   NSString *binDir = [bundle bundlePath], *resourceDir = [bundle resourcePath];
335   NSString *resourcePath, *resourcePaths;
336   NSRange range;
337   BOOL onWindows = NO; /* how do I determine this? */
338   NSString *pathSeparator = onWindows ? @";" : @":";
339   NSFileManager *fileManager = [NSFileManager defaultManager];
340   BOOL isDir;
341 /*NSLog (@"ns_init_paths: '%@'\n%@\n", [[NSBundle mainBundle] bundlePath], [[NSBundle mainBundle] resourcePath]); */
343   /* get bindir from base */
344   range = [resourceDir rangeOfString: @"Contents"];
345   if (range.location != NSNotFound)
346     {
347       binDir = [binDir stringByAppendingPathComponent: @"Contents"];
348 #ifdef NS_IMPL_COCOA
349       binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
350 #endif
351     }
353   /* the following based on Andrew Choi's init_mac_osx_environment () */
354   if (!getenv ("EMACSLOADPATH"))
355     {
356       NSArray *paths = [resourceDir stringsByAppendingPaths:
357                                   [NSArray arrayWithObjects:
358                                          @"site-lisp", @"lisp", @"leim", nil]];
359       NSEnumerator *pathEnum = [paths objectEnumerator];
360       resourcePaths = @"";
361       while (resourcePath = [pathEnum nextObject])
362         {
363           if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
364             if (isDir)
365               {
366                 if ([resourcePaths length] > 0)
367                   resourcePaths
368                     = [resourcePaths stringByAppendingString: pathSeparator];
369                 resourcePaths
370                   = [resourcePaths stringByAppendingString: resourcePath];
371               }
372         }
373       if ([resourcePaths length] > 0)
374         setenv ("EMACSLOADPATH", [resourcePaths UTF8String], 1);
375 /*NSLog (@"loadPath: '%s'\n", resourcePaths); */
376     }
378   if (!getenv ("EMACSPATH"))
379     {
380       NSArray *paths = [binDir stringsByAppendingPaths:
381                                   [NSArray arrayWithObjects: @"bin",
382                                                              @"lib-exec", nil]];
383       NSEnumerator *pathEnum = [paths objectEnumerator];
384       resourcePaths = @"";
385       while (resourcePath = [pathEnum nextObject])
386         {
387           if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
388             if (isDir)
389               {
390                 if ([resourcePaths length] > 0)
391                   resourcePaths
392                     = [resourcePaths stringByAppendingString: pathSeparator];
393                 resourcePaths
394                   = [resourcePaths stringByAppendingString: resourcePath];
395               }
396         }
397       if ([resourcePaths length] > 0)
398         setenv ("EMACSPATH", [resourcePaths UTF8String], 1);
399     }
401   resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
402   if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
403     {
404       if (isDir)
405         {
406           if (!getenv ("EMACSDATA"))
407             setenv ("EMACSDATA", [resourcePath UTF8String], 1);
408           if (!getenv ("EMACSDOC"))
409             setenv ("EMACSDOC", [resourcePath UTF8String], 1);
410         }
411     }
413   if (!getenv ("INFOPATH"))
414     {
415       resourcePath = [resourceDir stringByAppendingPathComponent: @"info"];
416       if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
417         if (isDir)
418           setenv ("INFOPATH", [resourcePath UTF8String], 1);
419     }
423 static int
424 timeval_subtract (struct timeval *result, struct timeval x, struct timeval y)
425 /* --------------------------------------------------------------------------
426    Subtract the `struct timeval' values X and Y, storing the result in RESULT.
427    Return 1 if the difference is negative, otherwise 0.
428    -------------------------------------------------------------------------- */
430   /* Perform the carry for the later subtraction by updating y.
431      This is safer because on some systems
432      the tv_sec member is unsigned.  */
433   if (x.tv_usec < y.tv_usec)
434     {
435       int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
436       y.tv_usec -= 1000000 * nsec;
437       y.tv_sec += nsec;
438     }
439   if (x.tv_usec - y.tv_usec > 1000000)
440     {
441       int nsec = (y.tv_usec - x.tv_usec) / 1000000;
442       y.tv_usec += 1000000 * nsec;
443       y.tv_sec -= nsec;
444     }
446   /* Compute the time remaining to wait.  tv_usec is certainly positive.  */
447   result->tv_sec = x.tv_sec - y.tv_sec;
448   result->tv_usec = x.tv_usec - y.tv_usec;
450   /* Return indication of whether the result should be considered negative.  */
451   return x.tv_sec < y.tv_sec;
454 static void
455 ns_timeout (int usecs)
456 /* --------------------------------------------------------------------------
457      Blocking timer utility used by ns_ring_bell
458    -------------------------------------------------------------------------- */
460   struct timeval wakeup;
462   EMACS_GET_TIME (wakeup);
464   /* Compute time to wait until, propagating carry from usecs.  */
465   wakeup.tv_usec += usecs;
466   wakeup.tv_sec += (wakeup.tv_usec / 1000000);
467   wakeup.tv_usec %= 1000000;
469   /* Keep waiting until past the time wakeup.  */
470   while (1)
471     {
472       struct timeval timeout;
474       EMACS_GET_TIME (timeout);
476       /* In effect, timeout = wakeup - timeout.
477          Break if result would be negative.  */
478       if (timeval_subtract (&timeout, wakeup, timeout))
479         break;
481       /* Try to wait that long--but we might wake up sooner.  */
482       select (0, NULL, NULL, NULL, &timeout);
483     }
487 void
488 ns_release_object (void *obj)
489 /* --------------------------------------------------------------------------
490     Release an object (callable from C)
491    -------------------------------------------------------------------------- */
493     [(id)obj release];
497 void
498 ns_retain_object (void *obj)
499 /* --------------------------------------------------------------------------
500     Retain an object (callable from C)
501    -------------------------------------------------------------------------- */
503     [(id)obj retain];
507 void *
508 ns_alloc_autorelease_pool ()
509 /* --------------------------------------------------------------------------
510      Allocate a pool for temporary objects (callable from C)
511    -------------------------------------------------------------------------- */
513   return [[NSAutoreleasePool alloc] init];
517 void
518 ns_release_autorelease_pool (void *pool)
519 /* --------------------------------------------------------------------------
520      Free a pool and temporary objects it refers to (callable from C)
521    -------------------------------------------------------------------------- */
523   ns_release_object (pool);
528 /* ==========================================================================
530     Focus (clipping) and screen update
532    ========================================================================== */
534 static NSRect
535 ns_resize_handle_rect (NSWindow *window)
537   NSRect r = [window frame];
538   r.origin.x = r.size.width - RESIZE_HANDLE_SIZE;
539   r.origin.y = 0;
540   r.size.width = r.size.height = RESIZE_HANDLE_SIZE;
541   return r;
545 static void
546 ns_update_begin (struct frame *f)
547 /* --------------------------------------------------------------------------
548    Prepare for a grouped sequence of drawing calls
549    external (RIF) call; whole frame, called before update_window_begin
550    -------------------------------------------------------------------------- */
552   NSView *view = FRAME_NS_VIEW (f);
553   NSTRACE (ns_update_begin);
555   ns_updating_frame = f;
556   [view lockFocus];
558 #ifdef NS_IMPL_GNUSTEP
559   uRect = NSMakeRect (0, 0, 0, 0);
560 #endif
564 static void
565 ns_update_window_begin (struct window *w)
566 /* --------------------------------------------------------------------------
567    Prepare for a grouped sequence of drawing calls
568    external (RIF) call; for one window, called after update_begin
569    -------------------------------------------------------------------------- */
571   struct frame *f = XFRAME (WINDOW_FRAME (w));
572   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
573   NSTRACE (ns_update_window_begin);
575   updated_window = w;
576   set_output_cursor (&w->cursor);
578   BLOCK_INPUT;
580   if (f == dpyinfo->mouse_face_mouse_frame)
581     {
582       /* Don't do highlighting for mouse motion during the update.  */
583       dpyinfo->mouse_face_defer = 1;
585         /* If the frame needs to be redrawn,
586            simply forget about any prior mouse highlighting.  */
587       if (FRAME_GARBAGED_P (f))
588         dpyinfo->mouse_face_window = Qnil;
590       /* (further code for mouse faces ifdef'd out in other terms elided) */
591     }
593   UNBLOCK_INPUT;
597 static void
598 ns_update_window_end (struct window *w, int cursor_on_p,
599                       int mouse_face_overwritten_p)
600 /* --------------------------------------------------------------------------
601    Finished a grouped sequence of drawing calls
602    external (RIF) call; for one window called before update_end
603    -------------------------------------------------------------------------- */
605   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (XFRAME (w->frame));
607   /* note: this fn is nearly identical in all terms */
608   if (!w->pseudo_window_p)
609     {
610       BLOCK_INPUT;
612       if (cursor_on_p)
613         display_and_set_cursor (w, 1,
614                                 output_cursor.hpos, output_cursor.vpos,
615                                 output_cursor.x, output_cursor.y);
617       if (draw_window_fringes (w, 1))
618         x_draw_vertical_border (w);
620       UNBLOCK_INPUT;
621     }
623   /* If a row with mouse-face was overwritten, arrange for
624      frame_up_to_date to redisplay the mouse highlight.  */
625   if (mouse_face_overwritten_p)
626     {
627       dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
628       dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
629       dpyinfo->mouse_face_window = Qnil;
630     }
632   updated_window = NULL;
633   NSTRACE (update_window_end);
637 static void
638 ns_update_end (struct frame *f)
639 /* --------------------------------------------------------------------------
640    Finished a grouped sequence of drawing calls
641    external (RIF) call; for whole frame, called after update_window_end
642    -------------------------------------------------------------------------- */
644   NSView *view = FRAME_NS_VIEW (f);
646 /*   if (f == FRAME_NS_DISPLAY_INFO (f)->mouse_face_mouse_frame) */
647     FRAME_NS_DISPLAY_INFO (f)->mouse_face_defer = 0;
649   BLOCK_INPUT;
651 #ifdef NS_IMPL_GNUSTEP
652   /* trigger flush only in the rectangle we tracked as being drawn */
653   [view unlockFocusNeedsFlush: NO];
654 /*fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", uRect.origin.x, uRect.origin.y, uRect.size.width, uRect.size.height); */
655   [view lockFocusInRect: uRect];
656 #endif
658   [view unlockFocus];
659   [[view window] flushWindow];
661   UNBLOCK_INPUT;
662   ns_updating_frame = NULL;
663   NSTRACE (ns_update_end);
667 static void
668 ns_flush (struct frame *f)
669 /* --------------------------------------------------------------------------
670    external (RIF) call
671    NS impl is no-op since currently we flush in ns_update_end and elsewhere
672    -------------------------------------------------------------------------- */
674     NSTRACE (ns_flush);
678 static void
679 ns_focus (struct frame *f, NSRect *r, int n)
680 /* --------------------------------------------------------------------------
681    Internal: Focus on given frame.  During small local updates this is used to
682      draw, however during large updates, ns_update_begin and ns_update_end are
683      called to wrap the whole thing, in which case these calls are stubbed out.
684      Except, on GNUstep, we accumulate the rectangle being drawn into, because
685      the back end won't do this automatically, and will just end up flushing
686      the entire window.
687    -------------------------------------------------------------------------- */
689 //  NSTRACE (ns_focus);
690 #ifdef NS_IMPL_GNUSTEP
691   NSRect u;
692     if (n == 2)
693       u = NSUnionRect (r[0], r[1]);
694     else if (r)
695       u = *r;
696 #endif
697 /* static int c =0;
698    fprintf (stderr, "focus: %d", c++);
699    if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
700    fprintf (stderr, "\n"); */
702   if (f != ns_updating_frame)
703     {
704       NSView *view = FRAME_NS_VIEW (f);
705       if (view != focus_view)
706         {
707           if (focus_view != NULL)
708             {
709               [focus_view unlockFocus];
710               [[focus_view window] flushWindow];
711 /*debug_lock--; */
712             }
714           if (view)
715 #ifdef NS_IMPL_GNUSTEP
716             r ? [view lockFocusInRect: u] : [view lockFocus];
717 #else
718             [view lockFocus];
719 #endif
720           focus_view = view;
721 /*if (view) debug_lock++; */
722         }
723 #ifdef NS_IMPL_GNUSTEP
724       else
725         {
726           /* more than one rect being drawn into */
727           if (view && r)
728             {
729               [view unlockFocus]; /* add prev rect to redraw list */
730               [view lockFocusInRect: u]; /* focus for draw in new rect */
731             }
732         }
733 #endif
734     }
735 #ifdef NS_IMPL_GNUSTEP
736   else
737     {
738       /* in batch mode, but in GNUstep must still track rectangles explicitly */
739       uRect = (r ? NSUnionRect (uRect, u) : [FRAME_NS_VIEW (f) visibleRect]);
740     }
741 #endif
743   /* clipping */
744   if (r)
745     {
746       [[NSGraphicsContext currentContext] saveGraphicsState];
747       if (n == 2)
748         NSRectClipList (r, 2);
749       else
750         NSRectClip (*r);
751       gsaved = YES;
752     }
756 static void
757 ns_unfocus (struct frame *f)
758 /* --------------------------------------------------------------------------
759      Internal: Remove focus on given frame
760    -------------------------------------------------------------------------- */
762 //  NSTRACE (ns_unfocus);
764   if (gsaved)
765     {
766       [[NSGraphicsContext currentContext] restoreGraphicsState];
767       gsaved = NO;
768     }
770   if (f != ns_updating_frame)
771     {
772       if (focus_view != NULL)
773         {
774           [focus_view unlockFocus];
775           [[focus_view window] flushWindow];
776           focus_view = NULL;
777 /*debug_lock--; */
778         }
779     }
783 static void
784 ns_clip_to_row (struct window *w, struct glyph_row *row, int area, BOOL gc)
785 /* --------------------------------------------------------------------------
786      Internal (but parallels other terms): Focus drawing on given row
787    -------------------------------------------------------------------------- */
789   struct frame *f = XFRAME (WINDOW_FRAME (w));
790   NSRect clip_rect;
791   int window_x, window_y, window_width;
793   window_box (w, area, &window_x, &window_y, &window_width, 0);
795   clip_rect.origin.x = window_x - FRAME_INTERNAL_BORDER_WIDTH (f);
796   clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
797   clip_rect.origin.y = max (clip_rect.origin.y, window_y);
798   clip_rect.size.width = window_width + 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
799   clip_rect.size.height = row->visible_height;
801   /* allow a full-height row at the top when requested
802      (used to draw fringe all the way through internal border area) */
803   if (gc && clip_rect.origin.y < 5)
804     {
805       clip_rect.origin.y -= FRAME_INTERNAL_BORDER_WIDTH (f);
806       clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
807     }
809   /* likewise at bottom */
810   if (gc &&
811       FRAME_PIXEL_HEIGHT (f) - (clip_rect.origin.y + clip_rect.size.height) < 5)
812     clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
814   ns_focus (f, &clip_rect, 1);
818 static void
819 ns_ring_bell ()
820 /* --------------------------------------------------------------------------
821      "Beep" routine
822    -------------------------------------------------------------------------- */
824   NSTRACE (ns_ring_bell);
825   if (visible_bell)
826     {
827       NSAutoreleasePool *pool;
828       struct frame *frame = SELECTED_FRAME ();
829       NSView *view;
831       BLOCK_INPUT;
832       pool = [[NSAutoreleasePool alloc] init];
834       view = FRAME_NS_VIEW (frame);
835       if (view != nil)
836         {
837           NSRect r, surr;
838           NSPoint dim = NSMakePoint (128, 128);
840           r = [view bounds];
841           r.origin.x += (r.size.width - dim.x) / 2;
842           r.origin.y += (r.size.height - dim.y) / 2;
843           r.size.width = dim.x;
844           r.size.height = dim.y;
845           surr = NSInsetRect (r, -2, -2);
846           ns_focus (frame, &surr, 1);
847           [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
848           [ns_lookup_indexed_color (NS_FACE_FOREGROUND
849                                       (FRAME_DEFAULT_FACE (frame)), frame) set];
850           NSRectFill (r);
851           [[view window] flushWindow];
852           ns_timeout (150000);
853           [[view window] restoreCachedImage];
854           [[view window] flushWindow];
855           ns_unfocus (frame);
856         }
857       [pool release];
858       UNBLOCK_INPUT;
859     }
860   else
861     {
862       NSBeep ();
863     }
867 static void
868 ns_reset_terminal_modes (struct terminal *terminal)
869 /*  Externally called as hook */
871   NSTRACE (ns_reset_terminal_modes);
874 static void
875 ns_set_terminal_modes (struct terminal *terminal)
876 /*  Externally called as hook */
878   NSTRACE (ns_set_terminal_modes);
883 /* ==========================================================================
885     Frame / window manager related functions
887    ========================================================================== */
890 static void
891 ns_raise_frame (struct frame *f)
892 /* --------------------------------------------------------------------------
893      Bring window to foreground and make it active
894    -------------------------------------------------------------------------- */
896   NSView *view = FRAME_NS_VIEW (f);
897   check_ns ();
898   BLOCK_INPUT;
899   FRAME_SAMPLE_VISIBILITY (f);
900   if (FRAME_VISIBLE_P (f))
901     {
902       [[view window] makeKeyAndOrderFront: NSApp];
903     }
904   UNBLOCK_INPUT;
908 static void
909 ns_lower_frame (struct frame *f)
910 /* --------------------------------------------------------------------------
911      Send window to back
912    -------------------------------------------------------------------------- */
914   NSView *view = FRAME_NS_VIEW (f);
915   check_ns ();
916   BLOCK_INPUT;
917   [[view window] orderBack: NSApp];
918   UNBLOCK_INPUT;
922 static void
923 ns_frame_raise_lower (struct frame *f, int raise)
924 /* --------------------------------------------------------------------------
925      External (hook)
926    -------------------------------------------------------------------------- */
928   NSTRACE (ns_frame_raise_lower);
930   if (raise)
931     ns_raise_frame (f);
932   else
933     ns_lower_frame (f);
937 static void
938 ns_frame_rehighlight (struct frame *frame)
939 /* --------------------------------------------------------------------------
940      External (hook): called on things like window switching within frame
941    -------------------------------------------------------------------------- */
943   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
944   struct frame *old_highlight = dpyinfo->x_highlight_frame;
946   NSTRACE (ns_frame_rehighlight);
947   if (dpyinfo->x_focus_frame)
948     {
949       dpyinfo->x_highlight_frame
950         = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
951            ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
952            : dpyinfo->x_focus_frame);
953       if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
954         {
955           FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
956           dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
957         }
958     }
959   else
960       dpyinfo->x_highlight_frame = 0;
962   if (dpyinfo->x_highlight_frame &&
963          dpyinfo->x_highlight_frame != old_highlight)
964     {
965       if (old_highlight)
966         {
967           x_update_cursor (old_highlight, 1);
968           x_set_frame_alpha (old_highlight);
969         }
970       if (dpyinfo->x_highlight_frame)
971         {
972           x_update_cursor (dpyinfo->x_highlight_frame, 1);
973           x_set_frame_alpha (dpyinfo->x_highlight_frame);
974         }
975     }
979 void
980 x_make_frame_visible (struct frame *f)
981 /* --------------------------------------------------------------------------
982      External: Show the window (X11 semantics)
983    -------------------------------------------------------------------------- */
985   NSTRACE (x_make_frame_visible);
986   /* XXX: at some points in past this was not needed, as the only place that
987      called this (frame.c:Fraise_frame ()) also called raise_lower;
988      if this ends up the case again, comment this out again. */
989   if (!FRAME_VISIBLE_P (f))
990     {
991       f->async_visible = 1;
992       ns_raise_frame (f);
993     }
997 void
998 x_make_frame_invisible (struct frame *f)
999 /* --------------------------------------------------------------------------
1000      External: Hide the window (X11 semantics)
1001    -------------------------------------------------------------------------- */
1003   NSView * view = FRAME_NS_VIEW (f);
1004   NSTRACE (x_make_frame_invisible);
1005   check_ns ();
1006   [[view window] orderOut: NSApp];
1007   f->async_visible = 0;
1008   f->async_iconified = 0;
1012 void
1013 x_iconify_frame (struct frame *f)
1014 /* --------------------------------------------------------------------------
1015      External: Iconify window
1016    -------------------------------------------------------------------------- */
1018   NSView * view = FRAME_NS_VIEW (f);
1019   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1020   NSTRACE (x_iconify_frame);
1021   check_ns ();
1023   if (dpyinfo->x_highlight_frame == f)
1024     dpyinfo->x_highlight_frame = 0;
1026   if ([[view window] windowNumber] <= 0)
1027     {
1028       /* the window is still deferred.  Make it very small, bring it
1029          on screen and order it out. */
1030       NSRect s = { { 100, 100}, {0, 0} };
1031       NSRect t;
1032       t = [[view window] frame];
1033       [[view window] setFrame: s display: NO];
1034       [[view window] orderBack: NSApp];
1035       [[view window] orderOut: NSApp];
1036       [[view window] setFrame: t display: NO];
1037     }
1038   [[view window] miniaturize: NSApp];
1042 void
1043 x_destroy_window (struct frame *f)
1044 /* --------------------------------------------------------------------------
1045      External: Delete the window
1046    -------------------------------------------------------------------------- */
1048   NSView *view = FRAME_NS_VIEW (f);
1049   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1050   NSTRACE (x_destroy_window);
1051   check_ns ();
1053   [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1055   BLOCK_INPUT;
1057   free_frame_menubar (f);
1059   if (FRAME_FACE_CACHE (f))
1060     free_frame_faces (f);
1062   if (f == dpyinfo->x_focus_frame)
1063     dpyinfo->x_focus_frame = 0;
1064   if (f == dpyinfo->x_highlight_frame)
1065     dpyinfo->x_highlight_frame = 0;
1066   if (f == dpyinfo->mouse_face_mouse_frame)
1067     {
1068       dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
1069       dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
1070       dpyinfo->mouse_face_window = Qnil;
1071       dpyinfo->mouse_face_deferred_gc = 0;
1072       dpyinfo->mouse_face_mouse_frame = 0;
1073     }
1075   xfree (f->output_data.ns);
1077   [[view window] close];
1078   [view release];
1080   ns_window_num--;
1081   UNBLOCK_INPUT;
1085 void
1086 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1087 /* --------------------------------------------------------------------------
1088      External: Position the window
1089    -------------------------------------------------------------------------- */
1091   NSScreen *screen;
1092   NSView *view = FRAME_NS_VIEW (f);
1094   NSTRACE (x_set_offset);
1096   BLOCK_INPUT;
1098   f->left_pos = xoff;
1099   f->top_pos = yoff;
1100 #ifdef NS_IMPL_GNUSTEP
1101   if (xoff < 100)
1102     f->left_pos = 100;  /* don't overlap menu */
1103 #endif
1104   if (view != nil && (screen = [[view window] screen]))
1105     [[view window] setFrameTopLeftPoint:
1106         NSMakePoint (SCREENMAXBOUND (f->left_pos),
1107                      SCREENMAXBOUND ([screen frame].size.height
1108                                      - NS_TOP_POS (f)))];
1109   UNBLOCK_INPUT;
1113 void
1114 x_set_window_size (struct frame *f, int change_grav, int cols, int rows)
1115 /* --------------------------------------------------------------------------
1116      Adjust window pixel size based on given character grid size
1117      Impl is a bit more complex than other terms, need to do some
1118      internal clipping and also pay attention to screen constraints.
1119    -------------------------------------------------------------------------- */
1121   EmacsView *view = FRAME_NS_VIEW (f);
1122   EmacsToolbar *toolbar = [view toolbar];
1123   NSWindow *window = [view window];
1124   NSScreen *screen = [window screen];
1125   NSRect wr = [window frame];
1126   int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1127   int pixelwidth, pixelheight;
1128   static int oldRows, oldCols, oldFontWidth, oldFontHeight;
1129   static int oldTB;
1130   static struct frame *oldF;
1132   NSTRACE (x_set_window_size);
1134   if (view == nil ||
1135       (f == oldF
1136        && rows == oldRows && cols == oldCols
1137        && oldFontWidth == FRAME_COLUMN_WIDTH (f)
1138        && oldFontHeight == FRAME_LINE_HEIGHT (f)
1139        && oldTB == tb))
1140     return;
1142 /*fprintf (stderr, "\tsetWindowSize: %d x %d, font size %d x %d\n", cols, rows, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f)); */
1144   BLOCK_INPUT;
1146   check_frame_size (f, &rows, &cols);
1147   oldF = f;
1148   oldRows = rows;
1149   oldCols = cols;
1150   oldFontWidth = FRAME_COLUMN_WIDTH (f);
1151   oldFontHeight = FRAME_LINE_HEIGHT (f);
1152   oldTB = tb;
1154   f->scroll_bar_actual_width = NS_SCROLL_BAR_WIDTH (f);
1155   compute_fringe_widths (f, 0);
1157   pixelwidth =  FRAME_TEXT_COLS_TO_PIXEL_WIDTH   (f, cols);
1158   pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
1160   /* If we have a toolbar, take its height into account. */
1161   if (tb)
1162     FRAME_NS_TOOLBAR_HEIGHT (f) =
1163       /* XXX: GNUstep has not yet implemented the first method below, added
1164          in Panther, however the second is incorrect under Cocoa. */
1165 #ifdef NS_IMPL_COCOA
1166       NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1167       /* NOTE: previously this would generate wrong result if toolbar not
1168                yet displayed and fixing toolbar_height=32 helped, but
1169                now (200903) seems no longer needed */
1170 #else
1171       NSHeight ([NSWindow frameRectForContentRect: NSMakeRect (0, 0, 0, 0)
1172                                         styleMask: [window styleMask]])
1173 #endif
1174             - FRAME_NS_TITLEBAR_HEIGHT (f);
1175   else
1176     FRAME_NS_TOOLBAR_HEIGHT (f) = 0;
1178   wr.size.width = pixelwidth + f->border_width;
1179   wr.size.height = pixelheight + FRAME_NS_TITLEBAR_HEIGHT (f) 
1180                   + FRAME_NS_TOOLBAR_HEIGHT (f);
1182   /* constrain to screen if we can */
1183   if (screen)
1184     {
1185       NSSize sz = [screen visibleFrame].size;
1186       NSSize ez = { wr.size.width - sz.width, wr.size.height - sz.height };
1187       if (ez.width > 0)
1188         {
1189           int cr = ez.width / FRAME_COLUMN_WIDTH (f) + 1;
1190           cols -= cr;
1191           oldCols = cols;
1192           wr.size.width -= cr * FRAME_COLUMN_WIDTH (f);
1193           pixelwidth -= cr * FRAME_COLUMN_WIDTH (f);
1194         }
1195       if (ez.height > 0)
1196         {
1197           int rr = ez.height / FRAME_LINE_HEIGHT (f) + 1;
1198           rows -= rr;
1199           oldRows = rows;
1200           wr.size.height -= rr * FRAME_LINE_HEIGHT (f);
1201           pixelheight -= rr * FRAME_LINE_HEIGHT (f);
1202         }
1203       wr.origin.x = f->left_pos;
1204       wr.origin.y = [screen frame].size.height - NS_TOP_POS (f)
1205         - wr.size.height;
1206     }
1208   [view setRows: rows andColumns: cols];
1209   [window setFrame: wr display: YES];
1211 /*fprintf (stderr, "\tx_set_window_size %d, %d\t%d, %d\n", cols, rows, pixelwidth, pixelheight); */
1213   /* This is a trick to compensate for Emacs' managing the scrollbar area
1214      as a fixed number of standard character columns.  Instead of leaving
1215      blank space for the extra, we chopped it off above.  Now for
1216      left-hand scrollbars, we shift all rendering to the left by the
1217      difference between the real width and Emacs' imagined one.  For
1218      right-hand bars, don't worry about it since the extra is never used.
1219      (Obviously doesn't work for vertically split windows tho..) */
1220   NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1221     ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1222                   - NS_SCROLL_BAR_WIDTH (f), 0)
1223     : NSMakePoint (0, 0);
1224   [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1225   [view setBoundsOrigin: origin];
1227   change_frame_size (f, rows, cols, 0, 1, 0); /* pretend, delay, safe */
1228   FRAME_PIXEL_WIDTH (f) = pixelwidth;
1229   FRAME_PIXEL_HEIGHT (f) = pixelheight;
1230 /*  SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */
1232   mark_window_cursors_off (XWINDOW (f->root_window));
1233   cancel_mouse_face (f);
1235   UNBLOCK_INPUT;
1240 /* ==========================================================================
1242     Color management
1244    ========================================================================== */
1247 NSColor *
1248 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1250   struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1251   return color_table->colors[idx];
1255 unsigned long
1256 ns_index_color (NSColor *color, struct frame *f)
1258   struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1259   int idx;
1260   NSNumber *index;
1262   if (!color_table->colors)
1263     {
1264       color_table->size = NS_COLOR_CAPACITY;
1265       color_table->avail = 1; /* skip idx=0 as marker */
1266       color_table->colors
1267         = (NSColor **)xmalloc (color_table->size * sizeof (NSColor *));
1268       color_table->empty_indices = [[NSMutableSet alloc] init];
1269     }
1271   /* do we already have this color ? */
1272   {
1273     int i;
1274     for (i = 1; i < color_table->avail; i++)
1275       {
1276         if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1277           {
1278             [color_table->colors[i] retain];
1279             return i;
1280           }
1281       }
1282   }
1284   if ([color_table->empty_indices count] > 0)
1285     {
1286       index = [color_table->empty_indices anyObject];
1287       [color_table->empty_indices removeObject: index];
1288       idx = [index unsignedIntValue];
1289     }
1290   else
1291     {
1292       if (color_table->avail == color_table->size)
1293         {
1294           color_table->size += NS_COLOR_CAPACITY;
1295           color_table->colors
1296             = (NSColor **)xrealloc (color_table->colors,
1297                                     color_table->size * sizeof (NSColor *));
1298         }
1299       idx = color_table->avail++;
1300     }
1302   color_table->colors[idx] = color;
1303   [color retain];
1304 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1305   return idx;
1309 void
1310 ns_free_indexed_color (unsigned long idx, struct frame *f)
1312   struct ns_color_table *color_table;
1313   NSColor *color;
1314   NSNumber *index;
1316   if (!f)
1317     return;
1319   color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1321   if (idx <= 0 || idx >= color_table->size) {
1322     message1("ns_free_indexed_color: Color index out of range.\n");
1323     return;
1324   }
1326   index = [NSNumber numberWithUnsignedInt: idx];
1327   if ([color_table->empty_indices containsObject: index]) {
1328     message1("ns_free_indexed_color: attempt to free already freed color.\n");
1329     return;
1330   }
1332   color = color_table->colors[idx];
1333   [color release];
1334   color_table->colors[idx] = nil;
1335   [color_table->empty_indices addObject: [NSNumber numberWithUnsignedInt: idx]];
1336 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1340 static int
1341 ns_get_color (const char *name, NSColor **col)
1342 /* --------------------------------------------------------------------------
1343      Parse a color name
1344 /* --------------------------------------------------------------------------
1345 /* On *Step, we recognize several color formats, in addition to a catalog
1346    of colors found in the file Emacs.clr. Color formats include:
1347    - #rrggbb or RGBrrggbb where rr, gg, bb specify red, green and blue in hex
1348    - ARGBaarrggbb is similar, with aa being the alpha channel (FF = opaque)
1349    - HSVhhssvv and AHSVaahhssvv (or HSB/AHSB) are similar for hue, saturation,
1350      value;
1351    - CMYKccmmyykk is similar for cyan, magenta, yellow, black. */
1353   NSColor * new = nil;
1354   const char *hex = NULL;
1355   enum { rgb, argb, hsv, ahsv, cmyk, gray } color_space;
1356   NSString *nsname = [NSString stringWithUTF8String: name];
1358 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1359   BLOCK_INPUT;
1361   if ([nsname isEqualToString: @"ns_selection_color"])
1362     {
1363       nsname = ns_selection_color;
1364       name = [ns_selection_color UTF8String];
1365     }
1367   if (name[0] == '0' || name[0] == '1' || name[0] == '.')
1368     {
1369       /* RGB decimal */
1370       NSScanner *scanner = [NSScanner scannerWithString: nsname];
1371       float r, g, b;
1372       [scanner scanFloat: &r];
1373       [scanner scanFloat: &g];
1374       [scanner scanFloat: &b];
1375       *col = [NSColor colorWithCalibratedRed: r green: g blue: b alpha: 1.0];
1376       UNBLOCK_INPUT;
1377       return 0;
1378     }
1380   /*  FIXME: emacs seems to downcase everything before passing it here,
1381         which we can work around, except for GRAY, since gray##, where ## is
1382         decimal between 0 and 99, is also an X11 colorname. */
1383   if (name[0] == '#')             /* X11 format */
1384     {
1385       hex = name + 1;
1386       color_space = rgb;
1387     }
1388   else if (!memcmp (name, "RGB", 3) || !memcmp (name, "rgb", 3))
1389     {
1390       hex = name + 3;
1391       color_space = rgb;
1392     }
1393   else if (!memcmp (name, "ARGB", 4) || !memcmp (name, "argb", 4))
1394     {
1395       hex = name + 4;
1396       color_space = argb;
1397     }
1398   else if (!memcmp (name, "HSV", 3) || !memcmp (name, "hsv", 3) || 
1399            !memcmp (name, "HSB", 3) || !memcmp (name, "hsb", 3))
1400     {
1401       hex = name + 3;
1402       color_space = hsv;
1403     }
1404   else if (!memcmp (name, "AHSV", 4) || !memcmp (name, "ahsv", 4) ||
1405            !memcmp (name, "AHSB", 4) || !memcmp (name, "ahsb", 4))
1406     {
1407       hex = name + 4;
1408       color_space = ahsv;
1409     }
1410   else if (!memcmp (name, "CMYK", 4) || !memcmp (name, "cmyk", 4))
1411     {
1412       hex = name + 4;
1413       color_space = cmyk;
1414     }
1415   else if (!memcmp (name, "GRAY", 4) /*|| !memcmp (name, "gray", 4)*/)
1416     {
1417       hex = name + 4;
1418       color_space = gray;
1419     }
1421   /* Direct colors (hex values) */
1422   if (hex)
1423     {
1424       unsigned long long color = 0;
1425       if (sscanf (hex, "%x", &color))
1426         {
1427           float f1, f2, f3, f4;
1428           /* Assume it's either 1 byte or 2 per channel... */
1429           if (strlen(hex) > 8) {
1430             f1 = ((color >> 48) & 0xffff) / 65535.0;
1431             f2 = ((color >> 32) & 0xffff) / 65535.0;
1432             f3 = ((color >> 16) & 0xffff) / 65535.0;
1433             f4 = ((color      ) & 0xffff) / 65535.0;
1434           } else {
1435             f1 = ((color >> 24) & 0xff) / 255.0;
1436             f2 = ((color >> 16) & 0xff) / 255.0;
1437             f3 = ((color >>  8) & 0xff) / 255.0;
1438             f4 = ((color      ) & 0xff) / 255.0;
1439           }
1441           switch (color_space)
1442             {
1443             case rgb:
1444               *col = [NSColor colorWithCalibratedRed: f2
1445                                                green: f3
1446                                                 blue: f4
1447                                                alpha: 1.0];
1448               break;
1449             case argb:
1450               *col = [NSColor colorWithCalibratedRed: f2
1451                                                green: f3
1452                                                 blue: f4
1453                                                alpha: f1];
1454               break;
1455             case hsv:
1456               *col = [NSColor colorWithCalibratedHue: f2
1457                                           saturation: f3
1458                                           brightness: f4
1459                                                alpha: 1.0];
1460               break;
1461             case ahsv:
1462               *col = [NSColor colorWithCalibratedHue: f2
1463                                           saturation: f3
1464                                           brightness: f4
1465                                                alpha: f1];
1466               break;
1467             case gray:
1468               *col = [NSColor colorWithCalibratedWhite: f3 alpha: f4];
1469               break;
1470             case cmyk:
1471               *col = [NSColor colorWithDeviceCyan: f1
1472                                           magenta: f2
1473                                            yellow: f3
1474                                             black: f4
1475                                             alpha: 1.0];
1476               break;
1477             }
1478           *col = [*col colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1479           UNBLOCK_INPUT;
1480           return 0;
1481         }
1482     }
1484   /* Otherwise, color is expected to be from a list */
1485   {
1486     NSEnumerator *lenum, *cenum;
1487     NSString *name;
1488     NSColorList *clist;
1490 #ifdef NS_IMPL_GNUSTEP
1491     /* XXX: who is wrong, the requestor or the implementation? */
1492     if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1493         == NSOrderedSame)
1494       nsname = @"highlightColor";
1495 #endif
1497     lenum = [[NSColorList availableColorLists] objectEnumerator];
1498     while ( (clist = [lenum nextObject]) && new == nil)
1499       {
1500         cenum = [[clist allKeys] objectEnumerator];
1501         while ( (name = [cenum nextObject]) && new == nil )
1502           {
1503             if ([name compare: nsname
1504                       options: NSCaseInsensitiveSearch] == NSOrderedSame )
1505               new = [clist colorWithKey: name];
1506           }
1507       }
1508   }
1510   if ( new )
1511     *col = [new colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1512 /*     else
1513        NSLog (@"Failed to find color '%@'", nsname); */
1514   UNBLOCK_INPUT;
1515   return new ? 0 : 1;
1519 static NSColor *
1520 ns_get_color_default (const char *name, NSColor *dflt)
1521 /* --------------------------------------------------------------------------
1522      Parse a color or use a default value
1523    -------------------------------------------------------------------------- */
1525   NSColor * col;
1527   if (ns_get_color (name, &col))
1528     return dflt;
1529   else
1530     return col;
1535 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1536 /* --------------------------------------------------------------------------
1537      Convert a Lisp string object to a NS color
1538    -------------------------------------------------------------------------- */
1540   NSTRACE (ns_lisp_to_color);
1541   if (STRINGP (color))
1542     return ns_get_color (SDATA (color), col);
1543   else if (SYMBOLP (color))
1544     return ns_get_color (SDATA (SYMBOL_NAME (color)), col);
1545   return 1;
1549 Lisp_Object
1550 ns_color_to_lisp (NSColor *col)
1551 /* --------------------------------------------------------------------------
1552      Convert a color to a lisp string with the RGB equivalent
1553    -------------------------------------------------------------------------- */
1555   float red, green, blue, alpha, gray;
1556   char buf[1024];
1557   const char *str;
1558   NSTRACE (ns_color_to_lisp);
1560   BLOCK_INPUT;
1561   if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1563       if ((str =[[col colorNameComponent] UTF8String]))
1564         {
1565           UNBLOCK_INPUT;
1566           return build_string ((char *)str);
1567         }
1569     [[col colorUsingColorSpaceName: NSCalibratedRGBColorSpace]
1570         getRed: &red green: &green blue: &blue alpha: &alpha];
1571   if (red ==green && red ==blue)
1572     {
1573       [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1574             getWhite: &gray alpha: &alpha];
1575       snprintf (buf, sizeof (buf), "GRAY%02.2lx%02.2lx",
1576                lrint (gray * 0xff), lrint (alpha * 0xff));
1577       UNBLOCK_INPUT;
1578       return build_string (buf);
1579     }
1581   snprintf (buf, sizeof (buf), "ARGB%02.2lx%02.2lx%02.2lx%02.2lx",
1582             lrint (alpha*0xff),
1583             lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1585   UNBLOCK_INPUT;
1586   return build_string (buf);
1590 void
1591 ns_query_color(void *col, XColor *color_def, int setPixel)
1592 /* --------------------------------------------------------------------------
1593          Get ARGB values out of NSColor col and put them into color_def.
1594          If setPixel, set the pixel to a concatenated version.
1595          and set color_def pixel to the resulting index.
1596    -------------------------------------------------------------------------- */
1598   float r, g, b, a;
1600   [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1601   color_def->red   = r * 65535;
1602   color_def->green = g * 65535;
1603   color_def->blue  = b * 65535;
1605   if (setPixel == YES)
1606     color_def->pixel
1607       = ARGB_TO_ULONG((int)(a*255),
1608                       (int)(r*255), (int)(g*255), (int)(b*255));
1613 ns_defined_color (struct frame *f, char *name, XColor *color_def, int alloc,
1614                   char makeIndex)
1615 /* --------------------------------------------------------------------------
1616          Return 1 if named color found, and set color_def rgb accordingly.
1617          If makeIndex and alloc are nonzero put the color in the color_table,
1618          and set color_def pixel to the resulting index.
1619          If makeIndex is zero, set color_def pixel to ARGB.
1620          Return 0 if not found
1621    -------------------------------------------------------------------------- */
1623   NSColor *temp;
1624   int notFound = ns_get_color (name, &temp);
1626   NSTRACE (ns_defined_color);
1628   if (notFound)
1629     return 0;
1631   if (makeIndex && alloc)
1632       color_def->pixel = ns_index_color(temp, f); /* [temp retain]; */
1634   ns_query_color (temp, color_def, !makeIndex);
1636   return 1;
1640 unsigned long
1641 ns_get_rgb_color (struct frame *f, float r, float g, float b, float a)
1642 /* --------------------------------------------------------------------------
1643     return an autoreleased RGB color
1644    -------------------------------------------------------------------------- */
1646 /*static int c = 1; fprintf (stderr, "color request %d\n", c++); */
1647   if (r < 0.0) r = 0.0;
1648   else if (r > 1.0) r = 1.0;
1649   if (g < 0.0) g = 0.0;
1650   else if (g > 1.0) g = 1.0;
1651   if (b < 0.0) b = 0.0;
1652   else if (b > 1.0) b = 1.0;
1653   if (a < 0.0) a = 0.0;
1654   else if (a > 1.0) a = 1.0;
1655   return (unsigned long) ns_index_color(
1656     [NSColor colorWithCalibratedRed: r green: g blue: b alpha: a], f);
1660 void
1661 x_set_frame_alpha (struct frame *f)
1662 /* --------------------------------------------------------------------------
1663      change the entire-frame transparency
1664    -------------------------------------------------------------------------- */
1666   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1667   EmacsView *view = FRAME_NS_VIEW (f);
1668   double alpha = 1.0;
1669   double alpha_min = 1.0;
1671   if (dpyinfo->x_highlight_frame == f)
1672     alpha = f->alpha[0];
1673   else
1674     alpha = f->alpha[1];
1676   if (FLOATP (Vframe_alpha_lower_limit))
1677     alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1678   else if (INTEGERP (Vframe_alpha_lower_limit))
1679     alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1681   if (alpha < 0.0)
1682     return;
1683   else if (1.0 < alpha)
1684     alpha = 1.0;
1685   else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1686     alpha = alpha_min;
1688 #ifdef NS_IMPL_COCOA
1689   [[view window] setAlphaValue: alpha];
1690 #endif
1694 /* ==========================================================================
1696     Mouse handling
1698    ========================================================================== */
1701 void
1702 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1703 /* --------------------------------------------------------------------------
1704      Programmatically reposition mouse pointer in pixel coordinates
1705    -------------------------------------------------------------------------- */
1707   NSTRACE (x_set_mouse_pixel_position);
1708   ns_raise_frame (f);
1709 #if 0
1710   /* FIXME: this does not work, and what about GNUstep? */
1711 #ifdef NS_IMPL_COCOA
1712   [FRAME_NS_VIEW (f) lockFocus];
1713   PSsetmouse ((float)pix_x, (float)pix_y);
1714   [FRAME_NS_VIEW (f) unlockFocus];
1715 #endif
1716 #endif
1720 void
1721 x_set_mouse_position (struct frame *f, int h, int v)
1722 /* --------------------------------------------------------------------------
1723      Programmatically reposition mouse pointer in character coordinates
1724    -------------------------------------------------------------------------- */
1726   int pix_x, pix_y;
1728   pix_x = FRAME_COL_TO_PIXEL_X (f, h) + FRAME_COLUMN_WIDTH (f) / 2;
1729   pix_y = FRAME_LINE_TO_PIXEL_Y (f, v) + FRAME_LINE_HEIGHT (f) / 2;
1731   if (pix_x < 0) pix_x = 0;
1732   if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
1734   if (pix_y < 0) pix_y = 0;
1735   if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
1737   x_set_mouse_pixel_position (f, pix_x, pix_y);
1741 static int
1742 note_mouse_movement (struct frame *frame, float x, float y)
1743 /*   ------------------------------------------------------------------------
1744      Called by EmacsView on mouseMovement events.  Passes on
1745      to emacs mainstream code if we moved off of a rect of interest
1746      known as last_mouse_glyph.
1747      ------------------------------------------------------------------------ */
1749 //  NSTRACE (note_mouse_movement);
1751   XSETFRAME (last_mouse_motion_frame, frame);
1753   /* Note, this doesn't get called for enter/leave, since we don't have a
1754      position.  Those are taken care of in the corresponding NSView methods. */
1756   /* has movement gone beyond last rect we were tracking? */
1757   if (x < last_mouse_glyph.origin.x ||
1758       x >= (last_mouse_glyph.origin.x + last_mouse_glyph.size.width) ||
1759       y < last_mouse_glyph.origin.y ||
1760       y >= (last_mouse_glyph.origin.y + last_mouse_glyph.size.height))
1761     {
1762       ns_update_begin(frame);
1763       frame->mouse_moved = 1;
1764       note_mouse_highlight (frame, x, y);
1765       remember_mouse_glyph (frame, x, y, &last_mouse_glyph);
1766       ns_update_end(frame);
1767       return 1;
1768     }
1770   return 0;
1774 static void
1775 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1776                    enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1777                    unsigned long *time)
1778 /* --------------------------------------------------------------------------
1779     External (hook): inform emacs about mouse position and hit parts.
1780     If a scrollbar is being dragged, set bar_window, part, x, y, time.
1781     x & y should be position in the scrollbar (the whole bar, not the handle)
1782     and length of scrollbar respectively
1783    -------------------------------------------------------------------------- */
1785   id view;
1786   NSPoint position;
1787   int xchar, ychar;
1788   Lisp_Object frame, tail;
1789   struct frame *f;
1790   struct ns_display_info *dpyinfo;
1792   NSTRACE (ns_mouse_position);
1794   if (*fp == NULL)
1795     {
1796       fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1797       return;
1798     }
1800   dpyinfo = FRAME_NS_DISPLAY_INFO (*fp);
1802   BLOCK_INPUT;
1804   if (last_mouse_scroll_bar != nil && insist == 0)
1805     {
1806       /* TODO: we do not use this path at the moment because drag events will
1807            go directly to the EmacsScroller.  Leaving code in for now. */
1808       [last_mouse_scroll_bar getMouseMotionPart: (int *)part window: bar_window
1809                                               x: x y: y];
1810       if (time) *time = last_mouse_movement_time;
1811       last_mouse_scroll_bar = nil;
1812     }
1813   else
1814     {
1815       /* Clear the mouse-moved flag for every frame on this display.  */
1816       FOR_EACH_FRAME (tail, frame)
1817         if (FRAME_NS_P (XFRAME (frame))
1818             && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1819           XFRAME (frame)->mouse_moved = 0;
1821       last_mouse_scroll_bar = nil;
1822       if (last_mouse_frame && FRAME_LIVE_P (last_mouse_frame))
1823         f = last_mouse_frame;
1824       else
1825         f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame
1826                                     : SELECTED_FRAME ();
1828       if (f && f->output_data.ns)  /* TODO: 2nd check no longer needed? */
1829         {
1830           view = FRAME_NS_VIEW (*fp);
1832           position = [[view window] mouseLocationOutsideOfEventStream];
1833           position = [view convertPoint: position fromView: nil];
1834           remember_mouse_glyph (f, position.x, position.y, &last_mouse_glyph);
1835 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1837           if (bar_window) *bar_window = Qnil;
1838           if (part) *part = 0; /*scroll_bar_handle; */
1840           if (x) XSETINT (*x, lrint (position.x));
1841           if (y) XSETINT (*y, lrint (position.y));
1842           if (time) *time = last_mouse_movement_time;
1843           *fp = f;
1844         }
1845     }
1847   UNBLOCK_INPUT;
1851 static void
1852 ns_frame_up_to_date (struct frame *f)
1853 /* --------------------------------------------------------------------------
1854     External (hook): Fix up mouse highlighting right after a full update.
1855     Some highlighting was deferred if GC was happening during
1856     note_mouse_highlight (), while other highlighting was deferred for update.
1857    -------------------------------------------------------------------------- */
1859   NSTRACE (ns_frame_up_to_date);
1861   if (FRAME_NS_P (f))
1862     {
1863       struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1864       if ((dpyinfo->mouse_face_deferred_gc||f ==dpyinfo->mouse_face_mouse_frame)
1865       /*&& dpyinfo->mouse_face_mouse_frame*/)
1866         {
1867           BLOCK_INPUT;
1868          ns_update_begin(f);
1869           if (dpyinfo->mouse_face_mouse_frame)
1870             note_mouse_highlight (dpyinfo->mouse_face_mouse_frame,
1871                                   dpyinfo->mouse_face_mouse_x,
1872                                   dpyinfo->mouse_face_mouse_y);
1873           dpyinfo->mouse_face_deferred_gc = 0;
1874          ns_update_end(f);
1875           UNBLOCK_INPUT;
1876         }
1877     }
1881 void
1882 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1883 /* --------------------------------------------------------------------------
1884     External (RIF): set frame mouse pointer type.
1885    -------------------------------------------------------------------------- */
1887   NSTRACE (ns_define_frame_cursor);
1888   if (FRAME_POINTER_TYPE (f) != cursor)
1889     {
1890       EmacsView *view = FRAME_NS_VIEW (f);
1891       FRAME_POINTER_TYPE (f) = cursor;
1892       [[view window] invalidateCursorRectsForView: view];
1893     }
1898 /* ==========================================================================
1900     Keyboard handling
1902    ========================================================================== */
1905 static unsigned
1906 ns_convert_key (unsigned code)
1907 /* --------------------------------------------------------------------------
1908     Internal call used by NSView-keyDown.
1909    -------------------------------------------------------------------------- */
1911   const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym)
1912                                 / sizeof (convert_ns_to_X_keysym[0]));
1913   unsigned keysym;
1914   /* An array would be faster, but less easy to read. */
1915   for (keysym = 0; keysym < last_keysym; keysym += 2)
1916     if (code == convert_ns_to_X_keysym[keysym])
1917       return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
1918   return 0;
1919 /* if decide to use keyCode and Carbon table, use this line:
1920      return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
1924 char *
1925 x_get_keysym_name (int keysym)
1926 /* --------------------------------------------------------------------------
1927     Called by keyboard.c.  Not sure if the return val is important, except
1928     that it be unique.
1929    -------------------------------------------------------------------------- */
1931   static char value[16];
1932   NSTRACE (x_get_keysym_name);
1933   sprintf (value, "%d", keysym);
1934   return value;
1939 /* ==========================================================================
1941     Block drawing operations
1943    ========================================================================== */
1946 static void
1947 ns_redraw_scroll_bars (struct frame *f)
1949   int i;
1950   id view;
1951   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
1952   NSTRACE (ns_judge_scroll_bars);
1953   for (i =[subviews count]-1; i >= 0; i--)
1954     {
1955       view = [subviews objectAtIndex: i];
1956       if (![view isKindOfClass: [EmacsScroller class]]) continue;
1957       [view display];
1958     }
1962 void
1963 ns_clear_frame (struct frame *f)
1964 /* --------------------------------------------------------------------------
1965       External (hook): Erase the entire frame
1966    -------------------------------------------------------------------------- */
1968   NSView *view = FRAME_NS_VIEW (f);
1969   NSRect r;
1971   NSTRACE (ns_clear_frame);
1972   if (ns_in_resize)
1973     return;
1975  /* comes on initial frame because we have
1976     after-make-frame-functions = select-frame */
1977  if (!FRAME_DEFAULT_FACE (f))
1978    return;
1980   mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
1982   output_cursor.hpos = output_cursor.vpos = 0;
1983   output_cursor.x = -1;
1985   r = [view bounds];
1987   BLOCK_INPUT;
1988   ns_focus (f, &r, 1);
1989   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
1990   NSRectFill (r);
1991   ns_unfocus (f);
1993 #ifdef NS_IMPL_COCOA
1994   [[view window] display];  /* redraw resize handle */
1995 #endif
1997   /* as of 2006/11 or so this is now needed */
1998   ns_redraw_scroll_bars (f);
1999   UNBLOCK_INPUT;
2003 void
2004 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2005 /* --------------------------------------------------------------------------
2006     External (RIF):  Clear section of frame
2007    -------------------------------------------------------------------------- */
2009   NSRect r = NSMakeRect (x, y, width, height);
2010   NSView *view = FRAME_NS_VIEW (f);
2011   struct face *face = FRAME_DEFAULT_FACE (f);
2013   if (!view || !face)
2014     return;
2016   NSTRACE (ns_clear_frame_area);
2018   r = NSIntersectionRect (r, [view frame]);
2019   ns_focus (f, &r, 1);
2020   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2022 #ifdef NS_IMPL_COCOA
2023   {
2024     /* clip out the resize handle */
2025     NSWindow *window = [FRAME_NS_VIEW (f) window];
2026     NSRect ir
2027       = [view convertRect: ns_resize_handle_rect (window) fromView: nil];
2029     ir = NSIntersectionRect (r, ir);
2030     if (NSIsEmptyRect (ir))
2031       {
2032 #endif
2034   NSRectFill (r);
2036 #ifdef NS_IMPL_COCOA
2037       }
2038     else
2039       {
2040         NSRect r1 = r, r2 = r; /* upper and lower non-intersecting */
2041         r1.size.height -= ir.size.height;
2042         r2.origin.y += r1.size.height;
2043         r2.size.width -= ir.size.width;
2044         r2.size.height = ir.size.height;
2045         NSRectFill (r1);
2046         NSRectFill (r2);
2047       }
2048   }
2049 #endif
2051   ns_unfocus (f);
2052   return;
2056 static void
2057 ns_scroll_run (struct window *w, struct run *run)
2058 /* --------------------------------------------------------------------------
2059     External (RIF):  Insert or delete n lines at line vpos
2060    -------------------------------------------------------------------------- */
2062   struct frame *f = XFRAME (w->frame);
2063   int x, y, width, height, from_y, to_y, bottom_y;
2065   NSTRACE (ns_scroll_run);
2067   /* begin copy from other terms */
2068   /* Get frame-relative bounding box of the text display area of W,
2069      without mode lines.  Include in this box the left and right
2070      fringe of W.  */
2071   window_box (w, -1, &x, &y, &width, &height);
2073   from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2074   to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2075   bottom_y = y + height;
2077   if (to_y < from_y)
2078     {
2079       /* Scrolling up.  Make sure we don't copy part of the mode
2080          line at the bottom.  */
2081       if (from_y + run->height > bottom_y)
2082         height = bottom_y - from_y;
2083       else
2084         height = run->height;
2085     }
2086   else
2087     {
2088       /* Scolling down.  Make sure we don't copy over the mode line.
2089          at the bottom.  */
2090       if (to_y + run->height > bottom_y)
2091         height = bottom_y - to_y;
2092       else
2093         height = run->height;
2094     }
2095   /* end copy from other terms */
2097   if (height == 0)
2098       return;
2100   BLOCK_INPUT;
2102   updated_window = w;
2103   x_clear_cursor (w);
2105   {
2106     NSRect srcRect = NSMakeRect (x, from_y, width, height);
2107     NSRect dstRect = NSMakeRect (x, to_y, width, height);
2108     NSPoint dstOrigin = NSMakePoint (x, to_y);
2110     ns_focus (f, &dstRect, 1);
2111     NSCopyBits (0, srcRect , dstOrigin);
2112     ns_unfocus (f);
2113   }
2115   UNBLOCK_INPUT;
2119 static void
2120 ns_after_update_window_line (struct glyph_row *desired_row)
2121 /* --------------------------------------------------------------------------
2122     External (RIF): preparatory to fringe update after text was updated
2123    -------------------------------------------------------------------------- */
2125   struct window *w = updated_window;
2126   struct frame *f;
2127   int width, height;
2129   NSTRACE (ns_after_update_window_line);
2131   /* begin copy from other terms */
2132   xassert (w);
2134   if (!desired_row->mode_line_p && !w->pseudo_window_p)
2135     desired_row->redraw_fringe_bitmaps_p = 1;
2137   /* When a window has disappeared, make sure that no rest of
2138      full-width rows stays visible in the internal border.
2139      Under NS this is drawn inside the fringes. */
2140   if (windows_or_buffers_changed
2141       && (f = XFRAME (w->frame),
2142           width = FRAME_INTERNAL_BORDER_WIDTH (f),
2143           width != 0)
2144       && (height = desired_row->visible_height,
2145           height > 0))
2146     {
2147       int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2149       /* Internal border is drawn below the tool bar.  */
2150       if (WINDOWP (f->tool_bar_window)
2151           && w == XWINDOW (f->tool_bar_window))
2152         y -= width;
2153       /* end copy from other terms */
2155       BLOCK_INPUT;
2156       if (!desired_row->full_width_p)
2157         {
2158           int x1 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2159             + WINDOW_LEFT_FRINGE_WIDTH (w);
2160           int x2 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2161             + FRAME_PIXEL_WIDTH (f) - NS_SCROLL_BAR_WIDTH (f)
2162             - WINDOW_RIGHT_FRINGE_WIDTH (w)
2163             - FRAME_INTERNAL_BORDER_WIDTH (f);
2164           ns_clear_frame_area (f, x1, y, width, height);
2165           ns_clear_frame_area (f, x2, y, width, height);
2166         }
2167       UNBLOCK_INPUT;
2168     }
2172 static void
2173 ns_shift_glyphs_for_insert (struct frame *f,
2174                            int x, int y, int width, int height,
2175                            int shift_by)
2176 /* --------------------------------------------------------------------------
2177     External (RIF): copy an area horizontally, don't worry about clearing src
2178    -------------------------------------------------------------------------- */
2180   NSRect srcRect = NSMakeRect (x, y, width, height);
2181   NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2182   NSPoint dstOrigin = dstRect.origin;
2184   NSTRACE (ns_shift_glyphs_for_insert);
2186   ns_focus (f, &dstRect, 1);
2187   NSCopyBits (0, srcRect, dstOrigin);
2188   ns_unfocus (f);
2193 /* ==========================================================================
2195     Character encoding and metrics
2197    ========================================================================== */
2200 static inline void
2201 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2202 /* --------------------------------------------------------------------------
2203      External (RIF); compute left/right overhang of whole string and set in s
2204    -------------------------------------------------------------------------- */
2206   struct face *face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2207   struct font *font = s->font; /*face->font; */
2209   if (s->char2b)
2210     {
2211       struct font_metrics metrics;
2212       unsigned int codes[2];
2213       codes[0] = *(s->char2b);
2214       codes[1] = *(s->char2b + s->nchars - 1);
2216       font->driver->text_extents (font, codes, 2, &metrics);
2217       s->left_overhang = -metrics.lbearing;
2218       s->right_overhang
2219         = metrics.rbearing > metrics.width
2220         ? metrics.rbearing - metrics.width : 0;
2221     }
2222   else
2223     {
2224       s->left_overhang = 0;
2225       s->right_overhang = ((struct nsfont_info *)font)->ital ?
2226         FONT_HEIGHT (font) * 0.2 : 0;
2227     }
2232 /* ==========================================================================
2234     Fringe and cursor drawing
2236    ========================================================================== */
2239 extern int max_used_fringe_bitmap;
2240 static void
2241 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2242                       struct draw_fringe_bitmap_params *p)
2243 /* --------------------------------------------------------------------------
2244     External (RIF); fringe-related
2245    -------------------------------------------------------------------------- */
2247   struct frame *f = XFRAME (WINDOW_FRAME (w));
2248   struct face *face = p->face;
2249   int rowY;
2250   static EmacsImage **bimgs = NULL;
2251   static int nBimgs = 0;
2252   /* NS-specific: move internal border inside fringe */
2253   int x = p->bx < 0 ? p->x : p->bx;
2254   int wd = p->bx < 0 ? p->wd : p->nx;
2255   BOOL fringeOnVeryLeft
2256     = x - WINDOW_LEFT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w)
2257       - FRAME_INTERNAL_BORDER_WIDTH (f) < 10;
2258   BOOL fringeOnVeryRight
2259     = FRAME_PIXEL_WIDTH (f) - x - wd - FRAME_INTERNAL_BORDER_WIDTH (f)
2260       - WINDOW_RIGHT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w) < 10;
2261   int xAdjust = FRAME_INTERNAL_BORDER_WIDTH (f) *
2262     (fringeOnVeryLeft ? -1 : (fringeOnVeryRight ? 1 : 0));
2264   /* grow bimgs if needed */
2265   if (nBimgs < max_used_fringe_bitmap)
2266     {
2267       EmacsImage **newBimgs
2268         = xmalloc (max_used_fringe_bitmap * sizeof (EmacsImage *));
2269       bzero (newBimgs, max_used_fringe_bitmap * sizeof (EmacsImage *));
2271       if (nBimgs)
2272         {
2273           bcopy (bimgs, newBimgs, nBimgs * sizeof (EmacsImage *));
2274           xfree (bimgs);
2275         }
2277       bimgs = newBimgs;
2278       nBimgs = max_used_fringe_bitmap;
2279     }
2281   /* Must clip because of partially visible lines.  */
2282   rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
2283   if (p->y < rowY)
2284     {
2285       /* Adjust position of "bottom aligned" bitmap on partially
2286          visible last row.  */
2287       int oldY = row->y;
2288       int oldVH = row->visible_height;
2289       row->visible_height = p->h;
2290       row->y -= rowY - p->y;
2291       ns_clip_to_row (w, row, -1, NO);
2292       row->y = oldY;
2293       row->visible_height = oldVH;
2294     }
2295   else
2296     ns_clip_to_row (w, row, -1, YES);
2298   if (p->bx >= 0 && !p->overlay_p)
2299     {
2300       int yAdjust = rowY - FRAME_INTERNAL_BORDER_WIDTH (f) < 5 ?
2301         -FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2302       int yIncr = FRAME_PIXEL_HEIGHT (f) - (p->by+yAdjust + p->ny) < 5 ?
2303         FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2304       if (yAdjust)
2305         yIncr += FRAME_INTERNAL_BORDER_WIDTH (f);
2306       NSRect r = NSMakeRect (p->bx+xAdjust, p->by+yAdjust, p->nx, p->ny+yIncr);
2307       NSRectClip (r);
2308       [ns_lookup_indexed_color(face->background, f) set];
2309       NSRectFill (r);
2310     }
2312   if (p->which)
2313     {
2314       NSRect r = NSMakeRect (p->x+xAdjust, p->y, p->wd, p->h);
2315       NSPoint pt = r.origin;
2316       EmacsImage *img = bimgs[p->which - 1];
2318       if (!img)
2319         {
2320           unsigned short *bits = p->bits + p->dh;
2321           int len = 8 * p->h/8;
2322           int i;
2323           unsigned char *cbits = xmalloc (len);
2325           for (i =0; i<len; i++)
2326             cbits[i] = ~(bits[i] & 0xff);
2327           img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2328                                            flip: NO];
2329           bimgs[p->which - 1] = img;
2330           xfree (cbits);
2331         }
2333       NSRectClip (r);
2334       /* Since we composite the bitmap instead of just blitting it, we need
2335          to erase the whole background. */
2336       [ns_lookup_indexed_color(face->background, f) set];
2337       NSRectFill (r);
2338       pt.y += p->h;
2339       [img setXBMColor: ns_lookup_indexed_color(face->foreground, f)];
2340       [img compositeToPoint: pt operation: NSCompositeSourceOver];
2341     }
2342   ns_unfocus (f);
2346 void
2347 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2348                        int x, int y, int cursor_type, int cursor_width,
2349                        int on_p, int active_p)
2350 /* --------------------------------------------------------------------------
2351      External call (RIF): draw cursor
2352      (modeled after x_draw_window_cursor
2353      FIXME: cursor_width is effectively bogus -- it sometimes gets set
2354      in xdisp.c set_frame_cursor_types, sometimes left uninitialized;
2355      DON'T USE IT (no other terms do)
2356    -------------------------------------------------------------------------- */
2358   NSRect r, s;
2359   int fx, fy, h;
2360   struct frame *f = WINDOW_XFRAME (w);
2361   struct glyph *phys_cursor_glyph;
2362   int overspill, cursorToDraw;
2364   NSTRACE (dumpcursor);
2365 //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);
2367   if (!on_p)
2368         return;
2370   w->phys_cursor_type = cursor_type;
2371   w->phys_cursor_on_p = on_p;
2373   if (cursor_type == NO_CURSOR)
2374     {
2375       w->phys_cursor_width = 0;
2376       return;
2377     }
2379   if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2380     {
2381       if (glyph_row->exact_window_width_line_p
2382           && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2383         {
2384           glyph_row->cursor_in_fringe_p = 1;
2385           draw_fringe_bitmap (w, glyph_row, 0);
2386         }
2387       return;
2388     }
2390   get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2392   r.origin.x = fx, r.origin.y = fy;
2393   r.size.height = h;
2394   r.size.width = w->phys_cursor_width;
2396   /* FIXME: if we overwrite the internal border area, it does not get erased;
2397      fix by truncating cursor, but better would be to erase properly */
2398   overspill = r.origin.x + r.size.width -
2399     WINDOW_TEXT_TO_FRAME_PIXEL_X (w, WINDOW_BOX_RIGHT_EDGE_X (w) 
2400       - WINDOW_TOTAL_FRINGE_WIDTH (w) - FRAME_INTERNAL_BORDER_WIDTH (f));
2401   if (overspill > 0)
2402     r.size.width -= overspill;
2404   /* TODO: only needed in rare cases with last-resort font in HELLO..
2405      should we do this more efficiently? */
2406   ns_clip_to_row (w, glyph_row, -1, NO); /* do ns_focus(f, &r, 1); if remove */
2407   [FRAME_CURSOR_COLOR (f) set];
2409 #ifdef NS_IMPL_COCOA
2410   /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2411            atomic.  Cleaner ways of doing this should be investigated.
2412            One way would be to set a global variable DRAWING_CURSOR
2413            when making the call to draw_phys..(), don't focus in that
2414            case, then move the ns_unfocus() here after that call. */
2415   NSDisableScreenUpdates ();
2416 #endif
2418   cursorToDraw = active_p ? cursor_type : HOLLOW_BOX_CURSOR;
2419   switch (cursorToDraw)
2420     {
2421     case NO_CURSOR:
2422       break;
2423     case FILLED_BOX_CURSOR:
2424       NSRectFill (r);
2425       break;
2426     case HOLLOW_BOX_CURSOR:
2427       NSRectFill (r);
2428       [FRAME_BACKGROUND_COLOR (f) set];
2429       NSRectFill (NSInsetRect (r, 1, 1));
2430       [FRAME_CURSOR_COLOR (f) set];
2431       break;
2432     case HBAR_CURSOR:
2433       s = r;
2434       s.origin.y += lrint (0.75 * s.size.height);
2435       s.size.height = lrint (s.size.height * 0.25);
2436       NSRectFill (s);
2437       break;
2438     case BAR_CURSOR:
2439       s = r;
2440       s.size.width = min (cursor_width, 2); //FIXME(see above)
2441       NSRectFill (s);
2442       break;
2443     }
2444   ns_unfocus (f);
2446   /* draw the character under the cursor */
2447   if (cursorToDraw != NO_CURSOR)
2448     draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2450 #ifdef NS_IMPL_COCOA
2451   NSEnableScreenUpdates ();
2452 #endif
2457 static void
2458 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2459 /* --------------------------------------------------------------------------
2460      External (RIF): Draw a vertical line.
2461    -------------------------------------------------------------------------- */
2463   struct frame *f = XFRAME (WINDOW_FRAME (w));
2464   struct face *face;
2465   NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2467   NSTRACE (ns_draw_vertical_window_border);
2469   face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2470   if (face)
2471       [ns_lookup_indexed_color(face->foreground, f) set];
2473   ns_focus (f, &r, 1);
2474   NSRectFill(r);
2475   ns_unfocus (f);
2479 void
2480 show_hourglass (struct atimer *timer)
2482   if (hourglass_shown_p)
2483     return;
2485   BLOCK_INPUT;
2487   /* TODO: add NSProgressIndicator to selected frame (see macfns.c) */
2489   hourglass_shown_p = 1;
2490   UNBLOCK_INPUT;
2494 void
2495 hide_hourglass ()
2497   if (!hourglass_shown_p)
2498     return;
2500   BLOCK_INPUT;
2502   /* TODO: remove NSProgressIndicator from all frames */
2504   hourglass_shown_p = 0;
2505   UNBLOCK_INPUT;
2510 /* ==========================================================================
2512     Glyph drawing operations
2514    ========================================================================== */
2517 static inline NSRect
2518 ns_fix_rect_ibw (NSRect r, int fibw, int frame_pixel_width)
2519 /* --------------------------------------------------------------------------
2520     Under NS we draw internal borders inside fringes, and want full-width
2521     rendering to go all the way to edge.  This function makes that correction.
2522    -------------------------------------------------------------------------- */
2524   if (r.origin.y <= fibw+1)
2525     {
2526       r.size.height += r.origin.y;
2527       r.origin.y = 0;
2528     }
2529   if (r.origin.x <= fibw+1)
2530     {
2531       r.size.width += r.origin.x;
2532       r.origin.x = 0;
2533     }
2534   if (frame_pixel_width - (r.origin.x+r.size.width) <= fibw+1)
2535     r.size.width += fibw;
2537   return r;
2541 static int
2542 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2543 /* --------------------------------------------------------------------------
2544     Wrapper utility to account for internal border width on full-width lines,
2545     and allow top full-width rows to hit the frame top.  nr should be pointer
2546     to two successive NSRects.  Number of rects actually used is returned.
2547    -------------------------------------------------------------------------- */
2549   int n = get_glyph_string_clip_rects (s, nr, 2);
2550   if (s->row->full_width_p)
2551     {
2552       *nr = ns_fix_rect_ibw (*nr, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2553                             FRAME_PIXEL_WIDTH (s->f));
2554       if (n == 2)
2555         *nr = ns_fix_rect_ibw (*(nr+1), FRAME_INTERNAL_BORDER_WIDTH (s->f),
2556                               FRAME_PIXEL_WIDTH (s->f));
2557     }
2558   return n;
2562 static void
2563 ns_draw_box (NSRect r, float thickness, NSColor *col, char left_p, char right_p)
2564 /* --------------------------------------------------------------------------
2565     Draw an unfilled rect inside r, optionally leaving left and/or right open.
2566     Note we can't just use an NSDrawRect command, because of the possibility
2567     of some sides not being drawn, and because the rect will be filled.
2568    -------------------------------------------------------------------------- */
2570   NSRect s = r;
2571   [col set];
2573   /* top, bottom */
2574   s.size.height = thickness;
2575   NSRectFill (s);
2576   s.origin.y += r.size.height - thickness;
2577   NSRectFill (s);
2579   s.size.height = r.size.height;
2580   s.origin.y = r.origin.y;
2582   /* left, right (optional) */
2583   s.size.width = thickness;
2584   if (left_p)
2585     NSRectFill (s);
2586   if (right_p)
2587     {
2588       s.origin.x += r.size.width - thickness;
2589       NSRectFill (s);
2590     }
2594 static void
2595 ns_draw_relief (NSRect r, int thickness, char raised_p,
2596                char top_p, char bottom_p, char left_p, char right_p,
2597                struct glyph_string *s)
2598 /* --------------------------------------------------------------------------
2599     Draw a relief rect inside r, optionally leaving some sides open.
2600     Note we can't just use an NSDrawBezel command, because of the possibility
2601     of some sides not being drawn, and because the rect will be filled.
2602    -------------------------------------------------------------------------- */
2604   static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2605   NSColor *newBaseCol = nil;
2606   NSRect sr = r;
2608   NSTRACE (ns_draw_relief);
2610   /* set up colors */
2612   if (s->face->use_box_color_for_shadows_p)
2613     {
2614       newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2615     }
2616 /*     else if (s->first_glyph->type == IMAGE_GLYPH
2617            && s->img->pixmap
2618            && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2619        {
2620          newBaseCol = IMAGE_BACKGROUND  (s->img, s->f, 0);
2621        } */
2622   else
2623     {
2624       newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2625     }
2627   if (newBaseCol == nil)
2628     newBaseCol = [NSColor grayColor];
2630   if (newBaseCol != baseCol)  /* TODO: better check */
2631     {
2632       [baseCol release];
2633       baseCol = [newBaseCol retain];
2634       [lightCol release];
2635       lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2636       [darkCol release];
2637       darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2638     }
2640   [(raised_p ? lightCol : darkCol) set];
2642   /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2644   /* top */
2645   sr.size.height = thickness;
2646   if (top_p) NSRectFill (sr);
2648   /* left */
2649   sr.size.height = r.size.height;
2650   sr.size.width = thickness;
2651   if (left_p) NSRectFill (sr);
2653   [(raised_p ? darkCol : lightCol) set];
2655   /* bottom */
2656   sr.size.width = r.size.width;
2657   sr.size.height = thickness;
2658   sr.origin.y += r.size.height - thickness;
2659   if (bottom_p) NSRectFill (sr);
2661   /* right */
2662   sr.size.height = r.size.height;
2663   sr.origin.y = r.origin.y;
2664   sr.size.width = thickness;
2665   sr.origin.x += r.size.width - thickness;
2666   if (right_p) NSRectFill (sr);
2670 static void
2671 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2672 /* --------------------------------------------------------------------------
2673       Function modeled after x_draw_glyph_string_box ().
2674       Sets up parameters for drawing.
2675    -------------------------------------------------------------------------- */
2677   int right_x, last_x;
2678   char left_p, right_p;
2679   struct glyph *last_glyph;
2680   NSRect r;
2681   int thickness;
2682   struct face *face;
2684   if (s->hl == DRAW_MOUSE_FACE)
2685     {
2686       face = FACE_FROM_ID
2687         (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2688       if (!face)
2689         face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2690     }
2691   else
2692     face = s->face;
2694   thickness = face->box_line_width;
2696   NSTRACE (ns_dumpglyphs_box_or_relief);
2698   last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2699             ? WINDOW_RIGHT_EDGE_X (s->w)
2700             : window_box_right (s->w, s->area));
2701   last_glyph = (s->cmp || s->img
2702                 ? s->first_glyph : s->first_glyph + s->nchars-1);
2704   right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2705               ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2707   left_p = (s->first_glyph->left_box_line_p
2708             || (s->hl == DRAW_MOUSE_FACE
2709                 && (s->prev == NULL || s->prev->hl != s->hl)));
2710   right_p = (last_glyph->right_box_line_p
2711              || (s->hl == DRAW_MOUSE_FACE
2712                  && (s->next == NULL || s->next->hl != s->hl)));
2714   r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2716   /* expand full-width row over internal borders */
2717   if (s->row->full_width_p)
2718     r = ns_fix_rect_ibw (r, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2719                         FRAME_PIXEL_WIDTH (s->f));
2721   if (s->face->box == FACE_SIMPLE_BOX)
2722     {
2723       xassert (s->face->box_color != nil);
2724       ns_draw_box (r, abs (thickness),
2725                    ns_lookup_indexed_color (face->box_color, s->f),
2726                   left_p, right_p);
2727     }
2728   else
2729     {
2730       ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2731                      1, 1, left_p, right_p, s);
2732     }
2736 static void
2737 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2738 /* --------------------------------------------------------------------------
2739       Modeled after x_draw_glyph_string_background, which draws BG in
2740       certain cases.  Others are left to the text rendering routine.
2741    -------------------------------------------------------------------------- */
2743   NSTRACE (ns_maybe_dumpglyphs_background);
2745   if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2746     {
2747       int box_line_width = max (s->face->box_line_width, 0);
2748       if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2749           || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2750         {
2751           struct face *face;
2752           if (s->hl == DRAW_MOUSE_FACE)
2753             {
2754               face = FACE_FROM_ID
2755                 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2756               if (!face)
2757                 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2758             }
2759           else
2760             face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2761           if (!face->stipple)
2762             [(NS_FACE_BACKGROUND (face) != 0
2763               ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2764               : FRAME_BACKGROUND_COLOR (s->f)) set];
2765           else
2766             {
2767               struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (s->f);
2768               [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2769             }
2771           if (s->hl != DRAW_CURSOR)
2772             {
2773               NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2774                                     s->background_width,
2775                                     s->height-2*box_line_width);
2777               /* expand full-width row over internal borders */
2778               if (s->row->full_width_p)
2779                 {
2780                   int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2781                   if (r.origin.y <= fibw+1 + box_line_width)
2782                     {
2783                       r.size.height += r.origin.y;
2784                       r.origin.y = 0;
2785                     }
2786                   if (r.origin.x <= fibw+1)
2787                     {
2788                       r.size.width += 2*r.origin.x;
2789                       r.origin.x = 0;
2790                     }
2791                   if (FRAME_PIXEL_WIDTH (s->f) - (r.origin.x + r.size.width)
2792                       <= fibw+1)
2793                     r.size.width += fibw;
2794                 }
2796               NSRectFill (r);
2797             }
2799           s->background_filled_p = 1;
2800         }
2801     }
2805 static void
2806 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2807 /* --------------------------------------------------------------------------
2808       Renders an image and associated borders.
2809    -------------------------------------------------------------------------- */
2811   EmacsImage *img = s->img->pixmap;
2812   int box_line_vwidth = max (s->face->box_line_width, 0);
2813   int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2814   int bg_x, bg_y, bg_height;
2815   int th;
2816   char raised_p;
2817   NSRect br;
2818   struct face *face;
2820   NSTRACE (ns_dumpglyphs_image);
2822   if (s->face->box != FACE_NO_BOX
2823       && s->first_glyph->left_box_line_p && s->slice.x == 0)
2824     x += abs (s->face->box_line_width);
2826   bg_x = x;
2827   bg_y =  s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2828   bg_height = s->height;
2829   /* other terms have this, but was causing problems w/tabbar mode */
2830   /* - 2 * box_line_vwidth; */
2832   if (s->slice.x == 0) x += s->img->hmargin;
2833   if (s->slice.y == 0) y += s->img->vmargin;
2835   /* Draw BG: if we need larger area than image itself cleared, do that,
2836      otherwise, since we composite the image under NS (instead of mucking
2837      with its background color), we must clear just the image area. */
2838   if (s->hl == DRAW_MOUSE_FACE)
2839     {
2840       face = FACE_FROM_ID
2841        (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2842       if (!face)
2843        face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2844     }
2845   else
2846     face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2848   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
2850   if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
2851       || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
2852     {
2853       br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
2854       s->background_filled_p = 1;
2855     }
2856   else
2857     {
2858       br = NSMakeRect (x, y, s->slice.width, s->slice.height);
2859     }
2861   /* expand full-width row over internal borders */
2862   if (s->row->full_width_p)
2863     {
2864       int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2865       if (br.origin.y <= fibw+1 + box_line_vwidth)
2866         {
2867           br.size.height += br.origin.y;
2868           br.origin.y = 0;
2869         }
2870       if (br.origin.x <= fibw+1 + box_line_vwidth)
2871         {
2872           br.size.width += br.origin.x;
2873           br.origin.x = 0;
2874         }
2875       if (FRAME_PIXEL_WIDTH (s->f) - (br.origin.x + br.size.width) <= fibw+1)
2876         br.size.width += fibw;
2877     }
2879   NSRectFill (br);
2881   /* Draw the image.. do we need to draw placeholder if img ==nil? */
2882   if (img != nil)
2883     [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
2884                 operation: NSCompositeSourceOver];
2886   /* Draw relief, if requested */
2887   if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
2888     {
2889       if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
2890         {
2891           th = tool_bar_button_relief >= 0 ?
2892             tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2893           raised_p = (s->hl == DRAW_IMAGE_RAISED);
2894         }
2895       else
2896         {
2897           th = abs (s->img->relief);
2898           raised_p = (s->img->relief > 0);
2899         }
2901       r.origin.x = x - th;
2902       r.origin.y = y - th;
2903       r.size.width = s->slice.width + 2*th-1;
2904       r.size.height = s->slice.height + 2*th-1;
2905       ns_draw_relief (r, th, raised_p,
2906                       s->slice.y == 0,
2907                       s->slice.y + s->slice.height == s->img->height,
2908                       s->slice.x == 0,
2909                       s->slice.x + s->slice.width == s->img->width, s);
2910     }
2914 static void
2915 ns_dumpglyphs_stretch (struct glyph_string *s)
2917   NSRect r[2];
2918   int n, i;
2919   struct face *face;
2921   if (!s->background_filled_p)
2922     {
2923       n = ns_get_glyph_string_clip_rect (s, r);
2924       *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
2926       for (i=0; i<n; i++)
2927         {
2928           if (!s->row->full_width_p)
2929             {
2930               /* truncate to avoid overwriting fringe and/or scrollbar */
2931               int overrun = max (0, (s->x + s->background_width)
2932                                   - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
2933                                     - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
2934               r[i].size.width -= overrun;
2936               /* XXX: Try to work between problem where a stretch glyph on
2937                  a partially-visible bottom row will clear part of the
2938                  modeline, and another where list-buffers headers and similar
2939                  rows erroneously have visible_height set to 0.  Not sure
2940                  where this is coming from as other terms seem not to show. */
2941               r[i].size.height = min (s->height, s->row->visible_height);
2942             }
2944           /* expand full-width rows over internal borders */
2945           else
2946             {
2947               r[i] = ns_fix_rect_ibw (r[i], FRAME_INTERNAL_BORDER_WIDTH (s->f),
2948                                       FRAME_PIXEL_WIDTH (s->f));
2949             }
2951           /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
2952              overwriting cursor (usually when cursor on a tab) */
2953           if (s->hl == DRAW_CURSOR)
2954             {
2955               r[i].origin.x += s->width;
2956               r[i].size.width -= s->width;
2957             }
2958         }
2960       ns_focus (s->f, r, n);
2962       if (s->hl == DRAW_MOUSE_FACE)
2963        {
2964          face = FACE_FROM_ID
2965            (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2966          if (!face)
2967            face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2968        }
2969       else
2970        face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2972       [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
2974       NSRectFill (r[0]);
2975       NSRectFill (r[1]);
2976       ns_unfocus (s->f);
2977       s->background_filled_p = 1;
2978     }
2982 static void
2983 ns_draw_glyph_string (struct glyph_string *s)
2984 /* --------------------------------------------------------------------------
2985       External (RIF): Main draw-text call.
2986    -------------------------------------------------------------------------- */
2988   /* TODO (optimize): focus for box and contents draw */
2989   NSRect r[2];
2990   int n;
2991   char box_drawn_p = 0;
2993   NSTRACE (ns_draw_glyph_string);
2995   if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
2996     {
2997       int width;
2998       struct glyph_string *next;
3000       for (width = 0, next = s->next;
3001            next && width < s->right_overhang;
3002            width += next->width, next = next->next)
3003         if (next->first_glyph->type != IMAGE_GLYPH)
3004           {
3005             if (next->first_glyph->type != STRETCH_GLYPH)
3006               {
3007                 n = ns_get_glyph_string_clip_rect (s->next, r);
3008                 ns_focus (s->f, r, n);
3009                 ns_maybe_dumpglyphs_background (s->next, 1);
3010                 ns_unfocus (s->f);
3011               }
3012             else
3013               {
3014                 ns_dumpglyphs_stretch (s->next);
3015               }
3016             next->num_clips = 0;
3017           }
3018     }
3020   if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3021         && (s->first_glyph->type == CHAR_GLYPH
3022             || s->first_glyph->type == COMPOSITE_GLYPH))
3023     {
3024       n = ns_get_glyph_string_clip_rect (s, r);
3025       ns_focus (s->f, r, n);
3026       ns_maybe_dumpglyphs_background (s, 1);
3027       ns_dumpglyphs_box_or_relief (s);
3028       ns_unfocus (s->f);
3029       box_drawn_p = 1;
3030     }
3032   switch (s->first_glyph->type)
3033     {
3035     case IMAGE_GLYPH:
3036       n = ns_get_glyph_string_clip_rect (s, r);
3037       ns_focus (s->f, r, n);
3038       ns_dumpglyphs_image (s, r[0]);
3039       ns_unfocus (s->f);
3040       break;
3042     case STRETCH_GLYPH:
3043       ns_dumpglyphs_stretch (s);
3044       break;
3046     case CHAR_GLYPH:
3047     case COMPOSITE_GLYPH:
3048       n = ns_get_glyph_string_clip_rect (s, r);
3049       ns_focus (s->f, r, n);
3051       if (s->for_overlaps || (s->cmp_from > 0
3052                               && ! s->first_glyph->u.cmp.automatic))
3053         s->background_filled_p = 1;
3054       else      /* 1 */
3055         ns_maybe_dumpglyphs_background
3056           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3058       ns_tmp_flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3059                     (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3060                      (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3061                       NS_DUMPGLYPH_NORMAL));
3062       ns_tmp_font = (struct nsfont_info *)s->face->font;
3063       if (ns_tmp_font == NULL)
3064           ns_tmp_font = (struct nsfont_info *)FRAME_FONT (s->f);
3066       ns_tmp_font->font.driver->draw
3067         (s, 0, s->nchars, s->x, s->y,
3068          (ns_tmp_flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3069          || ns_tmp_flags == NS_DUMPGLYPH_MOUSEFACE);
3071       ns_unfocus (s->f);
3072       break;
3074     default:
3075       abort ();
3076     }
3078   /* Draw box if not done already. */
3079   if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3080     {
3081       n = ns_get_glyph_string_clip_rect (s, r);
3082       ns_focus (s->f, r, n);
3083       ns_dumpglyphs_box_or_relief (s);
3084       ns_unfocus (s->f);
3085     }
3087   s->num_clips = 0;
3092 /* ==========================================================================
3094     Event loop
3096    ========================================================================== */
3099 static void
3100 ns_send_appdefined (int value)
3101 /* --------------------------------------------------------------------------
3102     Internal: post an appdefined event which EmacsApp-sendEvent will
3103               recognize and take as a command to halt the event loop.
3104    -------------------------------------------------------------------------- */
3106   /*NSTRACE (ns_send_appdefined); */
3108   /* Only post this event if we haven't already posted one.  This will end
3109        the [NXApp run] main loop after having processed all events queued at
3110        this moment.  */
3111   if (send_appdefined)
3112     {
3113       NSEvent *nxev;
3115       /* We only need one NX_APPDEFINED event to stop NXApp from running.  */
3116       send_appdefined = NO;
3118       /* Don't need wakeup timer any more */
3119       if (timed_entry)
3120         {
3121           [timed_entry invalidate];
3122           [timed_entry release];
3123           timed_entry = nil;
3124         }
3126       /* Ditto for file descriptor poller */
3127       if (fd_entry)
3128         {
3129           [fd_entry invalidate];
3130           [fd_entry release];
3131           fd_entry = nil;
3132         }
3134       nxev = [NSEvent otherEventWithType: NSApplicationDefined
3135                                 location: NSMakePoint (0, 0)
3136                            modifierFlags: 0
3137                                timestamp: 0
3138                             windowNumber: [[NSApp mainWindow] windowNumber]
3139                                  context: [NSApp context]
3140                                  subtype: 0
3141                                    data1: value
3142                                    data2: 0];
3144       /* Post an application defined event on the event queue.  When this is
3145          received the [NXApp run] will return, thus having processed all
3146          events which are currently queued.  */
3147       [NSApp postEvent: nxev atStart: NO];
3148     }
3152 static int
3153 ns_read_socket (struct terminal *terminal, int expected,
3154                 struct input_event *hold_quit)
3155 /* --------------------------------------------------------------------------
3156      External (hook): Post an event to ourself and keep reading events until
3157      we read it back again.  In effect process all events which were waiting.
3158      From 21+ we have to manage the event buffer ourselves.
3159    -------------------------------------------------------------------------- */
3161   struct input_event ev;
3162   int nevents;
3164 /* NSTRACE (ns_read_socket); */
3166   if (interrupt_input_blocked)
3167     {
3168       interrupt_input_pending = 1;
3169 #ifdef SYNC_INPUT
3170       pending_signals = 1;
3171 #endif
3172       return -1;
3173     }
3175   interrupt_input_pending = 0;
3176 #ifdef SYNC_INPUT
3177   pending_signals = pending_atimers;
3178 #endif
3180   BLOCK_INPUT;
3181   n_emacs_events_pending = 0;
3182   EVENT_INIT (ev);
3183   emacs_event = &ev;
3184   q_event_ptr = hold_quit;
3186   /* we manage autorelease pools by allocate/reallocate each time around
3187      the loop; strict nesting is occasionally violated but seems not to
3188      matter.. earlier methods using full nesting caused major memory leaks */
3189   [outerpool release];
3190   outerpool = [[NSAutoreleasePool alloc] init];
3192   /* If have pending open-file requests, attend to the next one of those. */
3193   if (ns_pending_files && [ns_pending_files count] != 0
3194       && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3195     {
3196       [ns_pending_files removeObjectAtIndex: 0];
3197     }
3198   /* Deal with pending service requests. */
3199   else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3200     && [(EmacsApp *)
3201          NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3202                       withArg: [ns_pending_service_args objectAtIndex: 0]])
3203     {
3204       [ns_pending_service_names removeObjectAtIndex: 0];
3205       [ns_pending_service_args removeObjectAtIndex: 0];
3206     }
3207   else
3208     {
3209       /* Run and wait for events.  We must always send one NX_APPDEFINED event
3210          to ourself, otherwise [NXApp run] will never exit.  */
3211       send_appdefined = YES;
3213       /* If called via ns_select, this is called once with expected=1,
3214          because we expect either the timeout or file descriptor activity.
3215          In this case the first event through will either be real input or
3216          one of these.  read_avail_input() then calls once more with expected=0
3217          and in that case we need to return quickly if there is nothing.
3218          If we're being called outside of that, it's also OK to return quickly
3219          after one iteration through the event loop, since other terms do
3220          this and emacs expects it. */
3221       if (!(inNsSelect && expected))  // (!inNsSelect || !expected)
3222         {
3223           /* Post an application defined event on the event queue.  When this is
3224              received the [NXApp run] will return, thus having processed all
3225              events which are currently queued, if any.  */
3226           ns_send_appdefined (-1);
3227         }
3229       [NSApp run];
3230     }
3232   nevents = n_emacs_events_pending;
3233   n_emacs_events_pending = 0;
3234   emacs_event = q_event_ptr = NULL;
3235   UNBLOCK_INPUT;
3237   return nevents;
3242 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3243            fd_set *exceptfds, struct timeval *timeout)
3244 /* --------------------------------------------------------------------------
3245      Replacement for select, checking for events
3246    -------------------------------------------------------------------------- */
3248   int result;
3249   double time;
3250   NSEvent *ev;
3251 /*  NSTRACE (ns_select); */
3253   if (NSApp == nil || inNsSelect == 1 /* || ([NSApp isActive] == NO &&
3254                       [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
3255  inMode:NSDefaultRunLoopMode dequeue:NO] == nil) */)
3256     return select (nfds, readfds, writefds, exceptfds, timeout);
3258   /* Save file descriptor set, which gets overwritten in calls to select ()
3259      Note, this is called from process.c, and only readfds is ever set */
3260   if (readfds)
3261     {
3262       memcpy (&select_readfds, readfds, sizeof (fd_set));
3263       select_nfds = nfds;
3264     }
3265   else
3266     select_nfds = 0;
3268     /* Try an initial select for pending data on input files */
3269   select_timeout.tv_sec = select_timeout.tv_usec = 0;
3270   result = select (nfds, readfds, writefds, exceptfds, &select_timeout);
3271   if (result)
3272     return result;
3274   /* if (!timeout || timed_entry || fd_entry)
3275        fprintf (stderr, "assertion failed: timeout null or timed_entry/fd_entry non-null in ns_select\n"); */
3277     /* set a timeout and run the main AppKit event loop while continuing
3278        to monitor the files */
3279   time = ((double) timeout->tv_sec) + ((double) timeout->tv_usec)/1000000.0;
3280   timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3281                                            target: NSApp
3282                                          selector: @selector (timeout_handler:)
3283                                          userInfo: 0
3284                                           repeats: YES] /* for safe removal */
3285                                                          retain];
3287   /* set a periodic task to try the select () again */
3288   fd_entry = [[NSTimer scheduledTimerWithTimeInterval: 0.1
3289                                                target: NSApp
3290                                              selector: @selector (fd_handler:)
3291                                              userInfo: 0
3292                                               repeats: YES]
3293                retain];
3295   /* Let Application dispatch events until it receives an event of the type
3296      NX_APPDEFINED, which should only be sent by timeout_handler.
3297      We tell read_avail_input() that input is "expected" because we do expect
3298      either the timeout or fd handler to fire, and if they don't, the original
3299      call from process.c that got us here expects us to wait until some input
3300      comes. */
3301   inNsSelect = 1;
3302   gobble_input (1);
3303   ev = last_appdefined_event;
3304   inNsSelect = 0;
3306   if (ev)
3307     {
3308       int t;
3309       if ([ev type] != NSApplicationDefined)
3310         abort ();
3312       t = [ev data1];
3313       last_appdefined_event = 0;
3315       if (t == -2)
3316         {
3317           /* The NX_APPDEFINED event we received was a timeout. */
3318           return 0;
3319         }
3320       else if (t == -1)
3321         {
3322           /* The NX_APPDEFINED event we received was the result of
3323              at least one real input event arriving.  */
3324           errno = EINTR;
3325           return -1;
3326         }
3327       else
3328         {
3329           /* Received back from select () in fd_handler; copy the results */
3330           if (readfds)
3331             memcpy (readfds, &select_readfds, sizeof (fd_set));
3332           return t;
3333         }
3334     }
3335   /* never reached, shut compiler up */
3336   return 0;
3341 /* ==========================================================================
3343     Scrollbar handling
3345    ========================================================================== */
3348 static void
3349 ns_set_vertical_scroll_bar (struct window *window,
3350                            int portion, int whole, int position)
3351 /* --------------------------------------------------------------------------
3352       External (hook): Update or add scrollbar
3353    -------------------------------------------------------------------------- */
3355   Lisp_Object win;
3356   NSRect r, v;
3357   struct frame *f = XFRAME (WINDOW_FRAME (window));
3358   EmacsView *view = FRAME_NS_VIEW (f);
3359   int window_y, window_height;
3360   BOOL barOnVeryLeft, barOnVeryRight;
3361   int top, left, height, width, sb_width, sb_left;
3362   EmacsScroller *bar;
3363 static int count = 0;
3365   /* optimization; display engine sends WAY too many of these.. */
3366   if (!NILP (window->vertical_scroll_bar))
3367     {
3368       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3369       if ([bar checkSamePosition: position portion: portion whole: whole])
3370         {
3371           if (view->scrollbarsNeedingUpdate == 0)
3372             {
3373               if (!windows_or_buffers_changed)
3374                   return;
3375             }
3376           else
3377             view->scrollbarsNeedingUpdate--;
3378         }
3379     }
3381   NSTRACE (ns_set_vertical_scroll_bar);
3383   /* Get dimensions.  */
3384   window_box (window, -1, 0, &window_y, 0, &window_height);
3385   top = window_y;
3386   height = window_height;
3387   width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3388   left = WINDOW_SCROLL_BAR_AREA_X (window);
3390   if (top < 5) /* top scrollbar adjustment */
3391     {
3392       top -= FRAME_INTERNAL_BORDER_WIDTH (f);
3393       height += FRAME_INTERNAL_BORDER_WIDTH (f);
3394     }
3396   /* allow for displaying a skinnier scrollbar than char area allotted */
3397   sb_width = (WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) > 0) ?
3398     WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) : width;
3400   barOnVeryLeft = left < 5;
3401   barOnVeryRight = FRAME_PIXEL_WIDTH (f) - left - width < 5;
3402   sb_left = left + FRAME_INTERNAL_BORDER_WIDTH (f)
3403       * (barOnVeryLeft ? -1 : (barOnVeryRight ? 1 : 0));
3405   r = NSMakeRect (sb_left, top, sb_width, height);
3406   /* the parent view is flipped, so we need to flip y value */
3407   v = [view frame];
3408   r.origin.y = (v.size.height - r.size.height - r.origin.y);
3410   XSETWINDOW (win, window);
3411   BLOCK_INPUT;
3413   /* we want at least 5 lines to display a scrollbar */
3414   if (WINDOW_TOTAL_LINES (window) < 5)
3415     {
3416       if (!NILP (window->vertical_scroll_bar))
3417         {
3418           bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3419           [bar removeFromSuperview];
3420           window->vertical_scroll_bar = Qnil;
3421         }
3422       ns_clear_frame_area (f, sb_left, top, width, height);
3423       UNBLOCK_INPUT;
3424       return;
3425     }
3427   if (NILP (window->vertical_scroll_bar))
3428     {
3429       ns_clear_frame_area (f, sb_left, top, width, height);
3430       bar = [[EmacsScroller alloc] initFrame: r window: win];
3431       window->vertical_scroll_bar = make_save_value (bar, 0);
3432     }
3433   else
3434     {
3435       NSRect oldRect;
3436       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3437       oldRect = [bar frame];
3438       r.size.width = oldRect.size.width;
3439       if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3440         {
3441           if (oldRect.origin.x != r.origin.x)
3442               ns_clear_frame_area (f, sb_left, top, width, height);
3443           [bar setFrame: r];
3444         }
3445     }
3447   [bar setPosition: position portion: portion whole: whole];
3448   UNBLOCK_INPUT;
3452 static void
3453 ns_condemn_scroll_bars (struct frame *f)
3454 /* --------------------------------------------------------------------------
3455      External (hook): arrange for all frame's scrollbars to be removed
3456      at next call to judge_scroll_bars, except for those redeemed.
3457    -------------------------------------------------------------------------- */
3459   int i;
3460   id view;
3461   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3463   NSTRACE (ns_condemn_scroll_bars);
3465   for (i =[subviews count]-1; i >= 0; i--)
3466     {
3467       view = [subviews objectAtIndex: i];
3468       if ([view isKindOfClass: [EmacsScroller class]])
3469         [view condemn];
3470     }
3474 static void
3475 ns_redeem_scroll_bar (struct window *window)
3476 /* --------------------------------------------------------------------------
3477      External (hook): arrange to spare this window's scrollbar
3478      at next call to judge_scroll_bars.
3479    -------------------------------------------------------------------------- */
3481   id bar;
3482   NSTRACE (ns_redeem_scroll_bar);
3483   if (!NILP (window->vertical_scroll_bar))
3484     {
3485       bar =XNS_SCROLL_BAR (window->vertical_scroll_bar);
3486       [bar reprieve];
3487     }
3491 static void
3492 ns_judge_scroll_bars (struct frame *f)
3493 /* --------------------------------------------------------------------------
3494      External (hook): destroy all scrollbars on frame that weren't
3495      redeemed after call to condemn_scroll_bars.
3496    -------------------------------------------------------------------------- */
3498   int i;
3499   id view;
3500   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3501   NSTRACE (ns_judge_scroll_bars);
3502   for (i =[subviews count]-1; i >= 0; i--)
3503     {
3504       view = [subviews objectAtIndex: i];
3505       if (![view isKindOfClass: [EmacsScroller class]]) continue;
3506       [view judge];
3507     }
3511 void
3512 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
3514   /* XXX irrelevant under NS */
3519 /* ==========================================================================
3521     Initialization
3523    ========================================================================== */
3526 x_display_pixel_height (dpyinfo)
3527      struct ns_display_info *dpyinfo;
3529   NSScreen *screen = [NSScreen mainScreen];
3530   return [screen frame].size.height;
3534 x_display_pixel_width (dpyinfo)
3535      struct ns_display_info *dpyinfo;
3537   NSScreen *screen = [NSScreen mainScreen];
3538   return [screen frame].size.width;
3542 static Lisp_Object ns_string_to_lispmod (const char *s)
3543 /* --------------------------------------------------------------------------
3544      Convert modifier name to lisp symbol
3545    -------------------------------------------------------------------------- */
3547   if (!strncmp (SDATA (SYMBOL_NAME (Qmeta)), s, 10))
3548     return Qmeta;
3549   else if (!strncmp (SDATA (SYMBOL_NAME (Qsuper)), s, 10))
3550     return Qsuper;
3551   else if (!strncmp (SDATA (SYMBOL_NAME (Qcontrol)), s, 10))
3552     return Qcontrol;
3553   else if (!strncmp (SDATA (SYMBOL_NAME (Qalt)), s, 10))
3554     return Qalt;
3555   else if (!strncmp (SDATA (SYMBOL_NAME (Qhyper)), s, 10))
3556     return Qhyper;
3557   else if (!strncmp (SDATA (SYMBOL_NAME (Qnone)), s, 10))
3558     return Qnone;
3559   else
3560     return Qnil;
3564 static Lisp_Object ns_mod_to_lisp (int m)
3565 /* --------------------------------------------------------------------------
3566      Convert modifier code (see lisp.h) to lisp symbol
3567    -------------------------------------------------------------------------- */
3569   if (m == CHAR_META)
3570     return Qmeta;
3571   else if (m == CHAR_SUPER)
3572     return Qsuper;
3573   else if (m == CHAR_CTL)
3574     return Qcontrol;
3575   else if (m == CHAR_ALT)
3576     return Qalt;
3577   else if (m == CHAR_HYPER)
3578     return Qhyper;
3579   else /* if (m == 0) */
3580     return Qnone;
3584 static void
3585 ns_set_default_prefs ()
3586 /* --------------------------------------------------------------------------
3587       Initialize preference variables to defaults
3588    -------------------------------------------------------------------------- */
3590   ns_alternate_modifier = Qmeta;
3591   ns_command_modifier = Qsuper;
3592   ns_control_modifier = Qcontrol;
3593   ns_function_modifier = Qnone;
3594   ns_antialias_text = Qt;
3595   ns_antialias_threshold = 10.0; /* not exposed to lisp side */
3596   ns_use_qd_smoothing = Qnil;
3597   ns_use_system_highlight_color = Qt;
3598   ns_confirm_quit = Qnil;
3602 static void
3603 ns_default (const char *parameter, Lisp_Object *result,
3604            Lisp_Object yesval, Lisp_Object noval,
3605            BOOL is_float, BOOL is_modstring)
3606 /* --------------------------------------------------------------------------
3607       Check a parameter value in user's preferences
3608    -------------------------------------------------------------------------- */
3610   const char *value;
3612   if ( (value =[[[NSUserDefaults standardUserDefaults]
3613                    stringForKey: [NSString stringWithUTF8String: parameter]]
3614                 UTF8String]) )
3615     {
3616       double f;
3617       char *pos;
3618       if (strcasecmp (value, "YES") == 0)
3619         *result = yesval;
3620       else if (strcasecmp (value, "NO") == 0)
3621         *result = noval;
3622       else if (is_float && (f = strtod (value, &pos), pos != value))
3623         *result = make_float (f);
3624       else if (is_modstring && value)
3625         *result = ns_string_to_lispmod (value);
3626       else fprintf (stderr,
3627                    "Bad value for default \"%s\": \"%s\"\n", parameter, value);
3628     }
3632 void
3633 ns_initialize_display_info (struct ns_display_info *dpyinfo)
3634 /* --------------------------------------------------------------------------
3635       Initialize global info and storage for display.
3636    -------------------------------------------------------------------------- */
3638     NSScreen *screen = [NSScreen mainScreen];
3639     NSWindowDepth depth = [screen depth];
3641     dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
3642     dpyinfo->resy = 72.27;
3643     dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
3644                                                   NSColorSpaceFromDepth (depth)]
3645                 && ![NSCalibratedWhiteColorSpace isEqualToString:
3646                                                  NSColorSpaceFromDepth (depth)];
3647     dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
3648     dpyinfo->image_cache = make_image_cache ();
3649     dpyinfo->color_table
3650       = (struct ns_color_table *)xmalloc (sizeof (struct ns_color_table));
3651     dpyinfo->color_table->colors = NULL;
3652     dpyinfo->root_window = 42; /* a placeholder.. */
3654     dpyinfo->mouse_face_mouse_frame = NULL;
3655     dpyinfo->mouse_face_deferred_gc = 0;
3656     dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
3657     dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
3658     dpyinfo->mouse_face_face_id = DEFAULT_FACE_ID;
3659     dpyinfo->mouse_face_window = dpyinfo->mouse_face_overlay = Qnil;
3660     dpyinfo->mouse_face_hidden = 0;
3662     dpyinfo->mouse_face_mouse_x = dpyinfo->mouse_face_mouse_y = 0;
3663     dpyinfo->mouse_face_defer = 0;
3665     dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
3667     dpyinfo->n_fonts = 0;
3668     dpyinfo->smallest_font_height = 1;
3669     dpyinfo->smallest_char_width = 1;
3673 /* This and next define (many of the) public functions in this file. */
3674 /* x_... are generic versions in xdisp.c that we, and other terms, get away
3675          with using despite presence in the "system dependent" redisplay
3676          interface.  In addition, many of the ns_ methods have code that is
3677          shared with all terms, indicating need for further refactoring. */
3678 extern frame_parm_handler ns_frame_parm_handlers[];
3679 static struct redisplay_interface ns_redisplay_interface =
3681   ns_frame_parm_handlers,
3682   x_produce_glyphs,
3683   x_write_glyphs,
3684   x_insert_glyphs,
3685   x_clear_end_of_line,
3686   ns_scroll_run,
3687   ns_after_update_window_line,
3688   ns_update_window_begin,
3689   ns_update_window_end,
3690   x_cursor_to,
3691   ns_flush,
3692   0, /* flush_display_optional */
3693   x_clear_window_mouse_face,
3694   x_get_glyph_overhangs,
3695   x_fix_overlapping_area,
3696   ns_draw_fringe_bitmap,
3697   0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
3698   0, /* destroy_fringe_bitmap */
3699   ns_compute_glyph_string_overhangs,
3700   ns_draw_glyph_string, /* interface to nsfont.m */
3701   ns_define_frame_cursor,
3702   ns_clear_frame_area,
3703   ns_draw_window_cursor,
3704   ns_draw_vertical_window_border,
3705   ns_shift_glyphs_for_insert
3709 static void
3710 ns_delete_display (struct ns_display_info *dpyinfo)
3712   /* TODO... */
3716 /* This function is called when the last frame on a display is deleted. */
3717 static void
3718 ns_delete_terminal (struct terminal *terminal)
3720   struct ns_display_info *dpyinfo = terminal->display_info.ns;
3721   int i;
3723   /* Protect against recursive calls.  delete_frame in
3724      delete_terminal calls us back when it deletes our last frame.  */
3725   if (!terminal->name)
3726     return;
3728   BLOCK_INPUT;
3730   x_destroy_all_bitmaps (dpyinfo);
3731   ns_delete_display (dpyinfo);
3732   UNBLOCK_INPUT;
3736 static struct terminal *
3737 ns_create_terminal (struct ns_display_info *dpyinfo)
3738 /* --------------------------------------------------------------------------
3739       Set up use of NS before we make the first connection.
3740    -------------------------------------------------------------------------- */
3742   struct terminal *terminal;
3744   NSTRACE (ns_create_terminal);
3746   terminal = create_terminal ();
3748   terminal->type = output_ns;
3749   terminal->display_info.ns = dpyinfo;
3750   dpyinfo->terminal = terminal;
3752   terminal->rif = &ns_redisplay_interface;
3754   terminal->clear_frame_hook = ns_clear_frame;
3755   terminal->ins_del_lines_hook = 0; /* XXX vestigial? */
3756   terminal->delete_glyphs_hook = 0; /* XXX vestigial? */
3757   terminal->ring_bell_hook = ns_ring_bell;
3758   terminal->reset_terminal_modes_hook = ns_reset_terminal_modes;
3759   terminal->set_terminal_modes_hook = ns_set_terminal_modes;
3760   terminal->update_begin_hook = ns_update_begin;
3761   terminal->update_end_hook = ns_update_end;
3762   terminal->set_terminal_window_hook = NULL; /* XXX vestigial? */
3763   terminal->read_socket_hook = ns_read_socket;
3764   terminal->frame_up_to_date_hook = ns_frame_up_to_date;
3765   terminal->mouse_position_hook = ns_mouse_position;
3766   terminal->frame_rehighlight_hook = ns_frame_rehighlight;
3767   terminal->frame_raise_lower_hook = ns_frame_raise_lower;
3769   terminal->fullscreen_hook = 0; /* see XTfullscreen_hook */
3771   terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
3772   terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
3773   terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
3774   terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
3776   terminal->delete_frame_hook = x_destroy_window;
3777   terminal->delete_terminal_hook = ns_delete_terminal;
3779   terminal->scroll_region_ok = 1;
3780   terminal->char_ins_del_ok = 1;
3781   terminal->line_ins_del_ok = 1;
3782   terminal->fast_clear_end_of_line = 1;
3783   terminal->memory_below_frame = 0;
3785   return terminal;
3789 struct ns_display_info *
3790 ns_term_init (Lisp_Object display_name)
3791 /* --------------------------------------------------------------------------
3792      Start the Application and get things rolling.
3793    -------------------------------------------------------------------------- */
3795   struct terminal *terminal;
3796   struct ns_display_info *dpyinfo;
3797   static int ns_initialized = 0;
3798   Lisp_Object tmp;
3800   NSTRACE (ns_term_init);
3802   /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
3803   /*GSDebugAllocationActive (YES); */
3804   BLOCK_INPUT;
3805   handling_signal = 0;
3807   if (!ns_initialized)
3808     {
3809       baud_rate = 38400;
3810       Fset_input_interrupt_mode (Qnil);
3811       ns_initialized = 1;
3812     }
3814   ns_pending_files = [[NSMutableArray alloc] init];
3815   ns_pending_service_names = [[NSMutableArray alloc] init];
3816   ns_pending_service_args = [[NSMutableArray alloc] init];
3818   /* Start app and create the main menu, window, view.
3819      Needs to be here because ns_initialize_display_info () uses AppKit classes.
3820      The view will then ask the NSApp to stop and return to Emacs. */
3821   [EmacsApp sharedApplication];
3822   if (NSApp == nil)
3823     return NULL;
3824   [NSApp setDelegate: NSApp];
3826   /* debugging: log all notifications */
3827   /*   [[NSNotificationCenter defaultCenter] addObserver: NSApp
3828                                          selector: @selector (logNotification:)
3829                                              name: nil object: nil]; */
3831   dpyinfo = (struct ns_display_info *)xmalloc (sizeof (struct ns_display_info));
3832   bzero (dpyinfo, sizeof (struct ns_display_info));
3834   ns_initialize_display_info (dpyinfo);
3835   terminal = ns_create_terminal (dpyinfo);
3837   terminal->kboard = (KBOARD *) xmalloc (sizeof (KBOARD));
3838   init_kboard (terminal->kboard);
3839   terminal->kboard->Vwindow_system = Qns;
3840   terminal->kboard->next_kboard = all_kboards;
3841   all_kboards = terminal->kboard;
3842   /* Don't let the initial kboard remain current longer than necessary.
3843      That would cause problems if a file loaded on startup tries to
3844      prompt in the mini-buffer.  */
3845   if (current_kboard == initial_kboard)
3846     current_kboard = terminal->kboard;
3847   terminal->kboard->reference_count++;
3849   dpyinfo->next = x_display_list;
3850   x_display_list = dpyinfo;
3852   /* Put it on ns_display_name_list */
3853   ns_display_name_list = Fcons (Fcons (display_name, Qnil),
3854                                 ns_display_name_list);
3855   dpyinfo->name_list_element = XCAR (ns_display_name_list);
3857   /* Set the name of the terminal. */
3858   terminal->name = (char *) xmalloc (SBYTES (display_name) + 1);
3859   strncpy (terminal->name, SDATA (display_name), SBYTES (display_name));
3860   terminal->name[SBYTES (display_name)] = 0;
3862   UNBLOCK_INPUT; 
3864   /* Read various user defaults. */
3865   ns_set_default_prefs ();
3866   if (!ns_no_defaults)
3867     {
3868       ns_default ("GSFontAntiAlias", &ns_antialias_text,
3869                  Qt, Qnil, NO, NO);
3870       tmp = Qnil;
3871       /* this is a standard variable */
3872       ns_default ("AppleAntiAliasingThreshold", &tmp,
3873                  make_float (10.0), make_float (6.0), YES, NO);
3874       ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
3875     }
3877   ns_selection_color = [[NSUserDefaults standardUserDefaults]
3878                          stringForKey: @"AppleHighlightColor"];
3879   if (ns_selection_color == nil)
3880     ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
3881   
3882   {
3883     NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
3885     if ( cl == nil )
3886       {
3887         Lisp_Object color_file, color_map, color;
3888         int r,g,b;
3889         unsigned long c;
3890         char *name;
3892         color_file = Fexpand_file_name (build_string ("rgb.txt"),
3893                          Fsymbol_value (intern ("data-directory")));
3894         if (NILP (Ffile_readable_p (color_file)))
3895           fatal ("Could not find %s.\n", SDATA (color_file));
3897         color_map = Fx_load_color_file (color_file);
3898         if (NILP (color_map))
3899           fatal ("Could not read %s.\n", SDATA (color_file));
3901         cl = [[NSColorList alloc] initWithName: @"Emacs"];
3902         for ( ; CONSP (color_map); color_map = XCDR (color_map))
3903           {
3904             color = XCAR (color_map);
3905             name = SDATA (XCAR (color));
3906             c = XINT (XCDR (color));
3907             [cl setColor:
3908                   [NSColor colorWithCalibratedRed: RED_FROM_ULONG (c) / 255.0
3909                                             green: GREEN_FROM_ULONG (c) / 255.0
3910                                              blue: BLUE_FROM_ULONG (c) / 255.0
3911                                             alpha: 1.0]
3912                   forKey: [NSString stringWithUTF8String: name]];
3913           }
3914         [cl writeToFile: nil];
3915       }
3916   }
3918   {
3919     char c[128];
3920 #ifdef NS_IMPL_GNUSTEP
3921     strncpy (c, gnustep_base_version, sizeof (c));
3922 #else
3923     /*PSnextrelease (128, c); */
3924     snprintf (c, sizeof (c), "%g", NSAppKitVersionNumber);
3925 #endif
3926     Vwindow_system_version = build_string (c);
3927   }
3929   delete_keyboard_wait_descriptor (0);
3931 /* Set up OS X app menu */
3932 #ifdef NS_IMPL_COCOA
3933   {
3934     NSMenu *appMenu;
3935     NSMenuItem *item;
3936     /* set up the application menu */
3937     svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
3938     [svcsMenu setAutoenablesItems: NO];
3939     appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
3940     [appMenu setAutoenablesItems: NO];
3941     mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
3942     dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
3944     [appMenu insertItemWithTitle: @"About Emacs"
3945                           action: @selector (orderFrontStandardAboutPanel:)
3946                    keyEquivalent: @""
3947                          atIndex: 0];
3948     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
3949     [appMenu insertItemWithTitle: @"Preferences..."
3950                           action: @selector (showPreferencesWindow:)
3951                    keyEquivalent: @","
3952                          atIndex: 2];
3953     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
3954     item = [appMenu insertItemWithTitle: @"Services"
3955                                  action: @selector (menuDown:)
3956                           keyEquivalent: @""
3957                                 atIndex: 4];
3958     [appMenu setSubmenu: svcsMenu forItem: item];
3959 /*    [svcsMenu setSupercell: item]; */
3960     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
3961     [appMenu insertItemWithTitle: @"Hide Emacs"
3962                           action: @selector (hide:)
3963                    keyEquivalent: @"h"
3964                          atIndex: 6];
3965     item =  [appMenu insertItemWithTitle: @"Hide Others"
3966                           action: @selector (hideOtherApplications:)
3967                    keyEquivalent: @"h"
3968                          atIndex: 7];
3969     [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
3970     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
3971     [appMenu insertItemWithTitle: @"Quit Emacs"
3972                           action: @selector (terminate:)
3973                    keyEquivalent: @"q"
3974                          atIndex: 9];
3976     item = [mainMenu insertItemWithTitle: @"Emacs"
3977                                   action: @selector (menuDown:)
3978                            keyEquivalent: @""
3979                                  atIndex: 0];
3980     [mainMenu setSubmenu: appMenu forItem: item];
3981     [dockMenu insertItemWithTitle: @"New Frame"
3982                            action: @selector (newFrame:)
3983                     keyEquivalent: @""
3984                           atIndex: 0];
3986     [NSApp setMainMenu: mainMenu];
3987     [NSApp setAppleMenu: appMenu];
3988     [NSApp setServicesMenu: svcsMenu];
3989     /* Needed at least on Cocoa, to get dock menu to show windows */
3990     [NSApp setWindowsMenu: [[NSMenu alloc] init]];
3991   }
3992 #endif /* MAC OS X menu setup */
3994   [NSApp run];
3996   return dpyinfo;
4000 extern Lisp_Object Vauto_save_list_file_name;
4001 void
4002 ns_term_shutdown (int sig)
4004   /* code not reached in emacs.c after this is called by shut_down_emacs: */
4005   if (STRINGP (Vauto_save_list_file_name))
4006     unlink (SDATA (Vauto_save_list_file_name));
4008   if (sig == 0 || sig == SIGTERM)
4009     {
4010       [NSApp terminate: NSApp];
4011     }
4012   else // force a stack trace to happen
4013     {
4014       abort();
4015     }
4019 /* ==========================================================================
4021     EmacsApp implementation
4023    ========================================================================== */
4026 @implementation EmacsApp
4028 - (void)logNotification: (NSNotification *)notification
4030   const char *name = [[notification name] UTF8String];
4031   if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4032       && !strstr (name, "WindowNumber"))
4033     NSLog (@"notification: '%@'", [notification name]);
4037 - (void)sendEvent: (NSEvent *)theEvent
4038 /* --------------------------------------------------------------------------
4039      Called when NSApp is running for each event received.  Used to stop
4040      the loop when we choose, since there's no way to just run one iteration.
4041    -------------------------------------------------------------------------- */
4043   int type = [theEvent type];
4044   NSWindow *window = [theEvent window];
4045 /*  NSTRACE (sendEvent); */
4046 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4048   if (type == NSCursorUpdate && window == nil)
4049     {
4050       fprintf (stderr, "Dropping external cursor update event.\n");
4051       return;
4052     }
4054 #ifdef NS_IMPL_COCOA
4055   /* pass mouse down in resize handle and subsequent drags directly to
4056      EmacsWindow so we can generate continuous redisplays */
4057   if (ns_in_resize)
4058     {
4059       if (type == NSLeftMouseDragged)
4060         {
4061           [window mouseDragged: theEvent];
4062           return;
4063         }
4064       else if (type == NSLeftMouseUp)
4065         {
4066           [window mouseUp: theEvent];
4067           return;
4068         }
4069     }
4070   else if (type == NSLeftMouseDown)
4071     {
4072       NSRect r = ns_resize_handle_rect (window);
4073       if (NSPointInRect ([theEvent locationInWindow], r))
4074         {
4075           ns_in_resize = YES;
4076           [window mouseDown: theEvent];
4077           return;
4078         }
4079     }
4080 #endif
4082   if (type == NSApplicationDefined)
4083     {
4084       /* Events posted by ns_send_appdefined interrupt the run loop here.
4085          But, if a modal window is up, an appdefined can still come through,
4086          (e.g., from a makeKeyWindow event) but stopping self also stops the
4087          modal loop. Just defer it until later. */
4088       if ([NSApp modalWindow] == nil)
4089         {
4090           last_appdefined_event = theEvent;
4091           [self stop: self];
4092         }
4093       else
4094         {
4095           send_appdefined = YES;
4096         }
4097     }
4099   [super sendEvent: theEvent];
4103 - (void)showPreferencesWindow: (id)sender
4105   struct frame *emacsframe = SELECTED_FRAME ();
4106   NSEvent *theEvent = [NSApp currentEvent];
4108   if (!emacs_event)
4109     return;
4110   emacs_event->kind = NS_NONKEY_EVENT;
4111   emacs_event->code = KEY_NS_SHOW_PREFS;
4112   emacs_event->modifiers = 0;
4113   EV_TRAILER (theEvent);
4117 - (void)newFrame: (id)sender
4119   struct frame *emacsframe = SELECTED_FRAME ();
4120   NSEvent *theEvent = [NSApp currentEvent];
4122   if (!emacs_event)
4123     return;
4124   emacs_event->kind = NS_NONKEY_EVENT;
4125   emacs_event->code = KEY_NS_NEW_FRAME;
4126   emacs_event->modifiers = 0;
4127   EV_TRAILER (theEvent);
4131 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4132 - (BOOL) openFile: (NSString *)fileName
4134   struct frame *emacsframe = SELECTED_FRAME ();
4135   NSEvent *theEvent = [NSApp currentEvent];
4137   if (!emacs_event)
4138     return NO;
4140   emacs_event->kind = NS_NONKEY_EVENT;
4141   emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4142   ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4143   ns_input_line = Qnil; /* can be start or cons start,end */
4144   emacs_event->modifiers =0;
4145   EV_TRAILER (theEvent);
4147   return YES;
4151 /* **************************************************************************
4153       EmacsApp delegate implementation
4155    ************************************************************************** */
4157 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4158 /* --------------------------------------------------------------------------
4159      When application is loaded, terminate event loop in ns_term_init
4160    -------------------------------------------------------------------------- */
4162   NSTRACE (applicationDidFinishLaunching);
4163   [NSApp setServicesProvider: NSApp];
4164   ns_send_appdefined (-2);
4168 /* Termination sequences:
4169     C-x C-c:
4170     Cmd-Q:
4171     MenuBar | File | Exit:
4172     Select Quit from App menubar:
4173         -terminate
4174         KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4175         ns_term_shutdown()
4177     Select Quit from Dock menu:
4178     Logout attempt:
4179         -appShouldTerminate
4180           Cancel -> Nothing else
4181           Accept ->
4182           
4183           -terminate
4184           KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4185           ns_term_shutdown()
4189 - (void) terminate: (id)sender
4191   struct frame *emacsframe = SELECTED_FRAME ();
4192   
4193   if (!emacs_event)
4194     return;
4195   
4196   emacs_event->kind = NS_NONKEY_EVENT;
4197   emacs_event->code = KEY_NS_POWER_OFF;
4198   emacs_event->arg = Qt; /* mark as non-key event */
4199   EV_TRAILER ((id)nil);
4203 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4205   int ret;
4207   if (NILP (ns_confirm_quit)) //   || ns_shutdown_properly  --> TO DO
4208     return NSTerminateNow;
4210     ret = NSRunAlertPanel([[NSProcessInfo processInfo] processName],
4211                           [NSString stringWithUTF8String:"Exit requested.  Would you like to Save Buffers and Exit, or Cancel the request?"],
4212                           @"Save Buffers and Exit", @"Cancel", nil);
4214     if (ret == NSAlertDefaultReturn)
4215         return NSTerminateNow;
4216     else if (ret == NSAlertAlternateReturn)
4217         return NSTerminateCancel;
4218     return NSTerminateNow;  /* just in case */
4222 /*   Notification from the Workspace to open a file */
4223 - (BOOL)application: sender openFile: (NSString *)file
4225   [ns_pending_files addObject: file];
4226   return YES;
4230 /*   Open a file as a temporary file */
4231 - (BOOL)application: sender openTempFile: (NSString *)file
4233   [ns_pending_files addObject: file];
4234   return YES;
4238 /*   Notification from the Workspace to open a file noninteractively (?) */
4239 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4241   [ns_pending_files addObject: file];
4242   return YES;
4246 /*   Notification from the Workspace to open multiple files */
4247 - (void)application: sender openFiles: (NSArray *)fileList
4249   NSEnumerator *files = [fileList objectEnumerator];
4250   NSString *file;
4251   while ((file = [files nextObject]) != nil)
4252     [ns_pending_files addObject: file];
4254 /* TODO: when GNUstep implements this (and we require that version of
4255          GNUstep), remove. */
4256 #ifndef NS_IMPL_GNUSTEP
4257   [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4258 #endif /* !NS_IMPL_GNUSTEP */
4263 /* Handle dock menu requests.  */
4264 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4266   return dockMenu;
4270 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4271 - (void)applicationWillBecomeActive: (NSNotification *)notification
4273   //ns_app_active=YES;
4275 - (void)applicationDidBecomeActive: (NSNotification *)notification
4277   //ns_app_active=YES;
4279 - (void)applicationDidResignActive: (NSNotification *)notification
4281   //ns_app_active=NO;
4282   ns_send_appdefined (-1);
4287 /* ==========================================================================
4289     EmacsApp aux handlers for managing event loop
4291    ========================================================================== */
4294 - (void)timeout_handler: (NSTimer *)timedEntry
4295 /* --------------------------------------------------------------------------
4296      The timeout specified to ns_select has passed.
4297    -------------------------------------------------------------------------- */
4299   /*NSTRACE (timeout_handler); */
4300   ns_send_appdefined (-2);
4303 extern void update_window_cursor (struct window *w, int on);
4305 - (void)fd_handler: (NSTimer *) fdEntry
4306 /* --------------------------------------------------------------------------
4307      Check data waiting on file descriptors and terminate if so
4308    -------------------------------------------------------------------------- */
4310   int result;
4311   /* NSTRACE (fd_handler); */
4313   if (select_nfds == 0)
4314     return;
4316   memcpy (&t_readfds, &select_readfds, sizeof (fd_set));
4318   select_timeout.tv_sec = select_timeout.tv_usec = 0;
4319   result = select (select_nfds, &t_readfds, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
4320                   &select_timeout);
4321   if (result)
4322     {
4323       memcpy (&select_readfds, &t_readfds, sizeof (fd_set));
4324       ns_send_appdefined (result);
4325     }
4330 /* ==========================================================================
4332     Service provision
4334    ========================================================================== */
4336 /* called from system: queue for next pass through event loop */
4337 - (void)requestService: (NSPasteboard *)pboard
4338               userData: (NSString *)userData
4339                  error: (NSString **)error
4341   [ns_pending_service_names addObject: userData];
4342   [ns_pending_service_args addObject: [NSString stringWithUTF8String:
4343       SDATA (ns_string_from_pasteboard (pboard))]];
4347 /* called from ns_read_socket to clear queue */
4348 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
4350   struct frame *emacsframe = SELECTED_FRAME ();
4351   NSEvent *theEvent = [NSApp currentEvent];
4353   if (!emacs_event)
4354     return NO;
4356   emacs_event->kind = NS_NONKEY_EVENT;
4357   emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
4358   ns_input_spi_name = build_string ([name UTF8String]);
4359   ns_input_spi_arg = build_string ([arg UTF8String]);
4360   emacs_event->modifiers = EV_MODIFIERS (theEvent);
4361   EV_TRAILER (theEvent);
4363   return YES;
4367 @end  /* EmacsApp */
4371 /* ==========================================================================
4373     EmacsView implementation
4375    ========================================================================== */
4378 @implementation EmacsView
4380 /* needed to inform when window closed from LISP */
4381 - (void) setWindowClosing: (BOOL)closing
4383   windowClosing = closing;
4387 - (void)dealloc
4389   NSTRACE (EmacsView_dealloc);
4390   [toolbar release];
4391   [super dealloc];
4395 /* called on font panel selection */
4396 - (void)changeFont: (id)sender
4398   NSEvent *e =[[self window] currentEvent];
4399   struct face *face =FRAME_DEFAULT_FACE (emacsframe);
4400   id newFont;
4401   float size;
4403   NSTRACE (changeFont);
4404   if (!emacs_event)
4405     return;
4407   if (newFont = [sender convertFont:
4408                            ((struct nsfont_info *)face->font)->nsfont])
4409     {
4410       SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
4412       emacs_event->kind = NS_NONKEY_EVENT;
4413       emacs_event->modifiers = 0;
4414       emacs_event->code = KEY_NS_CHANGE_FONT;
4416       size = [newFont pointSize];
4417       ns_input_fontsize = make_number (lrint (size));
4418       ns_input_font = build_string ([[newFont familyName] UTF8String]);
4419       EV_TRAILER (e);
4420     }
4424 - (BOOL)acceptsFirstResponder
4426   NSTRACE (acceptsFirstResponder);
4427   return YES;
4431 - (void)resetCursorRects
4433   NSRect visible = [self visibleRect];
4434   NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
4435   NSTRACE (resetCursorRects);
4437   if (currentCursor == nil)
4438     currentCursor = [NSCursor arrowCursor];
4440   if (!NSIsEmptyRect (visible))
4441     [self addCursorRect: visible cursor: currentCursor];
4442   [currentCursor setOnMouseEntered: YES];
4447 /*****************************************************************************/
4448 /* Keyboard handling. */
4449 #define NS_KEYLOG 0
4451 - (void)keyDown: (NSEvent *)theEvent
4453   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4454   int code;
4455   unsigned fnKeysym = 0;
4456   int flags;
4457   static NSMutableArray *nsEvArray;
4458   static BOOL firstTime = YES;
4460   NSTRACE (keyDown);
4462   /* Rhapsody and OS X give up and down events for the arrow keys */
4463   if (ns_fake_keydown == YES)
4464     ns_fake_keydown = NO;
4465   else if ([theEvent type] != NSKeyDown)
4466     return;
4468   if (!emacs_event)
4469     return;
4471  if (![[self window] isKeyWindow]
4472      && [[theEvent window] isKindOfClass: [EmacsWindow class]])
4473    {
4474      /* XXX: There is an occasional condition in which, when Emacs display
4475          updates a different frame from the current one, and temporarily
4476          selects it, then processes some interrupt-driven input
4477          (dispnew.c:3878), OS will send the event to the correct NSWindow, but
4478          for some reason that window has its first responder set to the NSView
4479          most recently updated (I guess), which is not the correct one. */
4480      [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
4481      return;
4482    }
4484   if (nsEvArray == nil)
4485     nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
4487   [NSCursor setHiddenUntilMouseMoves: YES];
4489   if (dpyinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
4490     {
4491       clear_mouse_face (dpyinfo);
4492       dpyinfo->mouse_face_hidden = 1;
4493     }
4495   if (!processingCompose)
4496     {
4497       code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
4498         0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
4499       /* (Carbon way: [theEvent keyCode]) */
4501       /* is it a "function key"? */
4502       fnKeysym = ns_convert_key (code);
4503       if (fnKeysym)
4504         {
4505           /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
4506              because Emacs treats Delete and KP-Delete same (in simple.el). */
4507           if (fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
4508             code = 0xFF08; /* backspace */
4509           else
4510             code = fnKeysym;
4511         }
4513       /* are there modifiers? */
4514       emacs_event->modifiers = 0;
4515       flags = [theEvent modifierFlags];
4517       if (flags & NSHelpKeyMask)
4518           emacs_event->modifiers |= hyper_modifier;
4520       if (flags & NSShiftKeyMask)
4521         emacs_event->modifiers |= shift_modifier;
4523       if (flags & NSCommandKeyMask)
4524         {
4525           emacs_event->modifiers |= parse_solitary_modifier (ns_command_modifier);
4526           /* if super (default), take input manager's word so things like
4527              dvorak / qwerty layout work */
4528           if (EQ (ns_command_modifier, Qsuper)
4529               && !fnKeysym
4530               && [[theEvent characters] length] != 0)
4531             {
4532               /* XXX: the code we get will be unshifted, so if we have
4533                  a shift modifier, must convert ourselves */
4534               if (!(flags & NSShiftKeyMask))
4535                 code = [[theEvent characters] characterAtIndex: 0];
4536 #if 0
4537               /* this is ugly and also requires linking w/Carbon framework
4538                  (for LMGetKbdType) so for now leave this rare (?) case
4539                  undealt with.. in future look into CGEvent methods */
4540               else
4541                 {
4542                   long smv = GetScriptManagerVariable (smKeyScript);
4543                   Handle uchrHandle = GetResource
4544                     ('uchr', GetScriptVariable (smv, smScriptKeys));
4545                   UInt32 dummy = 0;
4546                   UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
4547                                  [[theEvent characters] characterAtIndex: 0],
4548                                  kUCKeyActionDisplay,
4549                                  (flags & ~NSCommandKeyMask) >> 8,
4550                                  LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
4551                                  &dummy, 1, &dummy, &code);
4552                   code &= 0xFF;
4553                 }
4554 #endif
4555             }
4556         }
4558       if (flags & NSControlKeyMask)
4559           emacs_event->modifiers |=
4560             parse_solitary_modifier (ns_control_modifier);
4562       if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
4563           emacs_event->modifiers |=
4564             parse_solitary_modifier (ns_function_modifier);
4566       if (flags & NSAlternateKeyMask) /* default = meta */
4567         {
4568           if ((NILP (ns_alternate_modifier) || EQ (ns_alternate_modifier, Qnone))
4569               && !fnKeysym)
4570             {   /* accept pre-interp alt comb */
4571               if ([[theEvent characters] length] > 0)
4572                 code = [[theEvent characters] characterAtIndex: 0];
4573               /*HACK: clear lone shift modifier to stop next if from firing */
4574               if (emacs_event->modifiers == shift_modifier)
4575                 emacs_event->modifiers = 0;
4576             }
4577           else
4578               emacs_event->modifiers |=
4579                 parse_solitary_modifier (ns_alternate_modifier);
4580         }
4582   if (NS_KEYLOG)
4583     fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
4584              code, fnKeysym, flags, emacs_event->modifiers);
4586       /* if it was a function key or had modifiers, pass it directly to emacs */
4587       if (fnKeysym || (emacs_event->modifiers
4588                        && [[theEvent charactersIgnoringModifiers] length] > 0))
4589 /*[[theEvent characters] length] */
4590         {
4591           emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4592           if (code < 0x20)
4593             code |= (1<<28)|(3<<16);
4594           else if (code == 0x7f)
4595             code |= (1<<28)|(3<<16);
4596           else if (!fnKeysym)
4597             emacs_event->kind = code > 0xFF
4598               ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4600           emacs_event->code = code;
4601           EV_TRAILER (theEvent);
4602           return;
4603         }
4604     }
4606   /* if we get here we should send the key for input manager processing */
4607   if (firstTime && [[NSInputManager currentInputManager]
4608                      wantsToDelayTextChangeNotifications] == NO)
4609     fprintf (stderr,
4610           "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
4611   firstTime = NO;
4613   if (NS_KEYLOG && !processingCompose)
4614     fprintf (stderr, "keyDown: Begin compose sequence.\n");
4616   processingCompose = YES;
4617   [nsEvArray addObject: theEvent];
4618   [self interpretKeyEvents: nsEvArray];
4619   [nsEvArray removeObject: theEvent];
4623 #ifdef NS_IMPL_COCOA
4624 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
4625    decided not to send key-down for.
4626    See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
4627    If it matches one of these, send it on to keyDown. */
4628 -(void)keyUp: (NSEvent *)theEvent
4630   int flags = [theEvent modifierFlags];
4631   int code = [theEvent keyCode];
4632   if (code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
4633     {
4634       if (NS_KEYLOG)
4635         fprintf (stderr, "keyUp: passed test");
4636       ns_fake_keydown = YES;
4637       [self keyDown: theEvent];
4638     }
4640 #endif
4643 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
4646 /* <NSTextInput>: called when done composing;
4647    NOTE: also called when we delete over working text, followed immed.
4648          by doCommandBySelector: deleteBackward: */
4649 - (void)insertText: (id)aString
4651   int code;
4652   int len = [(NSString *)aString length];
4653   int i;
4655   if (NS_KEYLOG)
4656     NSLog (@"insertText '%@'\tlen = %d", aString, len);
4657   processingCompose = NO;
4659   if (!emacs_event)
4660     return;
4662   /* first, clear any working text */
4663   if (workingText != nil)
4664     [self deleteWorkingText];
4666   /* now insert the string as keystrokes */
4667   for (i =0; i<len; i++)
4668     {
4669       code = [aString characterAtIndex: i];
4670       /* TODO: still need this? */
4671       if (code == 0x2DC)
4672         code = '~'; /* 0x7E */
4673       emacs_event->modifiers = 0;
4674       emacs_event->kind
4675         = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4676       emacs_event->code = code;
4677       EV_TRAILER ((id)nil);
4678     }
4682 /* <NSTextInput>: inserts display of composing characters */
4683 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
4685   NSString *str = [aString respondsToSelector: @selector (string)] ?
4686     [aString string] : aString;
4687   if (NS_KEYLOG)
4688     NSLog (@"setMarkedText '%@' len =%d range %d from %d", str, [str length],
4689            selRange.length, selRange.location);
4691   if (workingText != nil)
4692     [self deleteWorkingText];
4693   if ([str length] == 0)
4694     return;
4696   if (!emacs_event)
4697     return;
4699   processingCompose = YES;
4700   workingText = [str copy];
4701   ns_working_text = build_string ([workingText UTF8String]);
4703   emacs_event->kind = NS_TEXT_EVENT;
4704   emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
4705   EV_TRAILER ((id)nil);
4709 /* delete display of composing characters [not in <NSTextInput>] */
4710 - (void)deleteWorkingText
4712   if (workingText == nil)
4713     return;
4714   if (NS_KEYLOG)
4715     NSLog(@"deleteWorkingText len =%d\n", [workingText length]);
4716   [workingText release];
4717   workingText = nil;
4718   processingCompose = NO;
4720   if (!emacs_event)
4721     return;
4723   emacs_event->kind = NS_TEXT_EVENT;
4724   emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
4725   EV_TRAILER ((id)nil);
4729 - (BOOL)hasMarkedText
4731   return workingText != nil;
4735 - (NSRange)markedRange
4737   NSRange rng = workingText != nil
4738     ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
4739   if (NS_KEYLOG)
4740     NSLog (@"markedRange request");
4741   return rng;
4745 - (void)unmarkText
4747   if (NS_KEYLOG)
4748     NSLog (@"unmark (accept) text");
4749   [self deleteWorkingText];
4750   processingCompose = NO;
4754 /* used to position char selection windows, etc. */
4755 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
4757   NSRect rect;
4758   NSPoint pt;
4759   struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
4760   if (NS_KEYLOG)
4761     NSLog (@"firstRectForCharRange request");
4763   rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
4764   rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
4765   pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
4766   pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
4767                                        +FRAME_LINE_HEIGHT (emacsframe));
4769   pt = [self convertPoint: pt toView: nil];
4770   pt = [[self window] convertBaseToScreen: pt];
4771   rect.origin = pt;
4772   return rect;
4776 - (NSInteger)conversationIdentifier
4778   return (NSInteger)self;
4782 - (void)doCommandBySelector: (SEL)aSelector
4784   if (NS_KEYLOG)
4785     NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
4787   if (aSelector == @selector (deleteBackward:))
4788     {
4789       /* happens when user backspaces over an ongoing composition:
4790          throw a 'delete' into the event queue */
4791       if (!emacs_event)
4792         return;
4793       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4794       emacs_event->code = 0xFF08;
4795       EV_TRAILER ((id)nil);
4796     }
4799 - (NSArray *)validAttributesForMarkedText
4801   static NSArray *arr = nil;
4802   if (arr == nil) arr = [NSArray new];
4803  /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
4804   return arr;
4807 - (NSRange)selectedRange
4809   if (NS_KEYLOG)
4810     NSLog (@"selectedRange request");
4811   return NSMakeRange (NSNotFound, 0);
4814 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
4816   if (NS_KEYLOG)
4817     NSLog (@"characterIndexForPoint request");
4818   return 0;
4821 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
4823   static NSAttributedString *str = nil;
4824   if (str == nil) str = [NSAttributedString new];
4825   if (NS_KEYLOG)
4826     NSLog (@"attributedSubstringFromRange request");
4827   return str;
4830 /* End <NSTextInput> impl. */
4831 /*****************************************************************************/
4834 /* This is what happens when the user presses a mouse button.  */
4835 - (void)mouseDown: (NSEvent *)theEvent
4837   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
4838   Lisp_Object window;
4840   NSTRACE (mouseDown);
4842   [self deleteWorkingText];
4844   if (!emacs_event)
4845     return;
4847   last_mouse_frame = emacsframe;
4848   /* appears to be needed to prevent spurious movement events generated on
4849      button clicks */
4850   last_mouse_frame->mouse_moved = 0;
4852   if ([theEvent type] == NSScrollWheel)
4853     {
4854       float delta = [theEvent deltaY];
4855       /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
4856       if (delta == 0)
4857         return;
4858       emacs_event->kind = WHEEL_EVENT;
4859       emacs_event->code = 0;
4860       emacs_event->modifiers = EV_MODIFIERS (theEvent) |
4861         ((delta > 0) ? up_modifier : down_modifier);
4862     }
4863   else
4864     {
4865       emacs_event->kind = MOUSE_CLICK_EVENT;
4866       emacs_event->code = EV_BUTTON (theEvent);
4867       emacs_event->modifiers = EV_MODIFIERS (theEvent)
4868                              | EV_UDMODIFIERS (theEvent);
4869     }
4870   XSETINT (emacs_event->x, lrint (p.x));
4871   XSETINT (emacs_event->y, lrint (p.y));
4872   EV_TRAILER (theEvent);
4876 - (void)rightMouseDown: (NSEvent *)theEvent
4878   NSTRACE (rightMouseDown);
4879   [self mouseDown: theEvent];
4883 - (void)otherMouseDown: (NSEvent *)theEvent
4885   NSTRACE (otherMouseDown);
4886   [self mouseDown: theEvent];
4890 - (void)mouseUp: (NSEvent *)theEvent
4892   NSTRACE (mouseUp);
4893   [self mouseDown: theEvent];
4897 - (void)rightMouseUp: (NSEvent *)theEvent
4899   NSTRACE (rightMouseUp);
4900   [self mouseDown: theEvent];
4904 - (void)otherMouseUp: (NSEvent *)theEvent
4906   NSTRACE (otherMouseUp);
4907   [self mouseDown: theEvent];
4911 - (void) scrollWheel: (NSEvent *)theEvent
4913   NSTRACE (scrollWheel);
4914   [self mouseDown: theEvent];
4918 /* Tell emacs the mouse has moved. */
4919 - (void)mouseMoved: (NSEvent *)e
4921   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4922   Lisp_Object frame;
4924 //  NSTRACE (mouseMoved);
4926   last_mouse_movement_time = EV_TIMESTAMP (e);
4927   last_mouse_motion_position
4928     = [self convertPoint: [e locationInWindow] fromView: nil];
4930   /* update any mouse face */
4931   if (dpyinfo->mouse_face_hidden)
4932     {
4933       dpyinfo->mouse_face_hidden = 0;
4934       clear_mouse_face (dpyinfo);
4935     }
4937   /* tooltip handling */
4938   previous_help_echo_string = help_echo_string;
4939   help_echo_string = Qnil;
4941   if (!note_mouse_movement (emacsframe, last_mouse_motion_position.x,
4942                             last_mouse_motion_position.y))
4943     help_echo_string = previous_help_echo_string;
4945   XSETFRAME (frame, emacsframe);
4946   if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
4947     {
4948       /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
4949          (note_mouse_highlight), which is called through the
4950          note_mouse_movement () call above */
4951       gen_help_event (help_echo_string, frame, help_echo_window,
4952                       help_echo_object, help_echo_pos);
4953     }
4954   else
4955     {
4956       help_echo_string = Qnil;
4957       gen_help_event (Qnil, frame, Qnil, Qnil, 0);
4958     }
4960   if (emacsframe->mouse_moved && send_appdefined)
4961     ns_send_appdefined (-1);
4965 - (void)mouseDragged: (NSEvent *)e
4967   NSTRACE (mouseDragged);
4968   [self mouseMoved: e];
4972 - (void)rightMouseDragged: (NSEvent *)e
4974   NSTRACE (rightMouseDragged);
4975   [self mouseMoved: e];
4979 - (void)otherMouseDragged: (NSEvent *)e
4981   NSTRACE (otherMouseDragged);
4982   [self mouseMoved: e];
4986 - (BOOL)windowShouldClose: (id)sender
4988   NSEvent *e =[[self window] currentEvent];
4990   NSTRACE (windowShouldClose);
4991   windowClosing = YES;
4992   if (!emacs_event)
4993     return NO;
4994   emacs_event->kind = DELETE_WINDOW_EVENT;
4995   emacs_event->modifiers = 0;
4996   emacs_event->code = 0;
4997   EV_TRAILER (e);
4998   /* Don't close this window, let this be done from lisp code.  */
4999   return NO;
5003 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
5004 /* normalize frame to gridded text size */
5006   NSTRACE (windowWillResize);
5007 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
5009   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe,
5010 #ifdef NS_IMPL_GNUSTEP
5011                                         frameSize.width + 3);
5012 #else
5013                                         frameSize.width);
5014 #endif
5015   if (cols < MINWIDTH)
5016     cols = MINWIDTH;
5017   frameSize.width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (emacsframe, cols);
5019   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, frameSize.height
5020 #ifdef NS_IMPL_GNUSTEP
5021       - FRAME_NS_TITLEBAR_HEIGHT (emacsframe) + 3
5022         - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
5023 #else
5024       - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5025         - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
5026 #endif
5027   if (rows < MINHEIGHT)
5028     rows = MINHEIGHT;
5029   frameSize.height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows)
5030                        + FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5031                        + FRAME_NS_TOOLBAR_HEIGHT (emacsframe);
5032 #ifdef NS_IMPL_COCOA
5033   {
5034     /* this sets window title to have size in it; the wm does this under GS */
5035     NSRect r = [[self window] frame];
5036     if (r.size.height == frameSize.height && r.size.width == frameSize.width)
5037       {
5038         if (old_title != 0)
5039           {
5040             xfree (old_title);
5041             old_title = 0;
5042           }
5043       }
5044     else
5045       {
5046         char *size_title;
5047         NSWindow *window = [self window];
5048         if (old_title == 0)
5049           {
5050             const char *t = [[[self window] title] UTF8String];
5051             char *pos = strstr (t, "  â€”  ");
5052             if (pos)
5053               *pos = '\0';
5054             old_title = (char *) xmalloc (strlen (t) + 1);
5055             strcpy (old_title, t);
5056           }
5057         size_title = xmalloc (strlen (old_title) + 40);
5058         sprintf (size_title, "%s  â€”  (%d x %d)", old_title, cols, rows);
5059         [window setTitle: [NSString stringWithUTF8String: size_title]];
5060         [window display];
5061         xfree (size_title);
5062       }
5063   }
5064 #endif /* NS_IMPL_COCOA */
5065 /*fprintf (stderr,"    ...size became %.0f x %.0f  (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
5067   return frameSize;
5071 - (void)windowDidResize: (NSNotification *)notification
5073   NSWindow *theWindow = [notification object];
5075 #ifdef NS_IMPL_GNUSTEP
5076    /* in GNUstep, at least currently, it's possible to get a didResize
5077       without getting a willResize.. therefore we need to act as if we got
5078       the willResize now */
5079   NSSize sz = [theWindow frame].size;
5080   sz = [self windowWillResize: theWindow toSize: sz];
5081 #endif /* NS_IMPL_GNUSTEP */
5083   NSTRACE (windowDidResize);
5084 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
5086 #ifdef NS_IMPL_COCOA
5087   if (old_title != 0)
5088     {
5089       xfree (old_title);
5090       old_title = 0;
5091     }
5092 #endif /* NS_IMPL_COCOA */
5094   // Calling x_set_window_size tends to get us into inf-loops
5095   // (x_set_window_size causes a resize which causes
5096   // a "windowDidResize" which calls x_set_window_size).
5097   // At least with GNUStep, don't know about MacOSX.  --Stef
5098 #ifndef NS_IMPL_GNUSTEP
5099   if (cols > 0 && rows > 0)
5100      x_set_window_size (emacsframe, 0, cols, rows);
5101 #endif
5103   ns_send_appdefined (-1);
5107 - (void)windowDidBecomeKey: (NSNotification *)notification
5108 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5110   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5111   struct frame *old_focus = dpyinfo->x_focus_frame;
5113   NSTRACE (windowDidBecomeKey);
5115   if (emacsframe != old_focus)
5116     dpyinfo->x_focus_frame = emacsframe;
5118   ns_frame_rehighlight (emacsframe);
5120   if (emacs_event)
5121     {
5122       emacs_event->kind = FOCUS_IN_EVENT;
5123       EV_TRAILER ((id)nil);
5124     }
5128 - (void)windowDidResignKey: (NSNotification *)notification
5129 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5131   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5132   NSTRACE (windowDidResignKey);
5134   if (dpyinfo->x_focus_frame == emacsframe)
5135     dpyinfo->x_focus_frame = 0;
5137   ns_frame_rehighlight (emacsframe);
5139   /* FIXME: for some reason needed on second and subsequent clicks away
5140             from sole-frame Emacs to get hollow box to show */
5141   if (!windowClosing && [[self window] isVisible] == YES)
5142     {
5143       x_update_cursor (emacsframe, 1);
5144       x_set_frame_alpha (emacsframe);
5145     }
5147   if (emacs_event)
5148     {
5149       [self deleteWorkingText];
5150       emacs_event->kind = FOCUS_IN_EVENT;
5151       EV_TRAILER ((id)nil);
5152     }
5156 - (void)windowWillMiniaturize: sender
5158   NSTRACE (windowWillMiniaturize);
5162 - (BOOL)isFlipped
5164   return YES;
5168 - (BOOL)isOpaque
5170   return NO;
5174 - initFrameFromEmacs: (struct frame *)f
5176   NSRect r, wr;
5177   Lisp_Object tem;
5178   NSWindow *win;
5179   NSButton *toggleButton;
5180   int vbextra = NS_SCROLL_BAR_WIDTH (f);
5181   NSSize sz;
5182   NSColor *col;
5183   NSString *name;
5185   NSTRACE (initFrameFromEmacs);
5187   windowClosing = NO;
5188   processingCompose = NO;
5189   scrollbarsNeedingUpdate = 0;
5191 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
5193   r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
5194                  FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
5195   [self initWithFrame: r];
5197   FRAME_NS_VIEW (f) = self;
5198   emacsframe = f;
5199   old_title = 0;
5201   win = [[EmacsWindow alloc]
5202             initWithContentRect: r
5203                       styleMask: (NSResizableWindowMask |
5204                                   NSMiniaturizableWindowMask |
5205                                   NSClosableWindowMask)
5206                         backing: NSBackingStoreBuffered
5207                           defer: YES];
5209   wr = [win frame];
5210   f->border_width = wr.size.width - r.size.width;
5211   FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
5213   [win setAcceptsMouseMovedEvents: YES];
5214   [win setDelegate: self];
5215   [win useOptimizedDrawing: YES];
5217   sz.width = FRAME_COLUMN_WIDTH (f);
5218   sz.height = FRAME_LINE_HEIGHT (f);
5219   [win setResizeIncrements: sz];
5221   [[win contentView] addSubview: self];
5223   if (ns_drag_types)
5224     [self registerForDraggedTypes: ns_drag_types];
5226   tem = f->name;
5227   name = [NSString stringWithUTF8String:
5228                    NILP (tem) ? (unsigned char *)"Emacs" : SDATA (tem)];
5229   [win setTitle: name];
5231   /* toolbar support */
5232   toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
5233                          [NSString stringWithFormat: @"Emacs Frame %d",
5234                                    ns_window_num]];
5235   [win setToolbar: toolbar];
5236   [toolbar setVisible: NO];
5237 #ifdef NS_IMPL_COCOA
5238   toggleButton = [win standardWindowButton: NSWindowToolbarButton];
5239   [toggleButton setTarget: self];
5240   [toggleButton setAction: @selector (toggleToolbar: )];
5241 #endif
5242   FRAME_NS_TOOLBAR_HEIGHT (f) = 0;
5244   tem = f->icon_name;
5245   if (!NILP (tem))
5246     [win setMiniwindowTitle:
5247            [NSString stringWithUTF8String: SDATA (tem)]];
5249   {
5250     NSScreen *screen = [win screen];
5252     if (screen != 0)
5253       [win setFrameTopLeftPoint: NSMakePoint
5254            (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
5255             IN_BOUND (-SCREENMAX,
5256                      [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
5257   }
5259   [win makeFirstResponder: self];
5261   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5262                                   (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
5263   [win setBackgroundColor: col];
5264   if ([col alphaComponent] != 1.0)
5265     [win setOpaque: NO];
5267   [self allocateGState];
5269   ns_window_num++;
5270   return self;
5274 - (void)windowDidMove: sender
5276   NSWindow *win = [self window];
5277   NSRect r = [win frame];
5278   NSScreen *screen = [win screen];
5279   NSRect sr = [screen frame];
5281   NSTRACE (windowDidMove);
5283   if (!emacsframe->output_data.ns)
5284     return;
5285   if (screen != nil)
5286     {
5287       emacsframe->left_pos = r.origin.x; /* - sr.origin.x; */
5288       emacsframe->top_pos = sr.size.height -
5289         (r.origin.y + r.size.height); /* + sr.origin.y; */
5290     }
5293 #ifdef NS_IMPL_COCOA
5294 /* if we don't do this manually, the window will resize but not move */
5295 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
5297   NSTRACE (windowShouldZoom);
5298   [[self window] setFrame: newFrame display: NO];
5299   return YES;
5301 #endif
5304 /* Override to do something slightly nonstandard, but nice.  First click on
5305    zoom button will zoom vertically.  Second will zoom completely.  Third
5306    returns to original. */
5307 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
5308                         defaultFrame:(NSRect)defaultFrame
5310   NSRect result = [sender frame];
5311   NSTRACE (windowWillUseStandardFrame);
5313   if (result.size.height == defaultFrame.size.height) {
5314     result = defaultFrame;
5315   } else {
5316     result.size.height = defaultFrame.size.height;
5317     result.origin.y = defaultFrame.origin.y;
5318   }
5320   /* A windowWillResize does not get generated at least on Tiger. */
5321   [self windowWillResize: sender toSize: result.size];
5322   return result;
5326 - (void)windowDidDeminiaturize: sender
5328   NSTRACE (windowDidDeminiaturize);
5329   if (!emacsframe->output_data.ns)
5330     return;
5331   emacsframe->async_iconified = 0;
5332   emacsframe->async_visible   = 1;
5333   windows_or_buffers_changed++;
5335   if (emacs_event)
5336     {
5337       emacs_event->kind = ICONIFY_EVENT;
5338       EV_TRAILER ((id)nil);
5339     }
5343 - (void)windowDidExpose: sender
5345   NSTRACE (windowDidExpose);
5346   if (!emacsframe->output_data.ns)
5347     return;
5348   emacsframe->async_visible = 1;
5349   SET_FRAME_GARBAGED (emacsframe);
5351   if (send_appdefined)
5352     ns_send_appdefined (-1);
5356 - (void)windowDidMiniaturize: sender
5358   NSTRACE (windowDidMiniaturize);
5359   if (!emacsframe->output_data.ns)
5360     return;
5362   emacsframe->async_iconified = 1;
5363   emacsframe->async_visible = 0;
5365   if (emacs_event)
5366     {
5367       emacs_event->kind = ICONIFY_EVENT;
5368       EV_TRAILER ((id)nil);
5369     }
5373 - (void)mouseEntered: (NSEvent *)theEvent
5375   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5376   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5377   NSTRACE (mouseEntered);
5379   last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5383 - (void)mouseExited: (NSEvent *)theEvent
5385   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5386   NSRect r;
5387   struct ns_display_info *dpyinfo
5388     = emacsframe ? FRAME_NS_DISPLAY_INFO (emacsframe) : NULL;
5390   NSTRACE (mouseExited);
5392   if (dpyinfo || !emacsframe)
5393     return;
5395   last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5397   if (emacsframe == dpyinfo->mouse_face_mouse_frame)
5398     {
5399       clear_mouse_face (dpyinfo);
5400       dpyinfo->mouse_face_mouse_frame = 0;
5401     }
5405 - menuDown: sender
5407   NSTRACE (menuDown);
5408   if (context_menu_value == -1)
5409     context_menu_value = [sender tag];
5410   else
5411     find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
5412                                   emacsframe->menu_bar_vector,
5413                                   (void *)[sender tag]);
5414   ns_send_appdefined (-1);
5415   return self;
5419 - (EmacsToolbar *)toolbar
5421   return toolbar;
5425 /* this gets called on toolbar button click */
5426 - toolbarClicked: (id)item
5428   NSEvent *theEvent;
5429   int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
5431   NSTRACE (toolbarClicked);
5433   if (!emacs_event)
5434     return self;
5436   /* send first event (for some reason two needed) */
5437   theEvent = [[self window] currentEvent];
5438   emacs_event->kind = TOOL_BAR_EVENT;
5439   XSETFRAME (emacs_event->arg, emacsframe);
5440   EV_TRAILER (theEvent);
5442   emacs_event->kind = TOOL_BAR_EVENT;
5443 /*   XSETINT (emacs_event->code, 0); */
5444   emacs_event->arg = AREF (emacsframe->tool_bar_items,
5445                           idx + TOOL_BAR_ITEM_KEY);
5446   emacs_event->modifiers = EV_MODIFIERS (theEvent);
5447   EV_TRAILER (theEvent);
5448   return self;
5452 - toggleToolbar: (id)sender
5454   if (!emacs_event)
5455     return self;
5457   emacs_event->kind = NS_NONKEY_EVENT;
5458   emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
5459   EV_TRAILER ((id)nil);
5460   return self;
5464 - (void)drawRect: (NSRect)rect
5466   int x = NSMinX (rect), y = NSMinY (rect);
5467   int width = NSWidth (rect), height = NSHeight (rect);
5469   NSTRACE (drawRect);
5471   if (!emacsframe || !emacsframe->output_data.ns || ns_in_resize)
5472     return;
5474   ns_clear_frame_area (emacsframe, x, y, width, height);
5475   expose_frame (emacsframe, x, y, width, height);
5477   /*
5478     drawRect: may be called (at least in OS X 10.5) for invisible
5479     views as well for some reason.  Thus, do not infer visibility 
5480     here.
5482     emacsframe->async_visible = 1;
5483     emacsframe->async_iconified = 0;
5484   */
5488 /* NSDraggingDestination protocol methods.  Actually this is not really a
5489    protocol, but a category of Object.  O well...  */
5491 -(unsigned int) draggingEntered: (id <NSDraggingInfo>) sender
5493   NSTRACE (draggingEntered);
5494   return NSDragOperationGeneric;
5498 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
5500   return YES;
5504 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
5506   id pb;
5507   int x, y;
5508   NSString *type;
5509   NSEvent *theEvent = [[self window] currentEvent];
5510   NSPoint position;
5512   NSTRACE (performDragOperation);
5514   if (!emacs_event)
5515     return;
5517   position = [self convertPoint: [sender draggingLocation] fromView: nil];
5518   x = lrint (position.x);  y = lrint (position.y);
5520   pb = [sender draggingPasteboard];
5521   type = [pb availableTypeFromArray: ns_drag_types];
5522   if (type == 0)
5523     {
5524       return NO;
5525     }
5526   else if ([type isEqualToString: NSFilenamesPboardType])
5527     {
5528       NSArray *files;
5529       NSEnumerator *fenum;
5530       NSString *file;
5532       if (!(files = [pb propertyListForType: type]))
5533         return NO;
5535       fenum = [files objectEnumerator];
5536       while ( (file = [fenum nextObject]) )
5537         {
5538           emacs_event->kind = NS_NONKEY_EVENT;
5539           emacs_event->code = KEY_NS_DRAG_FILE;
5540           XSETINT (emacs_event->x, x);
5541           XSETINT (emacs_event->y, y);
5542           ns_input_file = append2 (ns_input_file,
5543                                    build_string ([file UTF8String]));
5544           emacs_event->modifiers = EV_MODIFIERS (theEvent);
5545           EV_TRAILER (theEvent);
5546         }
5547       return YES;
5548     }
5549   else if ([type isEqualToString: NSURLPboardType])
5550     {
5551       NSString *file;
5552       NSURL *fileURL;
5554       if (!(fileURL = [NSURL URLFromPasteboard: pb]) ||
5555           [fileURL isFileURL] == NO)
5556         return NO;
5558       file = [fileURL path];
5559       emacs_event->kind = NS_NONKEY_EVENT;
5560       emacs_event->code = KEY_NS_DRAG_FILE;
5561       XSETINT (emacs_event->x, x);
5562       XSETINT (emacs_event->y, y);
5563       ns_input_file = append2 (ns_input_file, build_string ([file UTF8String]));
5564       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5565       EV_TRAILER (theEvent);
5566       return YES;
5567     }
5568   else if ([type isEqualToString: NSStringPboardType]
5569            || [type isEqualToString: NSTabularTextPboardType])
5570     {
5571       NSString *data;
5573       if (! (data = [pb stringForType: type]))
5574         return NO;
5576       emacs_event->kind = NS_NONKEY_EVENT;
5577       emacs_event->code = KEY_NS_DRAG_TEXT;
5578       XSETINT (emacs_event->x, x);
5579       XSETINT (emacs_event->y, y);
5580       ns_input_text = build_string ([data UTF8String]);
5581       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5582       EV_TRAILER (theEvent);
5583       return YES;
5584     }
5585   else if ([type isEqualToString: NSColorPboardType])
5586     {
5587       NSColor *c = [NSColor colorFromPasteboard: pb];
5588       emacs_event->kind = NS_NONKEY_EVENT;
5589       emacs_event->code = KEY_NS_DRAG_COLOR;
5590       XSETINT (emacs_event->x, x);
5591       XSETINT (emacs_event->y, y);
5592       ns_input_color = ns_color_to_lisp (c);
5593       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5594       EV_TRAILER (theEvent);
5595       return YES;
5596     }
5597   else if ([type isEqualToString: NSFontPboardType])
5598     {
5599       /* impl based on GNUstep NSTextView.m */
5600       NSData *data = [pb dataForType: NSFontPboardType];
5601       NSDictionary *dict = [NSUnarchiver unarchiveObjectWithData: data];
5602       NSFont *font = [dict objectForKey: NSFontAttributeName];
5603       char fontSize[10];
5605       if (font == nil)
5606         return NO;
5608       emacs_event->kind = NS_NONKEY_EVENT;
5609       emacs_event->code = KEY_NS_CHANGE_FONT;
5610       XSETINT (emacs_event->x, x);
5611       XSETINT (emacs_event->y, y);
5612       ns_input_font = build_string ([[font fontName] UTF8String]);
5613       snprintf (fontSize, 10, "%f", [font pointSize]);
5614       ns_input_fontsize = build_string (fontSize);
5615       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5616       EV_TRAILER (theEvent);
5617       return YES;
5618     }
5619   else
5620     {
5621       error ("Invalid data type in dragging pasteboard.");
5622       return NO;
5623     }
5627 - validRequestorForSendType: (NSString *)typeSent
5628                  returnType: (NSString *)typeReturned
5630   NSTRACE (validRequestorForSendType);
5631   if ([ns_send_types indexOfObjectIdenticalTo: typeSent] != NSNotFound &&
5632       [ns_return_types indexOfObjectIdenticalTo: typeSent] != NSNotFound)
5633     return self;
5635   return [super validRequestorForSendType: typeSent
5636                                returnType: typeReturned];
5640 /* The next two methods are part of NSServicesRequests informal protocol,
5641    supposedly called when a services menu item is chosen from this app.
5642    But this should not happen because we override the services menu with our
5643    own entries which call ns-perform-service.
5644    Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
5645    So let's at least stub them out until further investigation can be done. */
5647 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
5649   /* we could call ns_string_from_pasteboard(pboard) here but then it should
5650      be written into the buffer in place of the existing selection..
5651      ordinary service calls go through functions defined in ns-win.el */
5652   return NO;
5655 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
5657   /* supposed to write for as many of types as we are able */
5658   return NO;
5662 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
5663    (gives a miniaturized version of the window); currently we use the latter for
5664    frames whose active buffer doesn't correspond to any file
5665    (e.g., '*scratch*') */
5666 - setMiniwindowImage: (BOOL) setMini
5668   id image = [[self window] miniwindowImage];
5669   NSTRACE (setMiniwindowImage);
5671   /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
5672      about "AppleDockIconEnabled" notwithstanding, however the set message
5673      below has its effect nonetheless. */
5674   if (image != emacsframe->output_data.ns->miniimage)
5675     {
5676       if (image && [image isKindOfClass: [EmacsImage class]])
5677         [image release];
5678       [[self window] setMiniwindowImage:
5679                        setMini ? emacsframe->output_data.ns->miniimage : nil];
5680     }
5682   return self;
5686 - (void) setRows: (int) r andColumns: (int) c
5688   rows = r;
5689   cols = c;
5692 @end  /* EmacsView */
5696 /* ==========================================================================
5698     EmacsWindow implementation
5700    ========================================================================== */
5702 @implementation EmacsWindow
5704 /* called only on resize clicks by special case in EmacsApp-sendEvent */
5705 - (void)mouseDown: (NSEvent *)theEvent
5707   if (ns_in_resize)
5708     {
5709       NSSize size = [[theEvent window] frame].size;
5710       grabOffset = [theEvent locationInWindow];
5711       grabOffset.x = size.width - grabOffset.x;
5712     }
5713   else
5714     [super mouseDown: theEvent];
5718 /* stop resizing */
5719 - (void)mouseUp: (NSEvent *)theEvent
5721   if (ns_in_resize)
5722     {
5723       struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
5724       ns_in_resize = NO;
5725       ns_set_name_as_filename (f);
5726       [self display];
5727       ns_send_appdefined (-1);
5728     }
5729   else
5730     [super mouseUp: theEvent];
5734 /* send resize events */
5735 - (void)mouseDragged: (NSEvent *)theEvent
5737   if (ns_in_resize)
5738     {
5739       NSPoint p = [theEvent locationInWindow];
5740       NSSize size, vettedSize, origSize = [self frame].size;
5742       size.width = p.x + grabOffset.x;
5743       size.height = origSize.height - p.y + grabOffset.y;
5745       if (size.width == origSize.width && size.height == origSize.height)
5746         return;
5748       vettedSize = [[self delegate] windowWillResize: self toSize: size];
5749       if (vettedSize.width != size.width || vettedSize.height != size.height)
5750         {
5751           [[NSNotificationCenter defaultCenter]
5752             postNotificationName: NSWindowDidResizeNotification
5753                           object: self];
5754         }
5755     }
5756   else
5757     [super mouseDragged: theEvent];
5760 @end /* EmacsWindow */
5763 /* ==========================================================================
5765     EmacsScroller implementation
5767    ========================================================================== */
5770 @implementation EmacsScroller
5772 /* for repeat button push */
5773 #define SCROLL_BAR_FIRST_DELAY 0.5
5774 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
5776 + (float) scrollerWidth
5778   /* TODO: if we want to allow variable widths, this is the place to do it,
5779            however neither GNUstep nor Cocoa support it very well */
5780   return [NSScroller scrollerWidth];
5784 - initFrame: (NSRect )r window: (Lisp_Object)nwin
5786   NSTRACE (EmacsScroller_initFrame);
5788   r.size.width = [EmacsScroller scrollerWidth];
5789   [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
5790   [self setContinuous: YES];
5791   [self setEnabled: YES];
5793   /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
5794      locked against the right, top and bottom edges. */
5795   [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
5797   win = nwin;
5798   condemned = NO;
5799   pixel_height = NSHeight (r);
5800   min_portion = 20 / pixel_height;
5802   frame = XFRAME (XWINDOW (win)->frame);
5803   if (FRAME_LIVE_P (frame))
5804     {
5805       int i;
5806       EmacsView *view = FRAME_NS_VIEW (frame);
5807       NSView *sview = [[view window] contentView];
5808       NSArray *subs = [sview subviews];
5810       /* disable optimization stopping redraw of other scrollbars */
5811       view->scrollbarsNeedingUpdate = 0;
5812       for (i =[subs count]-1; i >= 0; i--)
5813         if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
5814           view->scrollbarsNeedingUpdate++;
5815       [sview addSubview: self];
5816     }
5818 /*  [self setFrame: r]; */
5820   return self;
5824 - (void)setFrame: (NSRect)newRect
5826   NSTRACE (EmacsScroller_setFrame);
5827 /*  BLOCK_INPUT; */
5828   pixel_height = NSHeight (newRect);
5829   min_portion = 20 / pixel_height;
5830   [super setFrame: newRect];
5831   [self display];
5832 /*  UNBLOCK_INPUT; */
5836 - (void)dealloc
5838   NSTRACE (EmacsScroller_dealloc);
5839   if (!NILP (win))
5840     XWINDOW (win)->vertical_scroll_bar = Qnil;
5841   [super dealloc];
5845 - condemn
5847   NSTRACE (condemn);
5848   condemned =YES;
5849   return self;
5853 - reprieve
5855   NSTRACE (reprieve);
5856   condemned =NO;
5857   return self;
5861 - judge
5863   NSTRACE (judge);
5864   if (condemned)
5865     {
5866       BLOCK_INPUT;
5867       /* ensure other scrollbar updates after deletion */
5868       EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
5869       if (view != nil)
5870         view->scrollbarsNeedingUpdate++;
5871       [self removeFromSuperview];
5872       [self release];
5873       UNBLOCK_INPUT;
5874     }
5875   return self;
5879 - (void)resetCursorRects
5881   NSRect visible = [self visibleRect];
5882   NSTRACE (resetCursorRects);
5884   if (!NSIsEmptyRect (visible))
5885     [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
5886   [[NSCursor arrowCursor] setOnMouseEntered: YES];
5890 - (int) checkSamePosition: (int) position portion: (int) portion
5891                     whole: (int) whole
5893   return em_position ==position && em_portion ==portion && em_whole ==whole
5894     && portion != whole; /* needed for resize empty buf */
5898 - setPosition: (int)position portion: (int)portion whole: (int)whole
5900   NSTRACE (setPosition);
5902   em_position = position;
5903   em_portion = portion;
5904   em_whole = whole;
5906   if (portion >= whole)
5907     [self setFloatValue: 0.0 knobProportion: 1.0];
5908   else
5909     {
5910       float pos, por;
5911       portion = max ((float)whole*min_portion/pixel_height, portion);
5912       pos = (float)position / (whole - portion);
5913       por = (float)portion/whole;
5914       [self setFloatValue: pos knobProportion: por];
5915     }
5916 #ifdef NS_IMPL_GNUSTEP
5917   [self display];
5918 #endif
5919   return self;
5922 /* FIXME: unused at moment (see ns_mouse_position) at the moment because
5923      drag events will go directly to the EmacsScroller.  Leaving in for now. */
5924 -(void)getMouseMotionPart: (int *)part window: (Lisp_Object *)window
5925                         x: (Lisp_Object *)x y: ( Lisp_Object *)y
5927   *part = last_hit_part;
5928   *window = win;
5929   XSETINT (*y, pixel_height);
5930   if ([self floatValue] > 0.999)
5931     XSETINT (*x, pixel_height);
5932   else
5933     XSETINT (*x, pixel_height * [self floatValue]);
5937 /* set up emacs_event */
5938 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
5940   if (!emacs_event)
5941     return;
5943   emacs_event->part = last_hit_part;
5944   emacs_event->code = 0;
5945   emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
5946   emacs_event->frame_or_window = win;
5947   emacs_event->timestamp = EV_TIMESTAMP (e);
5948   emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
5949   emacs_event->arg = Qnil;
5950   XSETINT (emacs_event->x, loc * pixel_height);
5951   XSETINT (emacs_event->y, pixel_height-20);
5953   n_emacs_events_pending++;
5954   kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
5955   EVENT_INIT (*emacs_event);
5956   ns_send_appdefined (-1);
5960 /* called manually thru timer to implement repeated button action w/hold-down */
5961 - repeatScroll: (NSTimer *)scrollEntry
5963   NSEvent *e = [[self window] currentEvent];
5964   NSPoint p =  [[self window] mouseLocationOutsideOfEventStream];
5965   BOOL inKnob = [self testPart: p] == NSScrollerKnob;
5967   /* clear timer if need be */
5968   if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
5969     {
5970         [scroll_repeat_entry invalidate];
5971         [scroll_repeat_entry release];
5972         scroll_repeat_entry = nil;
5974         if (inKnob)
5975           return self;
5977         scroll_repeat_entry
5978           = [[NSTimer scheduledTimerWithTimeInterval:
5979                         SCROLL_BAR_CONTINUOUS_DELAY
5980                                             target: self
5981                                           selector: @selector (repeatScroll:)
5982                                           userInfo: 0
5983                                            repeats: YES]
5984               retain];
5985     }
5987   [self sendScrollEventAtLoc: 0 fromEvent: e];
5988   return self;
5992 /* Asynchronous mouse tracking for scroller.  This allows us to dispatch
5993    mouseDragged events without going into a modal loop. */
5994 - (void)mouseDown: (NSEvent *)e
5996   NSRect sr, kr;
5997   /* hitPart is only updated AFTER event is passed on */
5998   NSScrollerPart part = [self testPart: [e locationInWindow]];
5999   double inc = 0.0, loc, kloc, pos;
6000   int edge = 0;
6002   NSTRACE (EmacsScroller_mouseDown);
6004   switch (part)
6005     {
6006     case NSScrollerDecrementPage:
6007         last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
6008     case NSScrollerIncrementPage:
6009         last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
6010     case NSScrollerDecrementLine:
6011       last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
6012     case NSScrollerIncrementLine:
6013       last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
6014     case NSScrollerKnob:
6015       last_hit_part = scroll_bar_handle; break;
6016     case NSScrollerKnobSlot:  /* GNUstep-only */
6017       last_hit_part = scroll_bar_move_ratio; break;
6018     default:  /* NSScrollerNoPart? */
6019       fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %d\n", part);
6020       return;
6021     }
6023   if (inc != 0.0)
6024     {
6025       pos = 0;      /* ignored */
6027       /* set a timer to repeat, as we can't let superclass do this modally */
6028       scroll_repeat_entry
6029         = [[NSTimer scheduledTimerWithTimeInterval: 0.5
6030                                             target: self
6031                                           selector: @selector (repeatScroll:)
6032                                           userInfo: 0
6033                                            repeats: YES]
6034             retain];
6035     }
6036   else
6037     {
6038       /* handle, or on GNUstep possibly slot */
6039       NSEvent *fake_event;
6041       /* compute float loc in slot and mouse offset on knob */
6042       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6043                       toView: nil];
6044       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6045       if (loc <= 0.0)
6046         {
6047           loc = 0.0;
6048           edge = -1;
6049         }
6050       else if (loc >= NSHeight (sr))
6051         {
6052           loc = NSHeight (sr);
6053           edge = 1;
6054         }
6056       if (edge)
6057         kloc = 0.5 * edge;
6058       else
6059         {
6060           kr = [self convertRect: [self rectForPart: NSScrollerKnob]
6061                           toView: nil];
6062           kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
6063         }
6064       last_mouse_offset = kloc;
6066       /* if knob, tell emacs a location offset by knob pos
6067          (to indicate top of handle) */
6068       if (part == NSScrollerKnob)
6069           pos = (loc - last_mouse_offset) / NSHeight (sr);
6070       else
6071         /* else this is a slot click on GNUstep: go straight there */
6072         pos = loc / NSHeight (sr);
6074       /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
6075       fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
6076                                       location: [e locationInWindow]
6077                                  modifierFlags: [e modifierFlags]
6078                                      timestamp: [e timestamp]
6079                                   windowNumber: [e windowNumber]
6080                                        context: [e context]
6081                                    eventNumber: [e eventNumber]
6082                                     clickCount: [e clickCount]
6083                                       pressure: [e pressure]];
6084       [super mouseUp: fake_event];
6085     }
6087   if (part != NSScrollerKnob)
6088     [self sendScrollEventAtLoc: pos fromEvent: e];
6092 /* Called as we manually track scroller drags, rather than superclass. */
6093 - (void)mouseDragged: (NSEvent *)e
6095     NSRect sr;
6096     double loc, pos;
6097     int edge = 0;
6099     NSTRACE (EmacsScroller_mouseDragged);
6101       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6102                       toView: nil];
6103       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6105       if (loc <= 0.0)
6106         {
6107           loc = 0.0;
6108           edge = -1;
6109         }
6110       else if (loc >= NSHeight (sr) + last_mouse_offset)
6111         {
6112           loc = NSHeight (sr) + last_mouse_offset;
6113           edge = 1;
6114         }
6116       pos = /*(edge ? loc :*/ (loc - last_mouse_offset) / NSHeight (sr);
6117       [self sendScrollEventAtLoc: pos fromEvent: e];
6121 - (void)mouseUp: (NSEvent *)e
6123   if (scroll_repeat_entry)
6124     {
6125       [scroll_repeat_entry invalidate];
6126       [scroll_repeat_entry release];
6127       scroll_repeat_entry = nil;
6128     }
6129   last_hit_part = 0;
6133 /* treat scrollwheel events in the bar as though they were in the main window */
6134 - (void) scrollWheel: (NSEvent *)theEvent
6136   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
6137   [view mouseDown: theEvent];
6140 @end  /* EmacsScroller */
6145 /* ==========================================================================
6147    Font-related functions; these used to be in nsfaces.m
6149    ========================================================================== */
6152 Lisp_Object
6153 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
6155   struct font *font = XFONT_OBJECT (font_object);
6157   if (fontset < 0)
6158     fontset = fontset_from_font (font_object);
6159   FRAME_FONTSET (f) = fontset;
6161   if (FRAME_FONT (f) == font)
6162     /* This font is already set in frame F.  There's nothing more to
6163        do.  */
6164     return font_object;
6166   FRAME_FONT (f) = font;
6168   FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
6169   FRAME_COLUMN_WIDTH (f) = font->average_width;
6170   FRAME_SPACE_WIDTH (f) = font->space_width;
6171   FRAME_LINE_HEIGHT (f) = font->height;
6173   compute_fringe_widths (f, 1);
6175   /* Compute the scroll bar width in character columns.  */
6176   if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
6177     {
6178       int wid = FRAME_COLUMN_WIDTH (f);
6179       FRAME_CONFIG_SCROLL_BAR_COLS (f)
6180         = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
6181     }
6182   else
6183     {
6184       int wid = FRAME_COLUMN_WIDTH (f);
6185       FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
6186     }
6188   /* Now make the frame display the given font.  */
6189   if (FRAME_NS_WINDOW (f) != 0)
6190         x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
6192   return font_object;
6196 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
6197 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
6198          in 1.43. */
6200 const char *
6201 ns_xlfd_to_fontname (const char *xlfd)
6202 /* --------------------------------------------------------------------------
6203     Convert an X font name (XLFD) to an NS font name.
6204     Only family is used.
6205     The string returned is temporarily allocated.
6206    -------------------------------------------------------------------------- */
6208   char *name = xmalloc (180);
6209   int i, len;
6210   const char *ret;
6212   if (!strncmp (xlfd, "--", 2))
6213     sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
6214   else
6215     sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
6217   /* stopgap for malformed XLFD input */
6218   if (strlen (name) == 0)
6219     strcpy (name, "Monaco");
6221   /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
6222      also uppercase after '-' or ' ' */
6223   name[0] = toupper (name[0]);
6224   for (len =strlen (name), i =0; i<len; i++)
6225     {
6226       if (name[i] == '$')
6227         {
6228           name[i] = '-';
6229           if (i+1<len)
6230             name[i+1] = toupper (name[i+1]);
6231         }
6232       else if (name[i] == '_')
6233         {
6234           name[i] = ' ';
6235           if (i+1<len)
6236             name[i+1] = toupper (name[i+1]);
6237         }
6238     }
6239 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name);  */
6240   ret = [[NSString stringWithUTF8String: name] UTF8String];
6241   xfree (name);
6242   return ret;
6246 void
6247 syms_of_nsterm ()
6249   NSTRACE (syms_of_nsterm);
6250   DEFVAR_LISP ("ns-input-file", &ns_input_file,
6251               "The file specified in the last NS event.");
6252   ns_input_file =Qnil;
6254   DEFVAR_LISP ("ns-input-text", &ns_input_text,
6255               "The data received in the last NS text drag event.");
6256   ns_input_text =Qnil;
6258   DEFVAR_LISP ("ns-working-text", &ns_working_text,
6259               "String for visualizing working composition sequence.");
6260   ns_working_text =Qnil;
6262   DEFVAR_LISP ("ns-input-font", &ns_input_font,
6263               "The font specified in the last NS event.");
6264   ns_input_font =Qnil;
6266   DEFVAR_LISP ("ns-input-fontsize", &ns_input_fontsize,
6267               "The fontsize specified in the last NS event.");
6268   ns_input_fontsize =Qnil;
6270   DEFVAR_LISP ("ns-input-line", &ns_input_line,
6271                "The line specified in the last NS event.");
6272   ns_input_line =Qnil;
6274   DEFVAR_LISP ("ns-input-color", &ns_input_color,
6275                "The color specified in the last NS event.");
6276   ns_input_color =Qnil;
6278   DEFVAR_LISP ("ns-input-spi-name", &ns_input_spi_name,
6279                "The service name specified in the last NS event.");
6280   ns_input_spi_name =Qnil;
6282   DEFVAR_LISP ("ns-input-spi-arg", &ns_input_spi_arg,
6283                "The service argument specified in the last NS event.");
6284   ns_input_spi_arg =Qnil;
6286   DEFVAR_LISP ("ns-alternate-modifier", &ns_alternate_modifier,
6287                "This variable describes the behavior of the alternate or option key.\n\
6288 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6289 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6290 at all, allowing it to be used at a lower level for accented character entry.");
6292   DEFVAR_LISP ("ns-command-modifier", &ns_command_modifier,
6293                "This variable describes the behavior of the command key.\n\
6294 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6296   DEFVAR_LISP ("ns-control-modifier", &ns_control_modifier,
6297                "This variable describes the behavior of the control key.\n\
6298 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6300   DEFVAR_LISP ("ns-function-modifier", &ns_function_modifier,
6301                "This variable describes the behavior of the function key (on laptops).\n\
6302 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6303 Set to none means that the function key is not interpreted by Emacs at all,\n\
6304 allowing it to be used at a lower level for accented character entry.");
6306   DEFVAR_LISP ("ns-antialias-text", &ns_antialias_text,
6307                "Non-nil (the default) means to render text antialiased. Only has an effect on OS X Panther and above.");
6309   DEFVAR_LISP ("ns-use-qd-smoothing", &ns_use_qd_smoothing,
6310                "Whether to render text using QuickDraw (less heavy) antialiasing. Only has an effect on OS X Panther and above.  Default is nil (use Quartz smoothing).");
6312   DEFVAR_LISP ("ns-use-system-highlight-color",
6313                &ns_use_system_highlight_color,
6314                "Whether to use the system default (on OS X only) for the highlight color.  Nil means to use standard emacs (prior to version 21) 'grey'.");
6316   DEFVAR_LISP ("ns-confirm-quit", &ns_confirm_quit,
6317                "Whether to confirm application quit using dialog.");
6319   staticpro (&ns_display_name_list);
6320   ns_display_name_list = Qnil;
6322   staticpro (&last_mouse_motion_frame);
6323   last_mouse_motion_frame = Qnil;
6325   /* from 23+ we need to tell emacs what modifiers there are.. */
6326   Qmodifier_value = intern ("modifier-value");
6327   Qalt = intern ("alt");
6328   Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
6329   Qhyper = intern ("hyper");
6330   Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
6331   Qmeta = intern ("meta");
6332   Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
6333   Qsuper = intern ("super");
6334   Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
6335   Qcontrol = intern ("control");
6336   Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
6338   /* TODO: move to common code */
6339   DEFVAR_LISP ("x-toolkit-scroll-bars", &Vx_toolkit_scroll_bars,
6340                doc: /* If not nil, Emacs uses toolkit scroll bars.  */);
6341 #ifdef USE_TOOLKIT_SCROLL_BARS
6342   Vx_toolkit_scroll_bars = Qt;
6343 #else
6344   Vx_toolkit_scroll_bars = Qnil;
6345 #endif
6347   /* these are unsupported but we need the declarations to avoid whining
6348      messages from cus-start.el */
6349   DEFVAR_BOOL ("x-use-underline-position-properties",
6350                &x_use_underline_position_properties,
6351      doc: /* NOT SUPPORTED UNDER NS.
6352 *Non-nil means make use of UNDERLINE_POSITION font properties.
6353 A value of nil means ignore them.  If you encounter fonts with bogus
6354 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
6355 to 4.1, set this to nil.
6357 NOTE: Not supported on Mac yet.  */);
6358   x_use_underline_position_properties = 0;
6360   DEFVAR_BOOL ("x-underline-at-descent-line",
6361                &x_underline_at_descent_line,
6362      doc: /* NOT SUPPORTED UNDER NS.
6363 *Non-nil means to draw the underline at the same place as the descent line.
6364 A value of nil means to draw the underline according to the value of the
6365 variable `x-use-underline-position-properties', which is usually at the
6366 baseline level.  The default value is nil.  */);
6367   x_underline_at_descent_line = 0;
6369   /* Tell emacs about this window system. */
6370   Fprovide (intern ("ns"), Qnil);
6374 // arch-tag: 6eaa8f7d-a69b-4e1c-b43d-ab31defbe0d2