(mh-mm-merge-handles)
[emacs.git] / src / nsterm.m
blob91dd37e30435f46777f6340ba0c3eae4979bd1b2
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 <unistd.h>
37 #include "lisp.h"
38 #include "blockinput.h"
39 #include "sysselect.h"
40 #include "nsterm.h"
41 #include "systime.h"
42 #include "character.h"
43 #include "fontset.h"
44 #include "composite.h"
45 #include "ccl.h"
47 #include "termhooks.h"
48 #include "termopts.h"
49 #include "termchar.h"
51 #include "window.h"
52 #include "keyboard.h"
54 #include "font.h"
56 /* call tracing */
57 #if 0
58 int term_trace_num = 0;
59 #define NSTRACE(x)        fprintf (stderr, "%s:%d: [%d] " #x "\n",         \
60                                 __FILE__, __LINE__, ++term_trace_num)
61 #else
62 #define NSTRACE(x)
63 #endif
66 /* ==========================================================================
68     Local declarations
70    ========================================================================== */
72 /* Convert a symbol indexed with an NSxxx value to a value as defined
73    in keyboard.c (lispy_function_key). I hope this is a correct way
74    of doing things... */
75 static unsigned convert_ns_to_X_keysym[] =
77   NSHomeFunctionKey,            0x50,
78   NSLeftArrowFunctionKey,       0x51,
79   NSUpArrowFunctionKey,         0x52,
80   NSRightArrowFunctionKey,      0x53,
81   NSDownArrowFunctionKey,       0x54,
82   NSPageUpFunctionKey,          0x55,
83   NSPageDownFunctionKey,        0x56,
84   NSEndFunctionKey,             0x57,
85   NSBeginFunctionKey,           0x58,
86   NSSelectFunctionKey,          0x60,
87   NSPrintFunctionKey,           0x61,
88   NSExecuteFunctionKey,         0x62,
89   NSInsertFunctionKey,          0x63,
90   NSUndoFunctionKey,            0x65,
91   NSRedoFunctionKey,            0x66,
92   NSMenuFunctionKey,            0x67,
93   NSFindFunctionKey,            0x68,
94   NSHelpFunctionKey,            0x6A,
95   NSBreakFunctionKey,           0x6B,
97   NSF1FunctionKey,              0xBE,
98   NSF2FunctionKey,              0xBF,
99   NSF3FunctionKey,              0xC0,
100   NSF4FunctionKey,              0xC1,
101   NSF5FunctionKey,              0xC2,
102   NSF6FunctionKey,              0xC3,
103   NSF7FunctionKey,              0xC4,
104   NSF8FunctionKey,              0xC5,
105   NSF9FunctionKey,              0xC6,
106   NSF10FunctionKey,             0xC7,
107   NSF11FunctionKey,             0xC8,
108   NSF12FunctionKey,             0xC9,
109   NSF13FunctionKey,             0xCA,
110   NSF14FunctionKey,             0xCB,
111   NSF15FunctionKey,             0xCC,
113   NSBackspaceCharacter,         0x08,  /* 8: Not on some KBs. */
114   NSDeleteCharacter,            0xFF,  /* 127: Big 'delete' key upper right. */
115   NSDeleteFunctionKey,          0x9F,  /* 63272: Del forw key off main array. */
117   NSTabCharacter,               0x09,
118   0x19,                         0x09,  /* left tab->regular since pass shift */
119   NSCarriageReturnCharacter,    0x0D,
120   NSNewlineCharacter,           0x0D,
121   NSEnterCharacter,             0x8D,
123   0x1B,                         0x1B   /* escape */
127 /* Lisp communications */
128 Lisp_Object ns_input_file, ns_input_font, ns_input_fontsize, ns_input_line;
129 Lisp_Object ns_input_color, ns_input_text, ns_working_text;
130 Lisp_Object ns_input_spi_name, ns_input_spi_arg;
131 Lisp_Object Vx_toolkit_scroll_bars;
132 static Lisp_Object Qmodifier_value;
133 /* TODO: unsure why these defined in term files, anyway we need in keymap.c */
134 Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper;
135 extern Lisp_Object Qcursor_color, Qcursor_type, Qns;
138 EmacsPrefsController *prefsController;
140 /* Preferences equivalent to those set by X resources under X are managed
141    through the OpenStep defaults system.  These pertain to behavior of the
142    graphical interface components.  The one difference from X is that the
143    values below are SET when the user chooses save-options. This makes
144    things easier for users, but sometimes violates expectations when some
145    user-set options appear when running under -q/Q.  Therefore we depart
146    from X behavior and refuse to read defaults when started under these
147    options. */
149 /* Set in emacs.c. */
150 char ns_no_defaults;
152 /* Specifies which emacs modifier should be generated when NS receives
153    the Alternate modifer.  May be Qnone or any of the modifier lisp symbols. */
154 Lisp_Object ns_alternate_modifier;
156 /* Specifies which emacs modifier should be generated when NS receives
157    the Command modifer.  May be any of the modifier lisp symbols. */
158 Lisp_Object ns_command_modifier;
160 /* Specifies which emacs modifier should be generated when NS receives
161    the Control modifer.  May be any of the modifier lisp symbols. */
162 Lisp_Object ns_control_modifier;
164 /* Specifies which emacs modifier should be generated when NS receives
165    the Function modifer (laptops).  May be any of the modifier lisp symbols. */
166 Lisp_Object ns_function_modifier;
168 /* A floating point value specifying vertical stretch (positive) or shrink
169   (negative) of text line spacing.  Zero means default spacing.
170   YES indicates 0.5, NO indicates 0.0. */
171 Lisp_Object ns_expand_space;
173 /* Control via default 'GSFontAntiAlias' on OS X and GNUstep. */
174 Lisp_Object ns_antialias_text;
176 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
177    the maximum font size to NOT antialias.  On GNUstep there is currently
178    no way to control this behavior. */
179 float ns_antialias_threshold;
181 /* Controls use of an undocumented CG function to do Quickdraw-style font
182    smoothing (less heavy) instead of regular Quartz smoothing. */
183 Lisp_Object ns_use_qd_smoothing;
185 /* Used to pick up AppleHighlightColor on OS X */
186 Lisp_Object ns_use_system_highlight_color;
187 NSString *ns_selection_color;
190 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
192 /* Display variables */
193 struct ns_display_info *x_display_list; /* Chain of existing displays */
194 Lisp_Object ns_display_name_list;
195 long context_menu_value = 0;
197 /* display update */
198 NSPoint last_mouse_motion_position;
199 static NSRect last_mouse_glyph;
200 static unsigned long last_mouse_movement_time = 0;
201 static Lisp_Object last_mouse_motion_frame;
202 static EmacsScroller *last_mouse_scroll_bar = nil;
203 static struct frame *ns_updating_frame;
204 static NSView *focus_view = NULL;
205 static int ns_window_num =0;
206 static NSRect uRect;
207 static BOOL gsaved = NO;
208 BOOL ns_in_resize = NO;
209 static BOOL ns_fake_keydown = NO;
210 int ns_tmp_flags; /* FIXME */
211 struct nsfont_info *ns_tmp_font; /* FIXME */
212 /*static int debug_lock = 0; */
214 #ifdef NS_IMPL_COCOA
215 /* This undocumented Quartz function controls how fonts are anti-aliased.
216    (Found from code in Mac wxWindows impl, discovered by running `nm' on
217    the "QD" framework.)
218    Mode 0 is normal anti-aliasing, mode 1 is no anti-aliasing, and mode 2 is
219    4-bit pixel-aligned anti-aliasing (the old QuickDraw standard). */
220 extern void CGContextSetFontRenderingMode (CGContextRef cg, int v);
221 #endif
224 /* event loop */
225 static BOOL send_appdefined = YES;
226 static NSEvent *last_appdefined_event = 0;
227 static NSTimer *timed_entry = 0;
228 static NSTimer *fd_entry = nil;
229 static NSTimer *scroll_repeat_entry = nil;
230 static fd_set select_readfds, t_readfds;
231 static struct timeval select_timeout;
232 static int select_nfds;
233 static NSAutoreleasePool *outerpool;
234 static BOOL ns_shutdown_properly = NO;
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           /* XXX: cacheImageInRect under GNUstep does not account for
846              offset in x_set_window_size, so overestimate (4 fine on Cocoa) */
847           surr = NSInsetRect (r, -10, -10);
848           ns_focus (frame, &surr, 1);
849           [[view window] cacheImageInRect: surr];
850           [ns_lookup_indexed_color (NS_FACE_FOREGROUND
851                                       (FRAME_DEFAULT_FACE (frame)), frame) set];
852           NSRectFill (r);
853           [[view window] flushWindow];
854           ns_timeout (150000);
855           [[view window] restoreCachedImage];
856           [[view window] flushWindow];
857           ns_unfocus (frame);
858         }
859       [pool release];
860       UNBLOCK_INPUT;
861     }
862   else
863     {
864       NSBeep ();
865     }
869 static void
870 ns_reset_terminal_modes (struct terminal *terminal)
871 /*  Externally called as hook */
873   NSTRACE (ns_reset_terminal_modes);
876 static void
877 ns_set_terminal_modes (struct terminal *terminal)
878 /*  Externally called as hook */
880   NSTRACE (ns_set_terminal_modes);
885 /* ==========================================================================
887     Frame / window manager related functions
889    ========================================================================== */
892 static void
893 ns_raise_frame (struct frame *f)
894 /* --------------------------------------------------------------------------
895      Bring window to foreground and make it active
896    -------------------------------------------------------------------------- */
898   NSView *view = FRAME_NS_VIEW (f);
899   check_ns ();
900   BLOCK_INPUT;
901   [[view window] makeKeyAndOrderFront: NSApp];
902   UNBLOCK_INPUT;
906 static void
907 ns_lower_frame (struct frame *f)
908 /* --------------------------------------------------------------------------
909      Send window to back
910    -------------------------------------------------------------------------- */
912   NSView *view = FRAME_NS_VIEW (f);
913   check_ns ();
914   BLOCK_INPUT;
915   [[view window] orderBack: NSApp];
916   UNBLOCK_INPUT;
920 static void
921 ns_frame_raise_lower (struct frame *f, int raise)
922 /* --------------------------------------------------------------------------
923      External (hook)
924    -------------------------------------------------------------------------- */
926   NSTRACE (ns_frame_raise_lower);
928   if (raise)
929     ns_raise_frame (f);
930   else
931     ns_lower_frame (f);
935 static void
936 ns_frame_rehighlight (struct frame *frame)
937 /* --------------------------------------------------------------------------
938      External (hook): called on things like window switching within frame
939    -------------------------------------------------------------------------- */
941   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
942   struct frame *old_highlight = dpyinfo->x_highlight_frame;
944   NSTRACE (ns_frame_rehighlight);
945   if (dpyinfo->x_focus_frame)
946     {
947       dpyinfo->x_highlight_frame
948         = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
949            ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
950            : dpyinfo->x_focus_frame);
951       if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
952         {
953           FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
954           dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
955         }
956     }
957   else
958       dpyinfo->x_highlight_frame = 0;
960   if (dpyinfo->x_highlight_frame &&
961          dpyinfo->x_highlight_frame != old_highlight)
962     {
963       if (old_highlight)
964         {
965           x_update_cursor (old_highlight, 1);
966           x_set_frame_alpha (old_highlight);
967         }
968       if (dpyinfo->x_highlight_frame)
969         {
970           x_update_cursor (dpyinfo->x_highlight_frame, 1);
971           x_set_frame_alpha (dpyinfo->x_highlight_frame);
972         }
973     }
977 void
978 x_make_frame_visible (struct frame *f)
979 /* --------------------------------------------------------------------------
980      External: Show the window (X11 semantics)
981    -------------------------------------------------------------------------- */
983   NSTRACE (x_make_frame_visible);
984   /* XXX: at some points in past this was not needed, as the only place that
985      called this (frame.c:Fraise_frame ()) also called raise_lower;
986      if this ends up the case again, comment this out again. */
987   if (!FRAME_VISIBLE_P (f))
988     ns_raise_frame (f);
992 void
993 x_make_frame_invisible (struct frame *f)
994 /* --------------------------------------------------------------------------
995      External: Hide the window (X11 semantics)
996    -------------------------------------------------------------------------- */
998   NSView * view = FRAME_NS_VIEW (f);
999   NSTRACE (x_make_frame_invisible);
1000   check_ns ();
1001   [[view window] orderOut: NSApp];
1005 void
1006 x_iconify_frame (struct frame *f)
1007 /* --------------------------------------------------------------------------
1008      External: Iconify window
1009    -------------------------------------------------------------------------- */
1011   NSView * view = FRAME_NS_VIEW (f);
1012   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1013   NSTRACE (x_iconify_frame);
1014   check_ns ();
1016   if (dpyinfo->x_highlight_frame == f)
1017     dpyinfo->x_highlight_frame = 0;
1019   if ([[view window] windowNumber] <= 0)
1020     {
1021       /* the window is still deferred.  Make it very small, bring it
1022          on screen and order it out. */
1023       NSRect s = { { 100, 100}, {0, 0} };
1024       NSRect t;
1025       t = [[view window] frame];
1026       [[view window] setFrame: s display: NO];
1027       [[view window] orderBack: NSApp];
1028       [[view window] orderOut: NSApp];
1029       [[view window] setFrame: t display: NO];
1030     }
1031   [[view window] miniaturize: NSApp];
1035 void
1036 x_destroy_window (struct frame *f)
1037 /* --------------------------------------------------------------------------
1038      External: Delete the window
1039    -------------------------------------------------------------------------- */
1041   NSView *view = FRAME_NS_VIEW (f);
1042   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1043   NSTRACE (x_destroy_window);
1044   check_ns ();
1046   [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1048   BLOCK_INPUT;
1050   free_frame_menubar (f);
1052   if (FRAME_FACE_CACHE (f))
1053     free_frame_faces (f);
1055   if (f == dpyinfo->x_focus_frame)
1056     dpyinfo->x_focus_frame = 0;
1057   if (f == dpyinfo->x_highlight_frame)
1058     dpyinfo->x_highlight_frame = 0;
1059   if (f == dpyinfo->mouse_face_mouse_frame)
1060     {
1061       dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
1062       dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
1063       dpyinfo->mouse_face_window = Qnil;
1064       dpyinfo->mouse_face_deferred_gc = 0;
1065       dpyinfo->mouse_face_mouse_frame = 0;
1066     }
1068   xfree (f->output_data.ns);
1070   [[view window] close];
1071   [view release];
1073   ns_window_num--;
1074   UNBLOCK_INPUT;
1078 void
1079 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1080 /* --------------------------------------------------------------------------
1081      External: Position the window
1082    -------------------------------------------------------------------------- */
1084   NSScreen *screen;
1085   NSView *view = FRAME_NS_VIEW (f);
1087   NSTRACE (x_set_offset);
1089   BLOCK_INPUT;
1091   f->left_pos = xoff;
1092   f->top_pos = yoff;
1093 #ifdef NS_IMPL_GNUSTEP
1094   if (xoff < 100)
1095     f->left_pos = 100;  /* don't overlap menu */
1096 #endif
1097   if (view != nil && (screen = [[view window] screen]))
1098     [[view window] setFrameTopLeftPoint:
1099         NSMakePoint (SCREENMAXBOUND (f->left_pos),
1100                      SCREENMAXBOUND ([screen frame].size.height
1101                                      - NS_TOP_POS (f)))];
1102   UNBLOCK_INPUT;
1106 void
1107 x_set_window_size (struct frame *f, int change_grav, int cols, int rows)
1108 /* --------------------------------------------------------------------------
1109      Adjust window pixel size based on given character grid size
1110      Impl is a bit more complex than other terms, need to do some
1111      internal clipping and also pay attention to screen constraints.
1112    -------------------------------------------------------------------------- */
1114   EmacsView *view = FRAME_NS_VIEW (f);
1115   EmacsToolbar *toolbar = [view toolbar];
1116   NSWindow *window = [view window];
1117   NSScreen *screen = [window screen];
1118   NSRect wr = [window frame];
1119   int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1120   int pixelwidth, pixelheight;
1121   static int oldRows, oldCols, oldFontWidth, oldFontHeight;
1122   static int oldTB;
1123   static struct frame *oldF;
1125   NSTRACE (x_set_window_size);
1127   if (view == nil ||
1128       (f == oldF
1129        && rows == oldRows && cols == oldCols
1130        && oldFontWidth == FRAME_COLUMN_WIDTH (f)
1131        && oldFontHeight == FRAME_LINE_HEIGHT (f)
1132        && oldTB == tb))
1133     return;
1135 /*fprintf (stderr, "\tsetWindowSize: %d x %d, font size %d x %d\n", cols, rows, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f)); */
1137   BLOCK_INPUT;
1139   check_frame_size (f, &rows, &cols);
1140   oldF = f;
1141   oldRows = rows;
1142   oldCols = cols;
1143   oldFontWidth = FRAME_COLUMN_WIDTH (f);
1144   oldFontHeight = FRAME_LINE_HEIGHT (f);
1145   oldTB = tb;
1147   f->scroll_bar_actual_width = NS_SCROLL_BAR_WIDTH (f);
1148   compute_fringe_widths (f, 0);
1150   pixelwidth =  FRAME_TEXT_COLS_TO_PIXEL_WIDTH   (f, cols);
1151   pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
1153   /* If we have a change in toolbar display, calculate height */
1154   if (tb)
1155     /* XXX: GNUstep has not yet implemented the first method below, added
1156            in Panther, however the second is incorrect under Cocoa. */
1157 #ifdef NS_IMPL_GNUSTEP
1158     FRAME_NS_TOOLBAR_HEIGHT (f)
1159       = NSHeight ([NSWindow frameRectForContentRect: NSMakeRect (0, 0, 0, 0)
1160                             styleMask: [window styleMask]])
1161         - FRAME_NS_TITLEBAR_HEIGHT (f);
1162 #else
1163     FRAME_NS_TOOLBAR_HEIGHT (f) = 32;
1164       /* actually get wrong result here if toolbar not yet displayed
1165          NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1166          - FRAME_NS_TITLEBAR_HEIGHT (f); */
1167 #endif
1168   else
1169     FRAME_NS_TOOLBAR_HEIGHT (f) = 0;
1171   wr.size.width = pixelwidth + f->border_width;
1172   wr.size.height = pixelheight + FRAME_NS_TITLEBAR_HEIGHT (f) 
1173                   + FRAME_NS_TOOLBAR_HEIGHT (f);
1175   /* constrain to screen if we can */
1176   if (screen)
1177     {
1178       NSSize sz = [screen visibleFrame].size;
1179       NSSize ez = { wr.size.width - sz.width, wr.size.height - sz.height };
1180       if (ez.width > 0)
1181         {
1182           int cr = ez.width / FRAME_COLUMN_WIDTH (f) + 1;
1183           cols -= cr;
1184           oldCols = cols;
1185           wr.size.width -= cr * FRAME_COLUMN_WIDTH (f);
1186           pixelwidth -= cr * FRAME_COLUMN_WIDTH (f);
1187         }
1188       if (ez.height > 0)
1189         {
1190           int rr = ez.height / FRAME_LINE_HEIGHT (f) + 1;
1191           rows -= rr;
1192           oldRows = rows;
1193           wr.size.height -= rr * FRAME_LINE_HEIGHT (f);
1194           pixelheight -= rr * FRAME_LINE_HEIGHT (f);
1195         }
1196       wr.origin.x = f->left_pos;
1197       wr.origin.y = [screen frame].size.height - NS_TOP_POS (f)
1198         - wr.size.height;
1199     }
1201   [view setRows: rows andColumns: cols];
1202   [window setFrame: wr display: YES];
1204 /*fprintf (stderr, "\tx_set_window_size %d, %d\t%d, %d\n", cols, rows, pixelwidth, pixelheight); */
1206   /* This is a trick to compensate for Emacs' managing the scrollbar area
1207      as a fixed number of standard character columns.  Instead of leaving
1208      blank space for the extra, we chopped it off above.  Now for
1209      left-hand scrollbars, we shift all rendering to the left by the
1210      difference between the real width and Emacs' imagined one.  For
1211      right-hand bars, don't worry about it since the extra is never used.
1212      (Obviously doesn't work for vertically split windows tho..) */
1213   NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1214     ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1215                   - NS_SCROLL_BAR_WIDTH (f), 0)
1216     : NSMakePoint (0, 0);
1217   [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1218   [view setBoundsOrigin: origin];
1220   change_frame_size (f, rows, cols, 0, 1, 0); /* pretend, delay, safe */
1221   FRAME_PIXEL_WIDTH (f) = pixelwidth;
1222   FRAME_PIXEL_HEIGHT (f) = pixelheight;
1223 /*  SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */
1225   mark_window_cursors_off (XWINDOW (f->root_window));
1226   cancel_mouse_face (f);
1228   UNBLOCK_INPUT;
1233 /* ==========================================================================
1235     Color management
1237    ========================================================================== */
1240 NSColor *
1241 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1243   struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1244   return color_table->colors[idx];
1248 unsigned long
1249 ns_index_color (NSColor *color, struct frame *f)
1251   struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1252   int idx;
1253   NSNumber *index;
1255   if (!color_table->colors)
1256     {
1257       color_table->size = NS_COLOR_CAPACITY;
1258       color_table->avail = 1; /* skip idx=0 as marker */
1259       color_table->colors
1260         = (NSColor **)xmalloc (color_table->size * sizeof (NSColor *));
1261       color_table->empty_indices = [[NSMutableSet alloc] init];
1262     }
1264   /* do we already have this color ? */
1265   {
1266     int i;
1267     for (i = 1; i < color_table->avail; i++)
1268       {
1269         if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1270           {
1271             [color_table->colors[i] retain];
1272             return i;
1273           }
1274       }
1275   }
1277   if ([color_table->empty_indices count] > 0)
1278     {
1279       index = [color_table->empty_indices anyObject];
1280       [color_table->empty_indices removeObject: index];
1281       idx = [index unsignedIntValue];
1282     }
1283   else
1284     {
1285       if (color_table->avail == color_table->size)
1286         {
1287           color_table->size += NS_COLOR_CAPACITY;
1288           color_table->colors
1289             = (NSColor **)xrealloc (color_table->colors,
1290                                     color_table->size * sizeof (NSColor *));
1291         }
1292       idx = color_table->avail++;
1293     }
1295   color_table->colors[idx] = color;
1296   [color retain];
1297 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1298   return idx;
1302 void
1303 ns_free_indexed_color (unsigned long idx, struct frame *f)
1305   struct ns_color_table *color_table;
1306   NSColor *color;
1307   NSNumber *index;
1309   if (!f)
1310     return;
1312   color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1314   if (idx <= 0 || idx >= color_table->size) {
1315     message1("ns_free_indexed_color: Color index out of range.\n");
1316     return;
1317   }
1319   index = [NSNumber numberWithUnsignedInt: idx];
1320   if ([color_table->empty_indices containsObject: index]) {
1321     message1("ns_free_indexed_color: attempt to free already freed color.\n");
1322     return;
1323   }
1325   color = color_table->colors[idx];
1326   [color release];
1327   color_table->colors[idx] = nil;
1328   [color_table->empty_indices addObject: [NSNumber numberWithUnsignedInt: idx]];
1329 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1333 static int
1334 ns_get_color (const char *name, NSColor **col)
1335 /* --------------------------------------------------------------------------
1336      Parse a color name
1337 /* --------------------------------------------------------------------------
1338 /* On *Step, we recognize several color formats, in addition to a catalog
1339    of colors found in the file Emacs.clr. Color formats include:
1340    - #rrggbb or RGBrrggbb where rr, gg, bb specify red, green and blue in hex
1341    - ARGBaarrggbb is similar, with aa being the alpha channel (FF = opaque)
1342    - HSVhhssvv and AHSVaahhssvv (or HSB/AHSB) are similar for hue, saturation,
1343      value;
1344    - CMYKccmmyykk is similar for cyan, magenta, yellow, black. */
1346   NSColor * new = nil;
1347   const char *hex = NULL;
1348   enum { rgb, argb, hsv, ahsv, cmyk, gray } color_space;
1349   NSString *nsname = [NSString stringWithUTF8String: name];
1351 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1352   BLOCK_INPUT;
1354   if ([nsname isEqualToString: @"ns_selection_color"])
1355     {
1356       nsname = ns_selection_color;
1357       name = [ns_selection_color UTF8String];
1358     }
1360   if (name[0] == '0' || name[0] == '1' || name[0] == '.')
1361     {
1362       /* RGB decimal */
1363       NSScanner *scanner = [NSScanner scannerWithString: nsname];
1364       float r, g, b;
1365       [scanner scanFloat: &r];
1366       [scanner scanFloat: &g];
1367       [scanner scanFloat: &b];
1368       *col = [NSColor colorWithCalibratedRed: r green: g blue: b alpha: 1.0];
1369       UNBLOCK_INPUT;
1370       return 0;
1371     }
1373   /*  FIXME: emacs seems to downcase everything before passing it here,
1374         which we can work around, except for GRAY, since gray##, where ## is
1375         decimal between 0 and 99, is also an X11 colorname. */
1376   if (name[0] == '#')             /* X11 format */
1377     {
1378       hex = name + 1;
1379       color_space = rgb;
1380     }
1381   else if (!memcmp (name, "RGB", 3) || !memcmp (name, "rgb", 3))
1382     {
1383       hex = name + 3;
1384       color_space = rgb;
1385     }
1386   else if (!memcmp (name, "ARGB", 4) || !memcmp (name, "argb", 4))
1387     {
1388       hex = name + 4;
1389       color_space = argb;
1390     }
1391   else if (!memcmp (name, "HSV", 3) || !memcmp (name, "hsv", 3) || 
1392            !memcmp (name, "HSB", 3) || !memcmp (name, "hsb", 3))
1393     {
1394       hex = name + 3;
1395       color_space = hsv;
1396     }
1397   else if (!memcmp (name, "AHSV", 4) || !memcmp (name, "ahsv", 4) ||
1398            !memcmp (name, "AHSB", 4) || !memcmp (name, "ahsb", 4))
1399     {
1400       hex = name + 4;
1401       color_space = ahsv;
1402     }
1403   else if (!memcmp (name, "CMYK", 4) || !memcmp (name, "cmyk", 4))
1404     {
1405       hex = name + 4;
1406       color_space = cmyk;
1407     }
1408   else if (!memcmp (name, "GRAY", 4) /*|| !memcmp (name, "gray", 4)*/)
1409     {
1410       hex = name + 4;
1411       color_space = gray;
1412     }
1414   /* Direct colors (hex values) */
1415   if (hex)
1416     {
1417       unsigned long long color = 0;
1418       if (sscanf (hex, "%x", &color))
1419         {
1420           float f1, f2, f3, f4;
1421           /* Assume it's either 1 byte or 2 per channel... */
1422           if (strlen(hex) > 8) {
1423             f1 = ((color >> 48) & 0xffff) / 65535.0;
1424             f2 = ((color >> 32) & 0xffff) / 65535.0;
1425             f3 = ((color >> 16) & 0xffff) / 65535.0;
1426             f4 = ((color      ) & 0xffff) / 65535.0;
1427           } else {
1428             f1 = ((color >> 24) & 0xff) / 255.0;
1429             f2 = ((color >> 16) & 0xff) / 255.0;
1430             f3 = ((color >>  8) & 0xff) / 255.0;
1431             f4 = ((color      ) & 0xff) / 255.0;
1432           }
1434           switch (color_space)
1435             {
1436             case rgb:
1437               *col = [NSColor colorWithCalibratedRed: f2
1438                                                green: f3
1439                                                 blue: f4
1440                                                alpha: 1.0];
1441               break;
1442             case argb:
1443               *col = [NSColor colorWithCalibratedRed: f2
1444                                                green: f3
1445                                                 blue: f4
1446                                                alpha: f1];
1447               break;
1448             case hsv:
1449               *col = [NSColor colorWithCalibratedHue: f2
1450                                           saturation: f3
1451                                           brightness: f4
1452                                                alpha: 1.0];
1453               break;
1454             case ahsv:
1455               *col = [NSColor colorWithCalibratedHue: f2
1456                                           saturation: f3
1457                                           brightness: f4
1458                                                alpha: f1];
1459               break;
1460             case gray:
1461               *col = [NSColor colorWithCalibratedWhite: f3 alpha: f4];
1462               break;
1463             case cmyk:
1464               *col = [NSColor colorWithDeviceCyan: f1
1465                                           magenta: f2
1466                                            yellow: f3
1467                                             black: f4
1468                                             alpha: 1.0];
1469               break;
1470             }
1471           *col = [*col colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1472           UNBLOCK_INPUT;
1473           return 0;
1474         }
1475     }
1477   /* Otherwise, color is expected to be from a list */
1478   {
1479     NSEnumerator *lenum, *cenum;
1480     NSString *name;
1481     NSColorList *clist;
1483 #ifdef NS_IMPL_GNUSTEP
1484     /* XXX: who is wrong, the requestor or the implementation? */
1485     if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1486         == NSOrderedSame)
1487       nsname = @"highlightColor";
1488 #endif
1490     lenum = [[NSColorList availableColorLists] objectEnumerator];
1491     while ( (clist = [lenum nextObject]) && new == nil)
1492       {
1493         cenum = [[clist allKeys] objectEnumerator];
1494         while ( (name = [cenum nextObject]) && new == nil )
1495           {
1496             if ([name compare: nsname
1497                       options: NSCaseInsensitiveSearch] == NSOrderedSame )
1498               new = [clist colorWithKey: name];
1499           }
1500       }
1501   }
1503   if ( new )
1504     *col = [new colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1505 /*     else
1506        NSLog (@"Failed to find color '%@'", nsname); */
1507   UNBLOCK_INPUT;
1508   return new ? 0 : 1;
1512 static NSColor *
1513 ns_get_color_default (const char *name, NSColor *dflt)
1514 /* --------------------------------------------------------------------------
1515      Parse a color or use a default value
1516    -------------------------------------------------------------------------- */
1518   NSColor * col;
1520   if (ns_get_color (name, &col))
1521     return dflt;
1522   else
1523     return col;
1528 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1529 /* --------------------------------------------------------------------------
1530      Convert a Lisp string object to a NS color
1531    -------------------------------------------------------------------------- */
1533   NSTRACE (ns_lisp_to_color);
1534   if (STRINGP (color))
1535     return ns_get_color (SDATA (color), col);
1536   else if (SYMBOLP (color))
1537     return ns_get_color (SDATA (SYMBOL_NAME (color)), col);
1538   return 1;
1542 Lisp_Object
1543 ns_color_to_lisp (NSColor *col)
1544 /* --------------------------------------------------------------------------
1545      Convert a color to a lisp string with the RGB equivalent
1546    -------------------------------------------------------------------------- */
1548   float red, green, blue, alpha, gray;
1549   char buf[1024];
1550   const char *str;
1551   NSTRACE (ns_color_to_lisp);
1553   BLOCK_INPUT;
1554   if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1556       if ((str =[[col colorNameComponent] UTF8String]))
1557         {
1558           UNBLOCK_INPUT;
1559           return build_string ((char *)str);
1560         }
1562     [[col colorUsingColorSpaceName: NSCalibratedRGBColorSpace]
1563         getRed: &red green: &green blue: &blue alpha: &alpha];
1564   if (red ==green && red ==blue)
1565     {
1566       [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1567             getWhite: &gray alpha: &alpha];
1568       snprintf (buf, sizeof (buf), "GRAY%02.2lx%02.2lx",
1569                lrint (gray * 0xff), lrint (alpha * 0xff));
1570       UNBLOCK_INPUT;
1571       return build_string (buf);
1572     }
1574   snprintf (buf, sizeof (buf), "ARGB%02.2lx%02.2lx%02.2lx%02.2lx",
1575             lrint (alpha*0xff),
1576             lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1578   UNBLOCK_INPUT;
1579   return build_string (buf);
1584 ns_defined_color (struct frame *f, char *name, XColor *color_def, int alloc,
1585                   char makeIndex)
1586 /* --------------------------------------------------------------------------
1587          Return 1 if named color found, and set color_def rgb accordingly.
1588          If makeIndex and alloc are nonzero put the color in the color_table,
1589          and set color_def pixel to the resulting index.
1590          If makeIndex is zero, set color_def pixel to ARGB.
1591          Return 0 if not found
1592    -------------------------------------------------------------------------- */
1594   NSColor *temp;
1595   float r, g, b, a;
1596   int notFound = ns_get_color (name, &temp);
1598   NSTRACE (ns_defined_color);
1600   if (notFound)
1601     return 0;
1603   if (makeIndex && alloc)
1604       color_def->pixel = ns_index_color(temp, f); /* [temp retain]; */
1606   [temp getRed: &r green: &g blue: &b alpha: &a];
1607   color_def->red   = r * 65535;
1608   color_def->green = g * 65535;
1609   color_def->blue  = b * 65535;
1611   if (!makeIndex)
1612     color_def->pixel
1613       = ARGB_TO_ULONG((int)(a*255),
1614                       (int)(r*255), (int)(g*255), (int)(b*255));
1616   return 1;
1620 unsigned long
1621 ns_get_rgb_color (struct frame *f, float r, float g, float b, float a)
1622 /* --------------------------------------------------------------------------
1623     return an autoreleased RGB color
1624    -------------------------------------------------------------------------- */
1626 /*static int c = 1; fprintf (stderr, "color request %d\n", c++); */
1627   if (r < 0.0) r = 0.0;
1628   else if (r > 1.0) r = 1.0;
1629   if (g < 0.0) g = 0.0;
1630   else if (g > 1.0) g = 1.0;
1631   if (b < 0.0) b = 0.0;
1632   else if (b > 1.0) b = 1.0;
1633   if (a < 0.0) a = 0.0;
1634   else if (a > 1.0) a = 1.0;
1635   return (unsigned long) ns_index_color(
1636     [NSColor colorWithCalibratedRed: r green: g blue: b alpha: a], f);
1640 void
1641 x_set_frame_alpha (struct frame *f)
1642 /* --------------------------------------------------------------------------
1643      change the entire-frame transparency
1644    -------------------------------------------------------------------------- */
1646   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1647   EmacsView *view = FRAME_NS_VIEW (f);
1648   double alpha = 1.0;
1649   double alpha_min = 1.0;
1651   if (dpyinfo->x_highlight_frame == f)
1652     alpha = f->alpha[0];
1653   else
1654     alpha = f->alpha[1];
1656   if (FLOATP (Vframe_alpha_lower_limit))
1657     alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1658   else if (INTEGERP (Vframe_alpha_lower_limit))
1659     alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1661   if (alpha < 0.0)
1662     return;
1663   else if (1.0 < alpha)
1664     alpha = 1.0;
1665   else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1666     alpha = alpha_min;
1668 #ifdef NS_IMPL_COCOA
1669   [[view window] setAlphaValue: alpha];
1670 #endif
1674 /* ==========================================================================
1676     Mouse handling
1678    ========================================================================== */
1681 void
1682 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1683 /* --------------------------------------------------------------------------
1684      Programmatically reposition mouse pointer in pixel coordinates
1685    -------------------------------------------------------------------------- */
1687   NSTRACE (x_set_mouse_pixel_position);
1688   ns_raise_frame (f);
1689 #if 0
1690   /* FIXME: this does not work, and what about GNUstep? */
1691 #ifdef NS_IMPL_COCOA
1692   [FRAME_NS_VIEW (f) lockFocus];
1693   PSsetmouse ((float)pix_x, (float)pix_y);
1694   [FRAME_NS_VIEW (f) unlockFocus];
1695 #endif
1696 #endif
1700 void
1701 x_set_mouse_position (struct frame *f, int h, int v)
1702 /* --------------------------------------------------------------------------
1703      Programmatically reposition mouse pointer in character coordinates
1704    -------------------------------------------------------------------------- */
1706   int pix_x, pix_y;
1708   pix_x = FRAME_COL_TO_PIXEL_X (f, h) + FRAME_COLUMN_WIDTH (f) / 2;
1709   pix_y = FRAME_LINE_TO_PIXEL_Y (f, v) + FRAME_LINE_HEIGHT (f) / 2;
1711   if (pix_x < 0) pix_x = 0;
1712   if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
1714   if (pix_y < 0) pix_y = 0;
1715   if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
1717   x_set_mouse_pixel_position (f, pix_x, pix_y);
1721 static int
1722 note_mouse_movement (struct frame *frame, float x, float y)
1723 /*   ------------------------------------------------------------------------
1724      Called by EmacsView on mouseMovement events.  Passes on
1725      to emacs mainstream code if we moved off of a rect of interest
1726      known as last_mouse_glyph.
1727      ------------------------------------------------------------------------ */
1729 //  NSTRACE (note_mouse_movement);
1731   XSETFRAME (last_mouse_motion_frame, frame);
1733   /* Note, this doesn't get called for enter/leave, since we don't have a
1734      position.  Those are taken care of in the corresponding NSView methods. */
1736   /* has movement gone beyond last rect we were tracking? */
1737   if (x < last_mouse_glyph.origin.x ||
1738       x >= (last_mouse_glyph.origin.x + last_mouse_glyph.size.width) ||
1739       y < last_mouse_glyph.origin.y ||
1740       y >= (last_mouse_glyph.origin.y + last_mouse_glyph.size.height))
1741     {
1742       frame->mouse_moved = 1;
1743       note_mouse_highlight (frame, x, y);
1744       remember_mouse_glyph (frame, x, y, &last_mouse_glyph);
1745       return 1;
1746     }
1748   return 0;
1752 static void
1753 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1754                    enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1755                    unsigned long *time)
1756 /* --------------------------------------------------------------------------
1757     External (hook): inform emacs about mouse position and hit parts.
1758     If a scrollbar is being dragged, set bar_window, part, x, y, time.
1759     x & y should be position in the scrollbar (the whole bar, not the handle)
1760     and length of scrollbar respectively
1761    -------------------------------------------------------------------------- */
1763   id view;
1764   NSPoint position;
1765   int xchar, ychar;
1766   Lisp_Object frame, tail;
1767   struct frame *f;
1768   struct ns_display_info *dpyinfo;
1770   NSTRACE (ns_mouse_position);
1772   if (*fp == NULL)
1773     {
1774       fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1775       return;
1776     }
1778   dpyinfo = FRAME_NS_DISPLAY_INFO (*fp);
1780   BLOCK_INPUT;
1782   if (last_mouse_scroll_bar != nil && insist == 0)
1783     {
1784       /* TODO: we do not use this path at the moment because drag events will
1785            go directly to the EmacsScroller.  Leaving code in for now. */
1786       [last_mouse_scroll_bar getMouseMotionPart: (int *)part window: bar_window
1787                                               x: x y: y];
1788       if (time) *time = last_mouse_movement_time;
1789       last_mouse_scroll_bar = nil;
1790     }
1791   else
1792     {
1793       /* Clear the mouse-moved flag for every frame on this display.  */
1794       FOR_EACH_FRAME (tail, frame)
1795         if (FRAME_NS_P (XFRAME (frame))
1796             && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1797           XFRAME (frame)->mouse_moved = 0;
1799       last_mouse_scroll_bar = nil;
1800       if (last_mouse_frame && FRAME_LIVE_P (last_mouse_frame))
1801         f = last_mouse_frame;
1802       else
1803         f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame
1804                                     : SELECTED_FRAME ();
1806       if (f && f->output_data.ns)  /* TODO: 2nd check no longer needed? */
1807         {
1808           view = FRAME_NS_VIEW (*fp);
1810           position = [[view window] mouseLocationOutsideOfEventStream];
1811           position = [view convertPoint: position fromView: nil];
1812           remember_mouse_glyph (f, position.x, position.y, &last_mouse_glyph);
1813 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1815           if (bar_window) *bar_window = Qnil;
1816           if (part) *part = 0; /*scroll_bar_handle; */
1818           if (x) XSETINT (*x, lrint (position.x));
1819           if (y) XSETINT (*y, lrint (position.y));
1820           if (time) *time = last_mouse_movement_time;
1821           *fp = f;
1822         }
1823     }
1825   UNBLOCK_INPUT;
1829 static void
1830 ns_frame_up_to_date (struct frame *f)
1831 /* --------------------------------------------------------------------------
1832     External (hook): Fix up mouse highlighting right after a full update.
1833     Some highlighting was deferred if GC was happening during
1834     note_mouse_highlight (), while other highlighting was deferred for update.
1835    -------------------------------------------------------------------------- */
1837   NSTRACE (ns_frame_up_to_date);
1839   if (FRAME_NS_P (f))
1840     {
1841       struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1842       if ((dpyinfo->mouse_face_deferred_gc||f ==dpyinfo->mouse_face_mouse_frame)
1843       /*&& dpyinfo->mouse_face_mouse_frame*/)
1844         {
1845           BLOCK_INPUT;
1846           if (dpyinfo->mouse_face_mouse_frame)
1847             note_mouse_highlight (dpyinfo->mouse_face_mouse_frame,
1848                                   dpyinfo->mouse_face_mouse_x,
1849                                   dpyinfo->mouse_face_mouse_y);
1850           dpyinfo->mouse_face_deferred_gc = 0;
1851           UNBLOCK_INPUT;
1852         }
1853     }
1857 void
1858 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1859 /* --------------------------------------------------------------------------
1860     External (RIF): set frame mouse pointer type.
1861    -------------------------------------------------------------------------- */
1863   NSTRACE (ns_define_frame_cursor);
1864   if (FRAME_POINTER_TYPE (f) != cursor)
1865     {
1866       EmacsView *view = FRAME_NS_VIEW (f);
1867       FRAME_POINTER_TYPE (f) = cursor;
1868       [[view window] invalidateCursorRectsForView: view];
1869     }
1874 /* ==========================================================================
1876     Keyboard handling
1878    ========================================================================== */
1881 static unsigned
1882 ns_convert_key (unsigned code)
1883 /* --------------------------------------------------------------------------
1884     Internal call used by NSView-keyDown.
1885    -------------------------------------------------------------------------- */
1887   const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym)
1888                                 / sizeof (convert_ns_to_X_keysym[0]));
1889   unsigned keysym;
1890   /* An array would be faster, but less easy to read. */
1891   for (keysym = 0; keysym < last_keysym; keysym += 2)
1892     if (code == convert_ns_to_X_keysym[keysym])
1893       return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
1894   return 0;
1895 /* if decide to use keyCode and Carbon table, use this line:
1896      return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
1900 char *
1901 x_get_keysym_name (int keysym)
1902 /* --------------------------------------------------------------------------
1903     Called by keyboard.c.  Not sure if the return val is important, except
1904     that it be unique.
1905    -------------------------------------------------------------------------- */
1907   static char value[16];
1908   NSTRACE (x_get_keysym_name);
1909   sprintf (value, "%d", keysym);
1910   return value;
1915 /* ==========================================================================
1917     Block drawing operations
1919    ========================================================================== */
1922 static void
1923 ns_redraw_scroll_bars (struct frame *f)
1925   int i;
1926   id view;
1927   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
1928   NSTRACE (ns_judge_scroll_bars);
1929   for (i =[subviews count]-1; i >= 0; i--)
1930     {
1931       view = [subviews objectAtIndex: i];
1932       if (![view isKindOfClass: [EmacsScroller class]]) continue;
1933       [view display];
1934     }
1938 void
1939 ns_clear_frame (struct frame *f)
1940 /* --------------------------------------------------------------------------
1941       External (hook): Erase the entire frame
1942    -------------------------------------------------------------------------- */
1944   NSView *view = FRAME_NS_VIEW (f);
1945   NSRect r;
1947   NSTRACE (ns_clear_frame);
1948   if (ns_in_resize)
1949     return;
1951  /* comes on initial frame because we have
1952     after-make-frame-functions = select-frame */
1953  if (!FRAME_DEFAULT_FACE (f))
1954    return;
1956   mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
1958   output_cursor.hpos = output_cursor.vpos = 0;
1959   output_cursor.x = -1;
1961   r = [view bounds];
1963   BLOCK_INPUT;
1964   ns_focus (f, &r, 1);
1965   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
1966   NSRectFill (r);
1967   ns_unfocus (f);
1969 #ifdef NS_IMPL_COCOA
1970   [[view window] display];  /* redraw resize handle */
1971 #endif
1973   /* as of 2006/11 or so this is now needed */
1974   ns_redraw_scroll_bars (f);
1975   UNBLOCK_INPUT;
1979 void
1980 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
1981 /* --------------------------------------------------------------------------
1982     External (RIF):  Clear section of frame
1983    -------------------------------------------------------------------------- */
1985   NSRect r = NSMakeRect (x, y, width, height);
1986   NSView *view = FRAME_NS_VIEW (f);
1987   struct face *face = FRAME_DEFAULT_FACE (f);
1989   if (!view || !face)
1990     return;
1992   NSTRACE (ns_clear_frame_area);
1994   r = NSIntersectionRect (r, [view frame]);
1995   ns_focus (f, &r, 1);
1996   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
1998 #ifdef NS_IMPL_COCOA
1999   {
2000     /* clip out the resize handle */
2001     NSWindow *window = [FRAME_NS_VIEW (f) window];
2002     NSRect ir
2003       = [view convertRect: ns_resize_handle_rect (window) fromView: nil];
2005     ir = NSIntersectionRect (r, ir);
2006     if (NSIsEmptyRect (ir))
2007       {
2008 #endif
2010   NSRectFill (r);
2012 #ifdef NS_IMPL_COCOA
2013       }
2014     else
2015       {
2016         NSRect r1 = r, r2 = r; /* upper and lower non-intersecting */
2017         r1.size.height -= ir.size.height;
2018         r2.origin.y += r1.size.height;
2019         r2.size.width -= ir.size.width;
2020         r2.size.height = ir.size.height;
2021         NSRectFill (r1);
2022         NSRectFill (r2);
2023       }
2024   }
2025 #endif
2027   ns_unfocus (f);
2028   return;
2032 static void
2033 ns_scroll_run (struct window *w, struct run *run)
2034 /* --------------------------------------------------------------------------
2035     External (RIF):  Insert or delete n lines at line vpos
2036    -------------------------------------------------------------------------- */
2038   struct frame *f = XFRAME (w->frame);
2039   int x, y, width, height, from_y, to_y, bottom_y;
2041   NSTRACE (ns_scroll_run);
2043   /* begin copy from other terms */
2044   /* Get frame-relative bounding box of the text display area of W,
2045      without mode lines.  Include in this box the left and right
2046      fringe of W.  */
2047   window_box (w, -1, &x, &y, &width, &height);
2049   from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2050   to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2051   bottom_y = y + height;
2053   if (to_y < from_y)
2054     {
2055       /* Scrolling up.  Make sure we don't copy part of the mode
2056          line at the bottom.  */
2057       if (from_y + run->height > bottom_y)
2058         height = bottom_y - from_y;
2059       else
2060         height = run->height;
2061     }
2062   else
2063     {
2064       /* Scolling down.  Make sure we don't copy over the mode line.
2065          at the bottom.  */
2066       if (to_y + run->height > bottom_y)
2067         height = bottom_y - to_y;
2068       else
2069         height = run->height;
2070     }
2071   /* end copy from other terms */
2073   if (height == 0)
2074       return;
2076   BLOCK_INPUT;
2078   updated_window = w;
2079   x_clear_cursor (w);
2081   {
2082     NSRect srcRect = NSMakeRect (x, from_y, width, height);
2083     NSRect dstRect = NSMakeRect (x, to_y, width, height);
2084     NSPoint dstOrigin = NSMakePoint (x, to_y);
2086     ns_focus (f, &dstRect, 1);
2087     NSCopyBits (0, srcRect , dstOrigin);
2088     ns_unfocus (f);
2089   }
2091   UNBLOCK_INPUT;
2095 static void
2096 ns_after_update_window_line (struct glyph_row *desired_row)
2097 /* --------------------------------------------------------------------------
2098     External (RIF): preparatory to fringe update after text was updated
2099    -------------------------------------------------------------------------- */
2101   struct window *w = updated_window;
2102   struct frame *f;
2103   int width, height;
2105   NSTRACE (ns_after_update_window_line);
2107   /* begin copy from other terms */
2108   xassert (w);
2110   if (!desired_row->mode_line_p && !w->pseudo_window_p)
2111     desired_row->redraw_fringe_bitmaps_p = 1;
2113   /* When a window has disappeared, make sure that no rest of
2114      full-width rows stays visible in the internal border.
2115      Under NS this is drawn inside the fringes. */
2116   if (windows_or_buffers_changed
2117       && (f = XFRAME (w->frame),
2118           width = FRAME_INTERNAL_BORDER_WIDTH (f),
2119           width != 0)
2120       && (height = desired_row->visible_height,
2121           height > 0))
2122     {
2123       int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2125       /* Internal border is drawn below the tool bar.  */
2126       if (WINDOWP (f->tool_bar_window)
2127           && w == XWINDOW (f->tool_bar_window))
2128         y -= width;
2129       /* end copy from other terms */
2131       BLOCK_INPUT;
2132       if (!desired_row->full_width_p)
2133         {
2134           int x1 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2135             + WINDOW_LEFT_FRINGE_WIDTH (w);
2136           int x2 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2137             + FRAME_PIXEL_WIDTH (f) - NS_SCROLL_BAR_WIDTH (f)
2138             - WINDOW_RIGHT_FRINGE_WIDTH (w)
2139             - FRAME_INTERNAL_BORDER_WIDTH (f);
2140           ns_clear_frame_area (f, x1, y, width, height);
2141           ns_clear_frame_area (f, x2, y, width, height);
2142         }
2143       UNBLOCK_INPUT;
2144     }
2148 static void
2149 ns_shift_glyphs_for_insert (struct frame *f,
2150                            int x, int y, int width, int height,
2151                            int shift_by)
2152 /* --------------------------------------------------------------------------
2153     External (RIF): copy an area horizontally, don't worry about clearing src
2154    -------------------------------------------------------------------------- */
2156   NSRect srcRect = NSMakeRect (x, y, width, height);
2157   NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2158   NSPoint dstOrigin = dstRect.origin;
2160   NSTRACE (ns_shift_glyphs_for_insert);
2162   ns_focus (f, &dstRect, 1);
2163   NSCopyBits (0, srcRect, dstOrigin);
2164   ns_unfocus (f);
2169 /* ==========================================================================
2171     Character encoding and metrics
2173    ========================================================================== */
2176 static inline void
2177 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2178 /* --------------------------------------------------------------------------
2179      External (RIF); compute left/right overhang of whole string and set in s
2180    -------------------------------------------------------------------------- */
2182   struct face *face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2183   struct font *font = s->font; /*face->font; */
2185   if (s->char2b)
2186     {
2187       struct font_metrics metrics;
2188       unsigned int codes[2];
2189       codes[0] = *(s->char2b);
2190       codes[1] = *(s->char2b + s->nchars - 1);
2192       font->driver->text_extents (font, codes, 2, &metrics);
2193       s->left_overhang = -metrics.lbearing;
2194       s->right_overhang
2195         = metrics.rbearing > metrics.width
2196         ? metrics.rbearing - metrics.width : 0;
2197     }
2198   else
2199     {
2200       s->left_overhang = 0;
2201       s->right_overhang = ((struct nsfont_info *)font)->ital ?
2202         FONT_HEIGHT (font) * 0.2 : 0;
2203     }
2208 /* ==========================================================================
2210     Fringe and cursor drawing
2212    ========================================================================== */
2215 extern int max_used_fringe_bitmap;
2216 static void
2217 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2218                       struct draw_fringe_bitmap_params *p)
2219 /* --------------------------------------------------------------------------
2220     External (RIF); fringe-related
2221    -------------------------------------------------------------------------- */
2223   struct frame *f = XFRAME (WINDOW_FRAME (w));
2224   struct face *face = p->face;
2225   int rowY;
2226   static EmacsImage **bimgs = NULL;
2227   static int nBimgs = 0;
2228   /* NS-specific: move internal border inside fringe */
2229   int x = p->bx < 0 ? p->x : p->bx;
2230   int wd = p->bx < 0 ? p->wd : p->nx;
2231   BOOL fringeOnVeryLeft
2232     = x - WINDOW_LEFT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w)
2233       - FRAME_INTERNAL_BORDER_WIDTH (f) < 10;
2234   BOOL fringeOnVeryRight
2235     = FRAME_PIXEL_WIDTH (f) - x - wd - FRAME_INTERNAL_BORDER_WIDTH (f)
2236       - WINDOW_RIGHT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w) < 10;
2237   int xAdjust = FRAME_INTERNAL_BORDER_WIDTH (f) *
2238     (fringeOnVeryLeft ? -1 : (fringeOnVeryRight ? 1 : 0));
2240   /* grow bimgs if needed */
2241   if (nBimgs < max_used_fringe_bitmap)
2242     {
2243       EmacsImage **newBimgs
2244         = xmalloc (max_used_fringe_bitmap * sizeof (EmacsImage *));
2245       bzero (newBimgs, max_used_fringe_bitmap * sizeof (EmacsImage *));
2247       if (nBimgs)
2248         {
2249           bcopy (bimgs, newBimgs, nBimgs * sizeof (EmacsImage *));
2250           xfree (bimgs);
2251         }
2253       bimgs = newBimgs;
2254       nBimgs = max_used_fringe_bitmap;
2255     }
2257   /* Must clip because of partially visible lines.  */
2258   rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
2259   if (p->y < rowY)
2260     {
2261       /* Adjust position of "bottom aligned" bitmap on partially
2262          visible last row.  */
2263       int oldY = row->y;
2264       int oldVH = row->visible_height;
2265       row->visible_height = p->h;
2266       row->y -= rowY - p->y;
2267       ns_clip_to_row (w, row, -1, NO);
2268       row->y = oldY;
2269       row->visible_height = oldVH;
2270     }
2271   else
2272     ns_clip_to_row (w, row, -1, YES);
2274   if (p->bx >= 0 && !p->overlay_p)
2275     {
2276       int yAdjust = rowY - FRAME_INTERNAL_BORDER_WIDTH (f) < 5 ?
2277         -FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2278       int yIncr = FRAME_PIXEL_HEIGHT (f) - (p->by+yAdjust + p->ny) < 5 ?
2279         FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2280       if (yAdjust)
2281         yIncr += FRAME_INTERNAL_BORDER_WIDTH (f);
2282       NSRect r = NSMakeRect (p->bx+xAdjust, p->by+yAdjust, p->nx, p->ny+yIncr);
2283       NSRectClip (r);
2284       [ns_lookup_indexed_color(face->background, f) set];
2285       NSRectFill (r);
2286     }
2288   if (p->which)
2289     {
2290       NSRect r = NSMakeRect (p->x+xAdjust, p->y, p->wd, p->h);
2291       NSPoint pt = r.origin;
2292       EmacsImage *img = bimgs[p->which - 1];
2294       if (!img)
2295         {
2296           unsigned short *bits = p->bits + p->dh;
2297           int len = 8 * p->h/8;
2298           int i;
2299           unsigned char *cbits = xmalloc (len);
2301           for (i =0; i<len; i++)
2302             cbits[i] = ~(bits[i] & 0xff);
2303           img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2304                                            flip: NO];
2305           bimgs[p->which - 1] = img;
2306           xfree (cbits);
2307         }
2309       NSRectClip (r);
2310       /* Since we composite the bitmap instead of just blitting it, we need
2311          to erase the whole background. */
2312       [ns_lookup_indexed_color(face->background, f) set];
2313       NSRectFill (r);
2314       pt.y += p->h;
2315       [img setXBMColor: ns_lookup_indexed_color(face->foreground, f)];
2316       [img compositeToPoint: pt operation: NSCompositeSourceOver];
2317     }
2318   ns_unfocus (f);
2322 void
2323 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2324                        int x, int y, int cursor_type, int cursor_width,
2325                        int on_p, int active_p)
2326 /* --------------------------------------------------------------------------
2327      External call (RIF): draw cursor
2328      (modeled after x_draw_window_cursor
2329      FIXME: cursor_width is effectively bogus -- it sometimes gets set
2330      in xdisp.c set_frame_cursor_types, sometimes left uninitialized;
2331      DON'T USE IT (no other terms do)
2332    -------------------------------------------------------------------------- */
2334   NSRect r, s;
2335   int fx, fy, h;
2336   struct frame *f = WINDOW_XFRAME (w);
2337   struct glyph *phys_cursor_glyph;
2338   int overspill, cursorToDraw;
2340   NSTRACE (dumpcursor);
2341 //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);
2343   if (!on_p)
2344         return;
2346   w->phys_cursor_type = cursor_type;
2347   w->phys_cursor_on_p = on_p;
2349   if (cursor_type == NO_CURSOR)
2350     {
2351       w->phys_cursor_width = 0;
2352       return;
2353     }
2355   if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2356     {
2357       if (glyph_row->exact_window_width_line_p
2358           && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2359         {
2360           glyph_row->cursor_in_fringe_p = 1;
2361           draw_fringe_bitmap (w, glyph_row, 0);
2362         }
2363       return;
2364     }
2366   get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2368   r.origin.x = fx, r.origin.y = fy;
2369   r.size.height = h;
2370   r.size.width = w->phys_cursor_width;
2372   /* FIXME: if we overwrite the internal border area, it does not get erased;
2373      fix by truncating cursor, but better would be to erase properly */
2374   overspill = r.origin.x + r.size.width -
2375     WINDOW_TEXT_TO_FRAME_PIXEL_X (w, WINDOW_BOX_RIGHT_EDGE_X (w) 
2376       - WINDOW_TOTAL_FRINGE_WIDTH (w) - FRAME_INTERNAL_BORDER_WIDTH (f));
2377   if (overspill > 0)
2378     r.size.width -= overspill;
2380   /* TODO: only needed in rare cases with last-resort font in HELLO..
2381      should we do this more efficiently? */
2382   ns_clip_to_row (w, glyph_row, -1, NO); /* do ns_focus(f, &r, 1); if remove */
2383   [FRAME_CURSOR_COLOR (f) set];
2385 #ifdef NS_IMPL_COCOA
2386   /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2387            atomic.  Cleaner ways of doing this should be investigated.
2388            One way would be to set a global variable DRAWING_CURSOR
2389            when making the call to draw_phys..(), don't focus in that
2390            case, then move the ns_unfocus() here after that call. */
2391   NSDisableScreenUpdates ();
2392 #endif
2394   cursorToDraw = active_p ? cursor_type : HOLLOW_BOX_CURSOR;
2395   switch (cursorToDraw)
2396     {
2397     case NO_CURSOR:
2398       break;
2399     case FILLED_BOX_CURSOR:
2400       NSRectFill (r);
2401       break;
2402     case HOLLOW_BOX_CURSOR:
2403       NSRectFill (r);
2404       [FRAME_BACKGROUND_COLOR (f) set];
2405       NSRectFill (NSInsetRect (r, 1, 1));
2406       [FRAME_CURSOR_COLOR (f) set];
2407       break;
2408     case HBAR_CURSOR:
2409       s = r;
2410       s.origin.y += lrint (0.75 * s.size.height);
2411       s.size.width = min (FRAME_COLUMN_WIDTH (f), s.size.width);
2412       s.size.height = lrint (s.size.height * 0.25);
2413       NSRectFill (s);
2414       break;
2415     case BAR_CURSOR:
2416       s = r;
2417       s.size.width = min (cursor_width, 2); //FIXME(see above)
2418       NSRectFill (s);
2419       break;
2420     }
2421   ns_unfocus (f);
2423   /* draw the character under the cursor */
2424   if (cursorToDraw != NO_CURSOR)
2425     draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2427 #ifdef NS_IMPL_COCOA
2428   NSEnableScreenUpdates ();
2429 #endif
2434 static void
2435 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2436 /* --------------------------------------------------------------------------
2437      External (RIF): Draw a vertical line.
2438    -------------------------------------------------------------------------- */
2440   struct frame *f = XFRAME (WINDOW_FRAME (w));
2441   struct face *face;
2442   NSRect r = NSMakeRect (x, y0, 2, y1-y0);
2444   NSTRACE (ns_draw_vertical_window_border);
2446   face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2447   if (face)
2448       [ns_lookup_indexed_color(face->foreground, f) set];
2450   ns_focus (f, &r, 1);
2451   NSDrawGroove (r, r);
2452   ns_unfocus (f);
2456 void
2457 show_hourglass (struct atimer *timer)
2459   if (hourglass_shown_p)
2460     return;
2462   BLOCK_INPUT;
2464   /* TODO: add NSProgressIndicator to selected frame (see macfns.c) */
2466   hourglass_shown_p = 1;
2467   UNBLOCK_INPUT;
2471 void
2472 hide_hourglass ()
2474   if (!hourglass_shown_p)
2475     return;
2477   BLOCK_INPUT;
2479   /* TODO: remove NSProgressIndicator from all frames */
2481   hourglass_shown_p = 0;
2482   UNBLOCK_INPUT;
2487 /* ==========================================================================
2489     Glyph drawing operations
2491    ========================================================================== */
2494 static inline NSRect
2495 ns_fix_rect_ibw (NSRect r, int fibw, int frame_pixel_width)
2496 /* --------------------------------------------------------------------------
2497     Under NS we draw internal borders inside fringes, and want full-width
2498     rendering to go all the way to edge.  This function makes that correction.
2499    -------------------------------------------------------------------------- */
2501   if (r.origin.y <= fibw+1)
2502     {
2503       r.size.height += r.origin.y;
2504       r.origin.y = 0;
2505     }
2506   if (r.origin.x <= fibw+1)
2507     {
2508       r.size.width += r.origin.x;
2509       r.origin.x = 0;
2510     }
2511   if (frame_pixel_width - (r.origin.x+r.size.width) <= fibw+1)
2512     r.size.width += fibw;
2514   return r;
2518 static int
2519 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2520 /* --------------------------------------------------------------------------
2521     Wrapper utility to account for internal border width on full-width lines,
2522     and allow top full-width rows to hit the frame top.  nr should be pointer
2523     to two successive NSRects.  Number of rects actually used is returned.
2524    -------------------------------------------------------------------------- */
2526   int n = get_glyph_string_clip_rects (s, nr, 2);
2527   if (s->row->full_width_p)
2528     {
2529       *nr = ns_fix_rect_ibw (*nr, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2530                             FRAME_PIXEL_WIDTH (s->f));
2531       if (n == 2)
2532         *nr = ns_fix_rect_ibw (*(nr+1), FRAME_INTERNAL_BORDER_WIDTH (s->f),
2533                               FRAME_PIXEL_WIDTH (s->f));
2534     }
2535   return n;
2539 static void
2540 ns_draw_box (NSRect r, float thickness, NSColor *col, char left_p, char right_p)
2541 /* --------------------------------------------------------------------------
2542     Draw an unfilled rect inside r, optionally leaving left and/or right open.
2543     Note we can't just use an NSDrawRect command, because of the possibility
2544     of some sides not being drawn, and because the rect will be filled.
2545    -------------------------------------------------------------------------- */
2547   NSRect s = r;
2548   [col set];
2550   /* top, bottom */
2551   s.size.height = thickness;
2552   NSRectFill (s);
2553   s.origin.y += r.size.height - thickness;
2554   NSRectFill (s);
2556   s.size.height = r.size.height;
2557   s.origin.y = r.origin.y;
2559   /* left, right (optional) */
2560   s.size.width = thickness;
2561   if (left_p)
2562     NSRectFill (s);
2563   if (right_p)
2564     {
2565       s.origin.x += r.size.width - thickness;
2566       NSRectFill (s);
2567     }
2571 static void
2572 ns_draw_relief (NSRect r, int thickness, char raised_p,
2573                char top_p, char bottom_p, char left_p, char right_p,
2574                struct glyph_string *s)
2575 /* --------------------------------------------------------------------------
2576     Draw a relief rect inside r, optionally leaving some sides open.
2577     Note we can't just use an NSDrawBezel command, because of the possibility
2578     of some sides not being drawn, and because the rect will be filled.
2579    -------------------------------------------------------------------------- */
2581   static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2582   NSColor *newBaseCol = nil;
2583   NSRect sr = r;
2585   NSTRACE (ns_draw_relief);
2587   /* set up colors */
2589   if (s->face->use_box_color_for_shadows_p)
2590     {
2591       newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2592     }
2593 /*     else if (s->first_glyph->type == IMAGE_GLYPH
2594            && s->img->pixmap
2595            && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2596        {
2597          newBaseCol = IMAGE_BACKGROUND  (s->img, s->f, 0);
2598        } */
2599   else
2600     {
2601       newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2602     }
2604   if (newBaseCol == nil)
2605     newBaseCol = [NSColor grayColor];
2607   if (newBaseCol != baseCol)  /* TODO: better check */
2608     {
2609       [baseCol release];
2610       baseCol = [newBaseCol retain];
2611       [lightCol release];
2612       lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2613       [darkCol release];
2614       darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2615     }
2617   [(raised_p ? lightCol : darkCol) set];
2619   /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2621   /* top */
2622   sr.size.height = thickness;
2623   if (top_p) NSRectFill (sr);
2625   /* left */
2626   sr.size.height = r.size.height;
2627   sr.size.width = thickness;
2628   if (left_p) NSRectFill (sr);
2630   [(raised_p ? darkCol : lightCol) set];
2632   /* bottom */
2633   sr.size.width = r.size.width;
2634   sr.size.height = thickness;
2635   sr.origin.y += r.size.height - thickness;
2636   if (bottom_p) NSRectFill (sr);
2638   /* right */
2639   sr.size.height = r.size.height;
2640   sr.origin.y = r.origin.y;
2641   sr.size.width = thickness;
2642   sr.origin.x += r.size.width - thickness;
2643   if (right_p) NSRectFill (sr);
2647 static void
2648 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2649 /* --------------------------------------------------------------------------
2650       Function modeled after x_draw_glyph_string_box ().
2651       Sets up parameters for drawing.
2652    -------------------------------------------------------------------------- */
2654   int right_x, last_x;
2655   char left_p, right_p;
2656   struct glyph *last_glyph;
2657   NSRect r;
2658   int thickness;
2659   struct face *face;
2661   if (s->hl == DRAW_MOUSE_FACE)
2662     {
2663       face = FACE_FROM_ID
2664         (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2665       if (!face)
2666         face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2667     }
2668   else
2669     face = s->face;
2671   thickness = face->box_line_width;
2673   NSTRACE (ns_dumpglyphs_box_or_relief);
2675   last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2676             ? WINDOW_RIGHT_EDGE_X (s->w)
2677             : window_box_right (s->w, s->area));
2678   last_glyph = (s->cmp || s->img
2679                 ? s->first_glyph : s->first_glyph + s->nchars-1);
2681   right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2682               ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2684   left_p = (s->first_glyph->left_box_line_p
2685             || (s->hl == DRAW_MOUSE_FACE
2686                 && (s->prev == NULL || s->prev->hl != s->hl)));
2687   right_p = (last_glyph->right_box_line_p
2688              || (s->hl == DRAW_MOUSE_FACE
2689                  && (s->next == NULL || s->next->hl != s->hl)));
2691   r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2693   /* expand full-width row over internal borders */
2694   if (s->row->full_width_p)
2695     r = ns_fix_rect_ibw (r, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2696                         FRAME_PIXEL_WIDTH (s->f));
2698   if (s->face->box == FACE_SIMPLE_BOX)
2699     {
2700       xassert (s->face->box_color != nil);
2701       ns_draw_box (r, abs (thickness),
2702                    ns_lookup_indexed_color (face->box_color, s->f),
2703                   left_p, right_p);
2704     }
2705   else
2706     {
2707       ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2708                      1, 1, left_p, right_p, s);
2709     }
2713 static void
2714 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2715 /* --------------------------------------------------------------------------
2716       Modeled after x_draw_glyph_string_background, which draws BG in
2717       certain cases.  Others are left to the text rendering routine.
2718    -------------------------------------------------------------------------- */
2720   NSTRACE (ns_maybe_dumpglyphs_background);
2722   if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2723     {
2724       int box_line_width = max (s->face->box_line_width, 0);
2725       if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2726           || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2727         {
2728           struct face *face;
2729           if (s->hl == DRAW_MOUSE_FACE)
2730             {
2731               face = FACE_FROM_ID
2732                 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2733               if (!face)
2734                 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2735             }
2736           else
2737             face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2738           if (!face->stipple)
2739             [(NS_FACE_BACKGROUND (face) != 0
2740               ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2741               : FRAME_BACKGROUND_COLOR (s->f)) set];
2742           else
2743             {
2744               struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (s->f);
2745               [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2746             }
2748           if (s->hl != DRAW_CURSOR)
2749             {
2750               NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2751                                     s->background_width,
2752                                     s->height-2*box_line_width);
2754               /* expand full-width row over internal borders */
2755               if (s->row->full_width_p)
2756                 {
2757                   int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2758                   if (r.origin.y <= fibw+1 + box_line_width)
2759                     {
2760                       r.size.height += r.origin.y;
2761                       r.origin.y = 0;
2762                     }
2763                   if (r.origin.x <= fibw+1)
2764                     {
2765                       r.size.width += 2*r.origin.x;
2766                       r.origin.x = 0;
2767                     }
2768                   if (FRAME_PIXEL_WIDTH (s->f) - (r.origin.x + r.size.width)
2769                       <= fibw+1)
2770                     r.size.width += fibw;
2771                 }
2773               NSRectFill (r);
2774             }
2776           s->background_filled_p = 1;
2777         }
2778     }
2782 static void
2783 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2784 /* --------------------------------------------------------------------------
2785       Renders an image and associated borders.
2786    -------------------------------------------------------------------------- */
2788   EmacsImage *img = s->img->pixmap;
2789   int box_line_vwidth = max (s->face->box_line_width, 0);
2790   int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2791   int bg_x, bg_y, bg_height;
2792   int th;
2793   char raised_p;
2794   NSRect br;
2796   NSTRACE (ns_dumpglyphs_image);
2798   if (s->face->box != FACE_NO_BOX
2799       && s->first_glyph->left_box_line_p && s->slice.x == 0)
2800     x += abs (s->face->box_line_width);
2802   bg_x = x;
2803   bg_y =  s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2804   bg_height = s->height;
2805   /* other terms have this, but was causing problems w/tabbar mode */
2806   /* - 2 * box_line_vwidth; */
2808   if (s->slice.x == 0) x += s->img->hmargin;
2809   if (s->slice.y == 0) y += s->img->vmargin;
2811   /* Draw BG: if we need larger area than image itself cleared, do that,
2812      otherwise, since we composite the image under NS (instead of mucking
2813      with its background color), we must clear just the image area. */
2814   [ns_lookup_indexed_color (NS_FACE_BACKGROUND
2815             (FACE_FROM_ID (s->f, s->first_glyph->face_id)), s->f) set];
2817   if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
2818       || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
2819     {
2820       br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
2821       s->background_filled_p = 1;
2822     }
2823   else
2824     {
2825       br = NSMakeRect (x, y, s->slice.width, s->slice.height);
2826     }
2828   /* expand full-width row over internal borders */
2829   if (s->row->full_width_p)
2830     {
2831       int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2832       if (br.origin.y <= fibw+1 + box_line_vwidth)
2833         {
2834           br.size.height += br.origin.y;
2835           br.origin.y = 0;
2836         }
2837       if (br.origin.x <= fibw+1 + box_line_vwidth)
2838         {
2839           br.size.width += br.origin.x;
2840           br.origin.x = 0;
2841         }
2842       if (FRAME_PIXEL_WIDTH (s->f) - (br.origin.x + br.size.width) <= fibw+1)
2843         br.size.width += fibw;
2844     }
2846   NSRectFill (br);
2848   /* Draw the image.. do we need to draw placeholder if img ==nil? */
2849   if (img != nil)
2850     [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
2851                 operation: NSCompositeSourceOver];
2853   /* Draw relief, if requested */
2854   if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
2855     {
2856       if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
2857         {
2858           th = tool_bar_button_relief >= 0 ?
2859             tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2860           raised_p = (s->hl == DRAW_IMAGE_RAISED);
2861         }
2862       else
2863         {
2864           th = abs (s->img->relief);
2865           raised_p = (s->img->relief > 0);
2866         }
2868       r.origin.x = x - th;
2869       r.origin.y = y - th;
2870       r.size.width = s->slice.width + 2*th-1;
2871       r.size.height = s->slice.height + 2*th-1;
2872       ns_draw_relief (r, th, raised_p,
2873                       s->slice.y == 0,
2874                       s->slice.y + s->slice.height == s->img->height,
2875                       s->slice.x == 0,
2876                       s->slice.x + s->slice.width == s->img->width, s);
2877     }
2881 static void
2882 ns_dumpglyphs_stretch (struct glyph_string *s)
2884   NSRect r[2];
2885   int n, i;
2887   if (!s->background_filled_p)
2888     {
2889       n = ns_get_glyph_string_clip_rect (s, r);
2890       *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
2892       for (i=0; i<n; i++)
2893         {
2894           if (!s->row->full_width_p)
2895             {
2896               /* truncate to avoid overwriting fringe and/or scrollbar */
2897               int overrun = max (0, (s->x + s->background_width)
2898                                   - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
2899                                     - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
2900               r[i].size.width -= overrun;
2902               /* XXX: Try to work between problem where a stretch glyph on
2903                  a partially-visible bottom row will clear part of the
2904                  modeline, and another where list-buffers headers and similar
2905                  rows erroneously have visible_height set to 0.  Not sure
2906                  where this is coming from as other terms seem not to show. */
2907               r[i].size.height = min (s->height, s->row->visible_height);
2908             }
2910           /* expand full-width rows over internal borders */
2911           else
2912             {
2913               r[i] = ns_fix_rect_ibw (r[i], FRAME_INTERNAL_BORDER_WIDTH (s->f),
2914                                       FRAME_PIXEL_WIDTH (s->f));
2915             }
2917           /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
2918              overwriting cursor (usually when cursor on a tab) */
2919           if (s->hl == DRAW_CURSOR)
2920             {
2921               r[i].origin.x += s->width;
2922               r[i].size.width -= s->width;
2923             }
2924         }
2926       ns_focus (s->f, r, n);
2927       [ns_lookup_indexed_color (NS_FACE_BACKGROUND
2928            (FACE_FROM_ID (s->f, s->first_glyph->face_id)), s->f) set];
2929       NSRectFill (r[0]);
2930       NSRectFill (r[1]);
2931       ns_unfocus (s->f);
2932       s->background_filled_p = 1;
2933     }
2937 static void
2938 ns_draw_glyph_string (struct glyph_string *s)
2939 /* --------------------------------------------------------------------------
2940       External (RIF): Main draw-text call.
2941    -------------------------------------------------------------------------- */
2943   /* TODO (optimize): focus for box and contents draw */
2944   NSRect r[2];
2945   int n;
2946   char box_drawn_p = 0;
2948   NSTRACE (ns_draw_glyph_string);
2950   if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
2951     {
2952       int width;
2953       struct glyph_string *next;
2955       for (width = 0, next = s->next;
2956            next && width < s->right_overhang;
2957            width += next->width, next = next->next)
2958         if (next->first_glyph->type != IMAGE_GLYPH)
2959           {
2960             if (next->first_glyph->type != STRETCH_GLYPH)
2961               {
2962                 n = ns_get_glyph_string_clip_rect (s->next, r);
2963                 ns_focus (s->f, r, n);
2964                 ns_maybe_dumpglyphs_background (s->next, 1);
2965                 ns_unfocus (s->f);
2966               }
2967             else
2968               {
2969                 ns_dumpglyphs_stretch (s->next);
2970               }
2971             next->num_clips = 0;
2972           }
2973     }
2975   if (!s->for_overlaps && s->face->box != FACE_NO_BOX
2976         && (s->first_glyph->type == CHAR_GLYPH
2977             || s->first_glyph->type == COMPOSITE_GLYPH))
2978     {
2979       n = ns_get_glyph_string_clip_rect (s, r);
2980       ns_focus (s->f, r, n);
2981       ns_maybe_dumpglyphs_background (s, 1);
2982       ns_dumpglyphs_box_or_relief (s);
2983       ns_unfocus (s->f);
2984       box_drawn_p = 1;
2985     }
2987   switch (s->first_glyph->type)
2988     {
2990     case IMAGE_GLYPH:
2991       n = ns_get_glyph_string_clip_rect (s, r);
2992       ns_focus (s->f, r, n);
2993       ns_dumpglyphs_image (s, r[0]);
2994       ns_unfocus (s->f);
2995       break;
2997     case STRETCH_GLYPH:
2998       ns_dumpglyphs_stretch (s);
2999       break;
3001     case CHAR_GLYPH:
3002     case COMPOSITE_GLYPH:
3003       n = ns_get_glyph_string_clip_rect (s, r);
3004       ns_focus (s->f, r, n);
3006       if (s->for_overlaps || (s->cmp_from > 0
3007                               && ! s->first_glyph->u.cmp.automatic))
3008         s->background_filled_p = 1;
3009       else      /* 1 */
3010         ns_maybe_dumpglyphs_background
3011           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3013       ns_tmp_flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3014                     (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3015                      (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3016                       NS_DUMPGLYPH_NORMAL));
3017       ns_tmp_font = (struct nsfont_info *)s->face->font;
3018       if (ns_tmp_font == NULL)
3019           ns_tmp_font = (struct nsfont_info *)FRAME_FONT (s->f);
3021       ns_tmp_font->font.driver->draw
3022         (s, 0, s->nchars, s->x, s->y,
3023          (ns_tmp_flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3024          || ns_tmp_flags == NS_DUMPGLYPH_MOUSEFACE);
3026       ns_unfocus (s->f);
3027       break;
3029     default:
3030       abort ();
3031     }
3033   /* Draw box if not done already. */
3034   if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3035     {
3036       n = ns_get_glyph_string_clip_rect (s, r);
3037       ns_focus (s->f, r, n);
3038       ns_dumpglyphs_box_or_relief (s);
3039       ns_unfocus (s->f);
3040     }
3042   s->num_clips = 0;
3047 /* ==========================================================================
3049     Event loop
3051    ========================================================================== */
3054 static void
3055 ns_send_appdefined (int value)
3056 /* --------------------------------------------------------------------------
3057     Internal: post an appdefined event which EmacsApp-sendEvent will
3058               recognize and take as a command to halt the event loop.
3059    -------------------------------------------------------------------------- */
3061   /*NSTRACE (ns_send_appdefined); */
3063   /* Only post this event if we haven't already posted one.  This will end
3064        the [NXApp run] main loop after having processed all events queued at
3065        this moment.  */
3066   if (send_appdefined)
3067     {
3068       NSEvent *nxev;
3070       /* We only need one NX_APPDEFINED event to stop NXApp from running.  */
3071       send_appdefined = NO;
3073       /* Don't need wakeup timer any more */
3074       if (timed_entry)
3075         {
3076           [timed_entry invalidate];
3077           [timed_entry release];
3078           timed_entry = nil;
3079         }
3081       /* Ditto for file descriptor poller */
3082       if (fd_entry)
3083         {
3084           [fd_entry invalidate];
3085           [fd_entry release];
3086           fd_entry = nil;
3087         }
3089       nxev = [NSEvent otherEventWithType: NSApplicationDefined
3090                                 location: NSMakePoint (0, 0)
3091                            modifierFlags: 0
3092                                timestamp: 0
3093                             windowNumber: [[NSApp mainWindow] windowNumber]
3094                                  context: [NSApp context]
3095                                  subtype: 0
3096                                    data1: value
3097                                    data2: 0];
3099       /* Post an application defined event on the event queue.  When this is
3100          received the [NXApp run] will return, thus having processed all
3101          events which are currently queued.  */
3102       [NSApp postEvent: nxev atStart: NO];
3103     }
3107 static int
3108 ns_read_socket (struct terminal *terminal, int expected,
3109                 struct input_event *hold_quit)
3110 /* --------------------------------------------------------------------------
3111      External (hook): Post an event to ourself and keep reading events until
3112      we read it back again.  In effect process all events which were waiting.
3113      From 21+ we have to manage the event buffer ourselves.
3114    -------------------------------------------------------------------------- */
3116   struct input_event ev;
3117   int nevents;
3118   static NSDate *lastCheck = nil;
3119 /*  NSTRACE (ns_read_socket); */
3121   if (interrupt_input_blocked)
3122     {
3123       interrupt_input_pending = 1;
3124       return -1;
3125     }
3127   interrupt_input_pending = 0;
3128   BLOCK_INPUT;
3130 #ifdef COCOA_EXPERIMENTAL_CTRL_G
3131   /* causes Feval to abort; unclear on why this isn't in calling code */
3132   ++handling_signal;
3133 #endif
3135   n_emacs_events_pending = 0;
3136   EVENT_INIT (ev);
3137   emacs_event = &ev;
3138   q_event_ptr = hold_quit;
3140   /* we manage autorelease pools by allocate/reallocate each time around
3141      the loop; strict nesting is occasionally violated but seems not to
3142      matter.. earlier methods using full nesting caused major memory leaks */
3143   [outerpool release];
3144   outerpool = [[NSAutoreleasePool alloc] init];
3146   /* If have pending open-file requests, attend to the next one of those. */
3147   if (ns_pending_files && [ns_pending_files count] != 0
3148       && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3149     {
3150       [ns_pending_files removeObjectAtIndex: 0];
3151     }
3152   /* Deal with pending service requests. */
3153   else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3154     && [(EmacsApp *)
3155          NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3156                       withArg: [ns_pending_service_args objectAtIndex: 0]])
3157     {
3158       [ns_pending_service_names removeObjectAtIndex: 0];
3159       [ns_pending_service_args removeObjectAtIndex: 0];
3160     }
3161   else
3162     {
3163       /* Run and wait for events.  We must always send one NX_APPDEFINED event
3164          to ourself, otherwise [NXApp run] will never exit.  */
3165       send_appdefined = YES;
3167       /* TODO: from termhooks.h: */
3168       /* XXX Please note that a non-zero value of EXPECTED only means that
3169      there is available input on at least one of the currently opened
3170      terminal devices -- but not necessarily on this device.
3171      Therefore, in most cases EXPECTED should be simply ignored. */
3172       /* However, if in ns_select, this is called from gobble_input, which
3173          appears to set it correctly for our purposes, and always assuming
3174          !expected causes 100% CPU usage. */
3175       if (!inNsSelect || !expected)
3176         {
3177           /* Post an application defined event on the event queue.  When this is
3178              received the [NXApp run] will return, thus having processed all
3179              events which are currently queued, if any.  */
3180           ns_send_appdefined (-1);
3181         }
3183       [NSApp run];
3184     }
3186   nevents = n_emacs_events_pending;
3187   n_emacs_events_pending = 0;
3188   emacs_event = q_event_ptr = NULL;
3190 #ifdef COCOA_EXPERIMENTAL_CTRL_G
3191   --handling_signal;
3192 #endif
3193   UNBLOCK_INPUT;
3194   return nevents;
3199 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3200            fd_set *exceptfds, struct timeval *timeout)
3201 /* --------------------------------------------------------------------------
3202      Replacement for select, checking for events
3203    -------------------------------------------------------------------------- */
3205   int result;
3206   double time;
3207   NSEvent *ev;
3208 /*  NSTRACE (ns_select); */
3210   if (NSApp == nil /* || ([NSApp isActive] == NO &&
3211                       [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
3212  inMode:NSDefaultRunLoopMode dequeue:NO] == nil) */)
3213     return select (nfds, readfds, writefds, exceptfds, timeout);
3215   /* Save file descriptor set, which gets overwritten in calls to select ()
3216      Note, this is called from process.c, and only readfds is ever set */
3217   if (readfds)
3218     {
3219       memcpy (&select_readfds, readfds, sizeof (fd_set));
3220       select_nfds = nfds;
3221     }
3222   else
3223     select_nfds = 0;
3225     /* Try an initial select for pending data on input files */
3226   select_timeout.tv_sec = select_timeout.tv_usec = 0;
3227   result = select (nfds, readfds, writefds, exceptfds, &select_timeout);
3228   if (result)
3229     return result;
3231   /* if (!timeout || timed_entry || fd_entry)
3232        fprintf (stderr, "assertion failed: timeout null or timed_entry/fd_entry non-null in ns_select\n"); */
3234     /* set a timeout and run the main AppKit event loop while continuing
3235        to monitor the files */
3236   time = ((double) timeout->tv_sec) + ((double) timeout->tv_usec)/1000000.0;
3237   timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3238                                            target: NSApp
3239                                          selector: @selector (timeout_handler:)
3240                                          userInfo: 0
3241                                           repeats: YES] /* for safe removal */
3242                                                          retain];
3244   /* set a periodic task to try the select () again */
3245   fd_entry = [[NSTimer scheduledTimerWithTimeInterval: 0.1
3246                                                target: NSApp
3247                                              selector: @selector (fd_handler:)
3248                                              userInfo: 0
3249                                               repeats: YES]
3250                retain];
3252   /* Let Application dispatch events until it receives an event of the type
3253        NX_APPDEFINED, which should only be sent by timeout_handler.  */
3254   inNsSelect = 1;
3255   gobble_input (timeout ? 1 : 0);
3256   ev = last_appdefined_event;
3257   inNsSelect = 0;
3259   if (ev)
3260     {
3261       int t;
3262       if ([ev type] != NSApplicationDefined)
3263         abort ();
3265       t = [ev data1];
3266       last_appdefined_event = 0;
3268       if (t == -2)
3269         {
3270           /* The NX_APPDEFINED event we received was a timeout. */
3271           return 0;
3272         }
3273       else if (t == -1)
3274         {
3275           /* The NX_APPDEFINED event we received was the result of
3276              at least one real input event arriving.  */
3277           errno = EINTR;
3278           return -1;
3279         }
3280       else
3281         {
3282           /* Received back from select () in fd_handler; copy the results */
3283           if (readfds)
3284             memcpy (readfds, &select_readfds, sizeof (fd_set));
3285           return t;
3286         }
3287     }
3288   /* never reached, shut compiler up */
3289   return 0;
3294 /* ==========================================================================
3296     Scrollbar handling
3298    ========================================================================== */
3301 static void
3302 ns_set_vertical_scroll_bar (struct window *window,
3303                            int portion, int whole, int position)
3304 /* --------------------------------------------------------------------------
3305       External (hook): Update or add scrollbar
3306    -------------------------------------------------------------------------- */
3308   Lisp_Object win;
3309   NSRect r, v;
3310   struct frame *f = XFRAME (WINDOW_FRAME (window));
3311   EmacsView *view = FRAME_NS_VIEW (f);
3312   int window_y, window_height;
3313   BOOL barOnVeryLeft, barOnVeryRight;
3314   int top, left, height, width, sb_width, sb_left;
3315   EmacsScroller *bar;
3316 static int count = 0;
3318   /* optimization; display engine sends WAY too many of these.. */
3319   if (!NILP (window->vertical_scroll_bar))
3320     {
3321       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3322       if ([bar checkSamePosition: position portion: portion whole: whole])
3323         {
3324           if (view->scrollbarsNeedingUpdate == 0)
3325             {
3326               if (!windows_or_buffers_changed)
3327                   return;
3328             }
3329           else
3330             view->scrollbarsNeedingUpdate--;
3331         }
3332     }
3334   NSTRACE (ns_set_vertical_scroll_bar);
3336   /* Get dimensions.  */
3337   window_box (window, -1, 0, &window_y, 0, &window_height);
3338   top = window_y;
3339   height = window_height;
3340   width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3341   left = WINDOW_SCROLL_BAR_AREA_X (window);
3343   if (top < 5) /* top scrollbar adjustment */
3344     {
3345       top -= FRAME_INTERNAL_BORDER_WIDTH (f);
3346       height += FRAME_INTERNAL_BORDER_WIDTH (f);
3347     }
3349   /* allow for displaying a skinnier scrollbar than char area allotted */
3350   sb_width = (WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) > 0) ?
3351     WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) : width;
3353   barOnVeryLeft = left < 5;
3354   barOnVeryRight = FRAME_PIXEL_WIDTH (f) - left - width < 5;
3355   sb_left = left + FRAME_INTERNAL_BORDER_WIDTH (f)
3356       * (barOnVeryLeft ? -1 : (barOnVeryRight ? 1 : 0));
3358   r = NSMakeRect (sb_left, top, sb_width, height);
3359   /* the parent view is flipped, so we need to flip y value */
3360   v = [view frame];
3361   r.origin.y = (v.size.height - r.size.height - r.origin.y);
3363   XSETWINDOW (win, window);
3364   BLOCK_INPUT;
3366   /* we want at least 5 lines to display a scrollbar */
3367   if (WINDOW_TOTAL_LINES (window) < 5)
3368     {
3369       if (!NILP (window->vertical_scroll_bar))
3370         {
3371           bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3372           [bar removeFromSuperview];
3373           window->vertical_scroll_bar = Qnil;
3374         }
3375       ns_clear_frame_area (f, sb_left, top, width, height);
3376       UNBLOCK_INPUT;
3377       return;
3378     }
3380   if (NILP (window->vertical_scroll_bar))
3381     {
3382       ns_clear_frame_area (f, sb_left, top, width, height);
3383       bar = [[EmacsScroller alloc] initFrame: r window: win];
3384       window->vertical_scroll_bar = make_save_value (bar, 0);
3385     }
3386   else
3387     {
3388       NSRect oldRect;
3389       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3390       oldRect = [bar frame];
3391       r.size.width = oldRect.size.width;
3392       if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3393         {
3394           if (oldRect.origin.x != r.origin.x)
3395               ns_clear_frame_area (f, sb_left, top, width, height);
3396           [bar setFrame: r];
3397         }
3398     }
3400   [bar setPosition: position portion: portion whole: whole];
3401   UNBLOCK_INPUT;
3405 static void
3406 ns_condemn_scroll_bars (struct frame *f)
3407 /* --------------------------------------------------------------------------
3408      External (hook): arrange for all frame's scrollbars to be removed
3409      at next call to judge_scroll_bars, except for those redeemed.
3410    -------------------------------------------------------------------------- */
3412   int i;
3413   id view;
3414   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3416   NSTRACE (ns_condemn_scroll_bars);
3418   for (i =[subviews count]-1; i >= 0; i--)
3419     {
3420       view = [subviews objectAtIndex: i];
3421       if ([view isKindOfClass: [EmacsScroller class]])
3422         [view condemn];
3423     }
3427 static void
3428 ns_redeem_scroll_bar (struct window *window)
3429 /* --------------------------------------------------------------------------
3430      External (hook): arrange to spare this window's scrollbar
3431      at next call to judge_scroll_bars.
3432    -------------------------------------------------------------------------- */
3434   id bar;
3435   NSTRACE (ns_redeem_scroll_bar);
3436   if (!NILP (window->vertical_scroll_bar))
3437     {
3438       bar =XNS_SCROLL_BAR (window->vertical_scroll_bar);
3439       [bar reprieve];
3440     }
3444 static void
3445 ns_judge_scroll_bars (struct frame *f)
3446 /* --------------------------------------------------------------------------
3447      External (hook): destroy all scrollbars on frame that weren't
3448      redeemed after call to condemn_scroll_bars.
3449    -------------------------------------------------------------------------- */
3451   int i;
3452   id view;
3453   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3454   NSTRACE (ns_judge_scroll_bars);
3455   for (i =[subviews count]-1; i >= 0; i--)
3456     {
3457       view = [subviews objectAtIndex: i];
3458       if (![view isKindOfClass: [EmacsScroller class]]) continue;
3459       [view judge];
3460     }
3464 void
3465 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
3467   /* XXX irrelevant under NS */
3472 /* ==========================================================================
3474     Initialization
3476    ========================================================================== */
3479 x_display_pixel_height (dpyinfo)
3480      struct ns_display_info *dpyinfo;
3482   NSScreen *screen = [NSScreen mainScreen];
3483   return [screen frame].size.height;
3487 x_display_pixel_width (dpyinfo)
3488      struct ns_display_info *dpyinfo;
3490   NSScreen *screen = [NSScreen mainScreen];
3491   return [screen frame].size.width;
3495 static Lisp_Object ns_string_to_lispmod (const char *s)
3496 /* --------------------------------------------------------------------------
3497      Convert modifier name to lisp symbol
3498    -------------------------------------------------------------------------- */
3500   if (!strncmp (SDATA (SYMBOL_NAME (Qmeta)), s, 10))
3501     return Qmeta;
3502   else if (!strncmp (SDATA (SYMBOL_NAME (Qsuper)), s, 10))
3503     return Qsuper;
3504   else if (!strncmp (SDATA (SYMBOL_NAME (Qcontrol)), s, 10))
3505     return Qcontrol;
3506   else if (!strncmp (SDATA (SYMBOL_NAME (Qalt)), s, 10))
3507     return Qalt;
3508   else if (!strncmp (SDATA (SYMBOL_NAME (Qhyper)), s, 10))
3509     return Qhyper;
3510   else if (!strncmp (SDATA (SYMBOL_NAME (Qnone)), s, 10))
3511     return Qnone;
3512   else
3513     return Qnil;
3517 static Lisp_Object ns_mod_to_lisp (int m)
3518 /* --------------------------------------------------------------------------
3519      Convert modifier code (see lisp.h) to lisp symbol
3520    -------------------------------------------------------------------------- */
3522   if (m == CHAR_META)
3523     return Qmeta;
3524   else if (m == CHAR_SUPER)
3525     return Qsuper;
3526   else if (m == CHAR_CTL)
3527     return Qcontrol;
3528   else if (m == CHAR_ALT)
3529     return Qalt;
3530   else if (m == CHAR_HYPER)
3531     return Qhyper;
3532   else /* if (m == 0) */
3533     return Qnone;
3537 static void
3538 ns_set_default_prefs ()
3539 /* --------------------------------------------------------------------------
3540       Initialize preference variables to defaults
3541    -------------------------------------------------------------------------- */
3543   ns_alternate_modifier = Qmeta;
3544   ns_command_modifier = Qsuper;
3545   ns_control_modifier = Qcontrol;
3546   ns_function_modifier = Qnone;
3547   ns_expand_space = make_float (0.0);
3548   ns_antialias_text = Qt;
3549   ns_antialias_threshold = 10.0; /* not exposed to lisp side */
3550   ns_use_qd_smoothing = Qnil;
3551   ns_use_system_highlight_color = Qt;
3555 static void
3556 ns_default (const char *parameter, Lisp_Object *result,
3557            Lisp_Object yesval, Lisp_Object noval,
3558            BOOL is_float, BOOL is_modstring)
3559 /* --------------------------------------------------------------------------
3560       Check a parameter value in user's preferences
3561    -------------------------------------------------------------------------- */
3563   const char *value;
3565   if ( (value =[[[NSUserDefaults standardUserDefaults]
3566                    stringForKey: [NSString stringWithUTF8String: parameter]]
3567                 UTF8String]) )
3568     {
3569       double f;
3570       char *pos;
3571       if (strcasecmp (value, "YES") == 0)
3572         *result = yesval;
3573       else if (strcasecmp (value, "NO") == 0)
3574         *result = noval;
3575       else if (is_float && (f = strtod (value, &pos), pos != value))
3576         *result = make_float (f);
3577       else if (is_modstring && value)
3578         *result = ns_string_to_lispmod (value);
3579       else fprintf (stderr,
3580                    "Bad value for default \"%s\": \"%s\"\n", parameter, value);
3581     }
3585 void
3586 ns_initialize_display_info (struct ns_display_info *dpyinfo)
3587 /* --------------------------------------------------------------------------
3588       Initialize global info and storage for display.
3589    -------------------------------------------------------------------------- */
3591     NSScreen *screen = [NSScreen mainScreen];
3592     NSWindowDepth depth = [screen depth];
3594     dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
3595     dpyinfo->resy = 72.27;
3596     dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
3597                                                   NSColorSpaceFromDepth (depth)]
3598                 && ![NSCalibratedWhiteColorSpace isEqualToString:
3599                                                  NSColorSpaceFromDepth (depth)];
3600     dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
3601     dpyinfo->image_cache = make_image_cache ();
3602     dpyinfo->color_table
3603       = (struct ns_color_table *)xmalloc (sizeof (struct ns_color_table));
3604     dpyinfo->color_table->colors = NULL;
3605     dpyinfo->root_window = 42; /* a placeholder.. */
3607     dpyinfo->mouse_face_mouse_frame = NULL;
3608     dpyinfo->mouse_face_deferred_gc = 0;
3609     dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
3610     dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
3611     dpyinfo->mouse_face_face_id = DEFAULT_FACE_ID;
3612     dpyinfo->mouse_face_window = dpyinfo->mouse_face_overlay = Qnil;
3613     dpyinfo->mouse_face_hidden = 0;
3615     dpyinfo->mouse_face_mouse_x = dpyinfo->mouse_face_mouse_y = 0;
3616     dpyinfo->mouse_face_defer = 0;
3618     dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
3620     dpyinfo->n_fonts = 0;
3621     dpyinfo->smallest_font_height = 1;
3622     dpyinfo->smallest_char_width = 1;
3626 /* This and next define (many of the) public functions in this file. */
3627 /* x_... are generic versions in xdisp.c that we, and other terms, get away
3628          with using despite presence in the "system dependent" redisplay
3629          interface.  In addition, many of the ns_ methods have code that is
3630          shared with all terms, indicating need for further refactoring. */
3631 extern frame_parm_handler ns_frame_parm_handlers[];
3632 static struct redisplay_interface ns_redisplay_interface =
3634   ns_frame_parm_handlers,
3635   x_produce_glyphs,
3636   x_write_glyphs,
3637   x_insert_glyphs,
3638   x_clear_end_of_line,
3639   ns_scroll_run,
3640   ns_after_update_window_line,
3641   ns_update_window_begin,
3642   ns_update_window_end,
3643   x_cursor_to,
3644   ns_flush,
3645   0, /* flush_display_optional */
3646   x_clear_window_mouse_face,
3647   x_get_glyph_overhangs,
3648   x_fix_overlapping_area,
3649   ns_draw_fringe_bitmap,
3650   0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
3651   0, /* destroy_fringe_bitmap */
3652   ns_compute_glyph_string_overhangs,
3653   ns_draw_glyph_string, /* interface to nsfont.m */
3654   ns_define_frame_cursor,
3655   ns_clear_frame_area,
3656   ns_draw_window_cursor,
3657   ns_draw_vertical_window_border,
3658   ns_shift_glyphs_for_insert
3662 static void
3663 ns_delete_display (struct ns_display_info *dpyinfo)
3665   /* TODO... */
3669 /* This function is called when the last frame on a display is deleted. */
3670 static void
3671 ns_delete_terminal (struct terminal *terminal)
3673   struct ns_display_info *dpyinfo = terminal->display_info.ns;
3674   int i;
3676   /* Protect against recursive calls.  delete_frame in
3677      delete_terminal calls us back when it deletes our last frame.  */
3678   if (!terminal->name)
3679     return;
3681   BLOCK_INPUT;
3683   x_destroy_all_bitmaps (dpyinfo);
3684   ns_delete_display (dpyinfo);
3685   UNBLOCK_INPUT;
3689 static struct terminal *
3690 ns_create_terminal (struct ns_display_info *dpyinfo)
3691 /* --------------------------------------------------------------------------
3692       Set up use of NS before we make the first connection.
3693    -------------------------------------------------------------------------- */
3695   struct terminal *terminal;
3697   NSTRACE (ns_create_terminal);
3699   terminal = create_terminal ();
3701   terminal->type = output_ns;
3702   terminal->display_info.ns = dpyinfo;
3703   dpyinfo->terminal = terminal;
3705   terminal->rif = &ns_redisplay_interface;
3707   terminal->clear_frame_hook = ns_clear_frame;
3708   terminal->ins_del_lines_hook = 0; /* XXX vestigial? */
3709   terminal->delete_glyphs_hook = 0; /* XXX vestigial? */
3710   terminal->ring_bell_hook = ns_ring_bell;
3711   terminal->reset_terminal_modes_hook = ns_reset_terminal_modes;
3712   terminal->set_terminal_modes_hook = ns_set_terminal_modes;
3713   terminal->update_begin_hook = ns_update_begin;
3714   terminal->update_end_hook = ns_update_end;
3715   terminal->set_terminal_window_hook = NULL; /* XXX vestigial? */
3716   terminal->read_socket_hook = ns_read_socket;
3717   terminal->frame_up_to_date_hook = ns_frame_up_to_date;
3718   terminal->mouse_position_hook = ns_mouse_position;
3719   terminal->frame_rehighlight_hook = ns_frame_rehighlight;
3720   terminal->frame_raise_lower_hook = ns_frame_raise_lower;
3722   terminal->fullscreen_hook = 0; /* see XTfullscreen_hook */
3724   terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
3725   terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
3726   terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
3727   terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
3729   terminal->delete_frame_hook = x_destroy_window;
3730   terminal->delete_terminal_hook = ns_delete_terminal;
3732   terminal->scroll_region_ok = 1;
3733   terminal->char_ins_del_ok = 1;
3734   terminal->line_ins_del_ok = 1;
3735   terminal->fast_clear_end_of_line = 1;
3736   terminal->memory_below_frame = 0;
3738   return terminal;
3742 void
3743 ns_initialize ()
3744 /* --------------------------------------------------------------------------
3745    Mainly vestigial under NS now that ns_create_terminal () does most things.
3746    -------------------------------------------------------------------------- */
3748   baud_rate = 38400;
3749   Fset_input_interrupt_mode (Qt);
3753 struct ns_display_info *
3754 ns_term_init (Lisp_Object display_name)
3755 /* --------------------------------------------------------------------------
3756      Start the Application and get things rolling.
3757    -------------------------------------------------------------------------- */
3759   extern Lisp_Object Fset_input_mode (Lisp_Object, Lisp_Object,
3760                                      Lisp_Object, Lisp_Object);
3761   struct terminal *terminal;
3762   struct ns_display_info *dpyinfo;
3763   static int ns_initialized = 0;
3764   Lisp_Object tmp;
3766   NSTRACE (ns_term_init);
3768   /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
3769   /*GSDebugAllocationActive (YES); */
3770   BLOCK_INPUT;
3771   handling_signal = 0;
3773   if (!ns_initialized)
3774     {
3775       ns_initialize ();
3776       ns_initialized = 1;
3777     }
3779   ns_pending_files = [[NSMutableArray alloc] init];
3780   ns_pending_service_names = [[NSMutableArray alloc] init];
3781   ns_pending_service_args = [[NSMutableArray alloc] init];
3783   /* Start app and create the main menu, window, view.
3784      Needs to be here because ns_initialize_display_info () uses AppKit classes.
3785      The view will then ask the NSApp to stop and return to Emacs. */
3786   [EmacsApp sharedApplication];
3787   if (NSApp == nil)
3788     return NULL;
3789   [NSApp setDelegate: NSApp];
3791   /* debugging: log all notifications */
3792   /*   [[NSNotificationCenter defaultCenter] addObserver: NSApp
3793                                          selector: @selector (logNotification:)
3794                                              name: nil object: nil]; */
3796   dpyinfo = (struct ns_display_info *)xmalloc (sizeof (struct ns_display_info));
3797   bzero (dpyinfo, sizeof (struct ns_display_info));
3799   ns_initialize_display_info (dpyinfo);
3800   terminal = ns_create_terminal (dpyinfo);
3802   terminal->kboard = (KBOARD *) xmalloc (sizeof (KBOARD));
3803   init_kboard (terminal->kboard);
3804   terminal->kboard->Vwindow_system = Qns;
3805   terminal->kboard->next_kboard = all_kboards;
3806   all_kboards = terminal->kboard;
3807   /* Don't let the initial kboard remain current longer than necessary.
3808      That would cause problems if a file loaded on startup tries to
3809      prompt in the mini-buffer.  */
3810   if (current_kboard == initial_kboard)
3811     current_kboard = terminal->kboard;
3812   terminal->kboard->reference_count++;
3814   dpyinfo->next = x_display_list;
3815   x_display_list = dpyinfo;
3817   /* Put it on ns_display_name_list */
3818   ns_display_name_list = Fcons (Fcons (display_name, Qnil),
3819                                 ns_display_name_list);
3820   dpyinfo->name_list_element = XCAR (ns_display_name_list);
3822   /* Set the name of the terminal. */
3823   terminal->name = (char *) xmalloc (SBYTES (display_name) + 1);
3824   strncpy (terminal->name, SDATA (display_name), SBYTES (display_name));
3825   terminal->name[SBYTES (display_name)] = 0;
3827   UNBLOCK_INPUT; 
3829   /* Read various user defaults. */
3830   ns_set_default_prefs ();
3831   if (!ns_no_defaults)
3832     {
3833       ns_default ("AlternateModifier", &ns_alternate_modifier,
3834                  Qnil, Qnil, NO, YES);
3835       if (NILP (ns_alternate_modifier))
3836         ns_alternate_modifier = Qmeta;
3837       ns_default ("CommandModifier", &ns_command_modifier,
3838                  Qnil, Qnil, NO, YES);
3839       if (NILP (ns_command_modifier))
3840         ns_command_modifier = Qsuper;
3841       ns_default ("ControlModifier", &ns_control_modifier,
3842                  Qnil, Qnil, NO, YES);
3843       if (NILP (ns_control_modifier))
3844         ns_control_modifier = Qcontrol;
3845       ns_default ("FunctionModifier", &ns_function_modifier,
3846                  Qnil, Qnil, NO, YES);
3847       if (NILP (ns_function_modifier))
3848         ns_function_modifier = Qnone;
3849       ns_default ("ExpandSpace", &ns_expand_space,
3850                  make_float (0.5), make_float (0.0), YES, NO);
3851       ns_default ("GSFontAntiAlias", &ns_antialias_text,
3852                  Qt, Qnil, NO, NO);
3853       tmp = Qnil;
3854       ns_default ("AppleAntiAliasingThreshold", &tmp,
3855                  make_float (10.0), make_float (6.0), YES, NO);
3856       ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
3857       ns_default ("UseQuickdrawSmoothing", &ns_use_qd_smoothing,
3858                  Qt, Qnil, NO, NO);
3859       ns_default ("UseSystemHighlightColor", &ns_use_system_highlight_color,
3860                  Qt, Qnil, NO, NO);
3861     }
3863   if (EQ (ns_use_system_highlight_color, Qt))
3864     {
3865       ns_selection_color = [[NSUserDefaults standardUserDefaults]
3866                                stringForKey: @"AppleHighlightColor"];
3867       if (ns_selection_color == nil)
3868         ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
3869     }
3870   else
3871     ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
3873   {
3874     NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
3876     if ( cl == nil )
3877       {
3878         Lisp_Object color_file, color_map, color;
3879         int r,g,b;
3880         unsigned long c;
3881         char *name;
3883         color_file = Fexpand_file_name (build_string ("rgb.txt"),
3884                          Fsymbol_value (intern ("data-directory")));
3885         if (NILP (Ffile_readable_p (color_file)))
3886           fatal ("Could not find %s.\n", SDATA (color_file));
3888         color_map = Fx_load_color_file (color_file);
3889         if (NILP (color_map))
3890           fatal ("Could not read %s.\n", SDATA (color_file));
3892         cl = [[NSColorList alloc] initWithName: @"Emacs"];
3893         for ( ; CONSP (color_map); color_map = XCDR (color_map))
3894           {
3895             color = XCAR (color_map);
3896             name = SDATA (XCAR (color));
3897             c = XINT (XCDR (color));
3898             [cl setColor:
3899                   [NSColor colorWithCalibratedRed: RED_FROM_ULONG (c) / 255.0
3900                                             green: GREEN_FROM_ULONG (c) / 255.0
3901                                              blue: BLUE_FROM_ULONG (c) / 255.0
3902                                             alpha: 1.0]
3903                   forKey: [NSString stringWithUTF8String: name]];
3904           }
3905         [cl writeToFile: nil];
3906       }
3907   }
3909   {
3910     char c[128];
3911 #ifdef NS_IMPL_GNUSTEP
3912     strncpy (c, gnustep_base_version, sizeof (c));
3913 #else
3914     /*PSnextrelease (128, c); */
3915     snprintf (c, sizeof (c), "%g", NSAppKitVersionNumber);
3916 #endif
3917     Vwindow_system_version = build_string (c);
3918   }
3920   delete_keyboard_wait_descriptor (0);
3922 /* Set up OS X app menu */
3923 #ifdef NS_IMPL_COCOA
3924   {
3925     NSMenu *appMenu;
3926     NSMenuItem *item;
3927     /* set up the application menu */
3928     svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
3929     [svcsMenu setAutoenablesItems: NO];
3930     appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
3931     [appMenu setAutoenablesItems: NO];
3932     mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
3933     dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
3935     [appMenu insertItemWithTitle: @"About Emacs"
3936                           action: @selector (orderFrontStandardAboutPanel:)
3937                    keyEquivalent: @""
3938                          atIndex: 0];
3939     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
3940     [appMenu insertItemWithTitle: @"Preferences..."
3941                           action: @selector (showPreferencesWindow:)
3942                    keyEquivalent: @","
3943                          atIndex: 2];
3944     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
3945     item = [appMenu insertItemWithTitle: @"Services"
3946                                  action: @selector (menuDown:)
3947                           keyEquivalent: @""
3948                                 atIndex: 4];
3949     [appMenu setSubmenu: svcsMenu forItem: item];
3950 /*    [svcsMenu setSupercell: item]; */
3951     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
3952     [appMenu insertItemWithTitle: @"Hide Emacs"
3953                           action: @selector (hide:)
3954                    keyEquivalent: @"h"
3955                          atIndex: 6];
3956     item =  [appMenu insertItemWithTitle: @"Hide Others"
3957                           action: @selector (hideOtherApplications:)
3958                    keyEquivalent: @"h"
3959                          atIndex: 7];
3960     [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
3961     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
3962     [appMenu insertItemWithTitle: @"Quit Emacs"
3963                           action: @selector (terminate:)
3964                    keyEquivalent: @"q"
3965                          atIndex: 9];
3967     item = [mainMenu insertItemWithTitle: @"Emacs"
3968                                   action: @selector (menuDown:)
3969                            keyEquivalent: @""
3970                                  atIndex: 0];
3971     [mainMenu setSubmenu: appMenu forItem: item];
3972     [dockMenu insertItemWithTitle: @"New Frame"
3973                            action: @selector (newFrame:)
3974                     keyEquivalent: @""
3975                           atIndex: 0];
3977     [NSApp setMainMenu: mainMenu];
3978     [NSApp setAppleMenu: appMenu];
3979     [NSApp setServicesMenu: svcsMenu];
3980     /* Needed at least on Cocoa, to get dock menu to show windows */
3981     [NSApp setWindowsMenu: [[NSMenu alloc] init]];
3982   }
3983 #endif /* MAC OS X menu setup */
3985   [NSApp run];
3987   return dpyinfo;
3991 extern Lisp_Object Vauto_save_list_file_name;
3992 void
3993 ns_term_shutdown (int sig)
3995   /* code not reached in emacs.c after this is called by shut_down_emacs: */
3996   if (STRINGP (Vauto_save_list_file_name))
3997     unlink (SDATA (Vauto_save_list_file_name));
3999   if (sig == 0 || sig == SIGTERM)
4000     {
4001       ns_shutdown_properly = YES;
4002       [NSApp terminate: NSApp];
4003     }
4004   else // force a stack trace to happen
4005     {
4006       abort();
4007     }
4011 /* ==========================================================================
4013     EmacsApp implementation
4015    ========================================================================== */
4018 @implementation EmacsApp
4020 - (void)logNotification: (NSNotification *)notification
4022   const char *name = [[notification name] UTF8String];
4023   if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4024       && !strstr (name, "WindowNumber"))
4025     NSLog (@"notification: '%@'", [notification name]);
4029 - (void)sendEvent: (NSEvent *)theEvent
4030 /* --------------------------------------------------------------------------
4031      Events posted by ns_send_appdefined interrupt the run loop here
4032    -------------------------------------------------------------------------- */
4034   int type = [theEvent type];
4035   NSWindow *window = [theEvent window];
4036 /*  NSTRACE (sendEvent); */
4037 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4039   if (type == NSCursorUpdate && window == nil)
4040     {
4041       fprintf (stderr, "Dropping external cursor update event.\n");
4042       return;
4043     }
4045 #ifdef NS_IMPL_COCOA
4046   /* pass mouse down in resize handle and subsequent drags directly to
4047      EmacsWindow so we can generate continuous redisplays */
4048   if (ns_in_resize)
4049     {
4050       if (type == NSLeftMouseDragged)
4051         {
4052           [window mouseDragged: theEvent];
4053           return;
4054         }
4055       else if (type == NSLeftMouseUp)
4056         {
4057           [window mouseUp: theEvent];
4058           return;
4059         }
4060     }
4061   else if (type == NSLeftMouseDown)
4062     {
4063       NSRect r = ns_resize_handle_rect (window);
4064       if (NSPointInRect ([theEvent locationInWindow], r))
4065         {
4066           ns_in_resize = YES;
4067           [window mouseDown: theEvent];
4068           return;
4069         }
4070     }
4071 #endif
4073   if (type == NSApplicationDefined)
4074     {
4075       last_appdefined_event = theEvent;
4076       [self stop: self];
4077     }
4079   [super sendEvent: theEvent];
4083 - (void)showPreferencesWindow: (id)sender
4085   if (prefsController == nil)
4086     prefsController = [[EmacsPrefsController alloc] init];
4087   [prefsController showForFrame: SELECTED_FRAME ()];
4091 - (void)newFrame: (id)sender
4093   struct frame *emacsframe = SELECTED_FRAME ();
4094   NSEvent *theEvent = [NSApp currentEvent];
4096   if (!emacs_event)
4097     return;
4098   emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4099   emacs_event->code = KEY_NS_NEW_FRAME;
4100   emacs_event->modifiers = 0;
4101   EV_TRAILER (theEvent);
4105 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4106 - (BOOL) openFile: (NSString *)fileName
4108   struct frame *emacsframe = SELECTED_FRAME ();
4109   NSEvent *theEvent = [NSApp currentEvent];
4111   if (!emacs_event)
4112     return NO;
4114   emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4115   emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4116   ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4117   ns_input_line = Qnil; /* can be start or cons start,end */
4118   emacs_event->modifiers =0;
4119   EV_TRAILER (theEvent);
4121   return YES;
4125 /* **************************************************************************
4127       EmacsApp delegate implementation
4129    ************************************************************************** */
4131 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4132 /* --------------------------------------------------------------------------
4133      When application is loaded, terminate event loop in ns_term_init
4134    -------------------------------------------------------------------------- */
4136   NSTRACE (applicationDidFinishLaunching);
4137   [NSApp setServicesProvider: NSApp];
4138   ns_send_appdefined (-2);
4142 /* Termination sequences (ns_shutdown_properly):
4143     C-x C-c:
4144     Cmd-Q:
4145     MenuBar | File | Exit:
4146         ns_term_shutdown: 0
4147         received -terminate: 1
4148         received -appShouldTerminate: 1
4150     Select Quit from App menubar:
4151         received -terminate: 0
4152         ns_term_shutdown: 0
4153         received -terminate: 1
4154         received -appShouldTerminate: 1
4156     Select Quit from Dock menu:
4157     Logout attempt:
4158         received -appShouldTerminate: 0
4159           Cancel -> Nothing else
4160           Accept ->
4161             received -terminate: 0
4162             ns_term_shutdown: 0
4163             received -terminate: 1
4164             received -appShouldTerminate: 1
4167 - (void) terminate: (id)sender
4169   if (ns_shutdown_properly)
4170     [super terminate: sender];
4171   else
4172     {
4173       struct frame *emacsframe = SELECTED_FRAME ();
4175       if (!emacs_event)
4176         return;
4178       ns_shutdown_properly = YES;
4179       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4180       emacs_event->code = KEY_NS_POWER_OFF;
4181       EV_TRAILER ((id)nil);
4182     }
4186 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4188   int ret;
4190   if (ns_shutdown_properly)
4191     return NSTerminateNow;
4193   /* XXX: This while() loop is needed because if the user switches to another
4194           application while the panel is up, it is taken down w/a return value
4195           of -1000, and the event queue gets messed up.  In this case resend
4196           the appdefined and put up the window again. */
4197   while (1) {
4198     ret = NSRunAlertPanel([[NSProcessInfo processInfo] processName],
4199                           [NSString stringWithUTF8String:"Exit requested.  Would you like to Save Buffers and Exit, or Cancel the request?"],
4200                           @"Save Buffers and Exit", @"Cancel", nil);
4202     if (ret == NSAlertDefaultReturn)
4203       {
4204         send_appdefined = YES;
4205         ns_send_appdefined(-1);
4206         return NSTerminateNow;
4207       }
4208     else if (ret == NSAlertAlternateReturn)
4209       {
4210         send_appdefined = YES;
4211         ns_send_appdefined(-1);
4212         return NSTerminateCancel;
4213       }
4214   }
4218 /*   Notification from the Workspace to open a file */
4219 - (BOOL)application: sender openFile: (NSString *)file
4221   [ns_pending_files addObject: file];
4222   return YES;
4226 /*   Open a file as a temporary file */
4227 - (BOOL)application: sender openTempFile: (NSString *)file
4229   [ns_pending_files addObject: file];
4230   return YES;
4234 /*   Notification from the Workspace to open a file noninteractively (?) */
4235 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4237   [ns_pending_files addObject: file];
4238   return YES;
4242 /*   Notification from the Workspace to open multiple files */
4243 - (void)application: sender openFiles: (NSArray *)fileList
4245   NSEnumerator *files = [fileList objectEnumerator];
4246   NSString *file;
4247   while ((file = [files nextObject]) != nil)
4248     [ns_pending_files addObject: file];
4250 /* TODO: when GNUstep implements this (and we require that version of
4251          GNUstep), remove. */
4252 #ifndef NS_IMPL_GNUSTEP
4253   [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4254 #endif /* !NS_IMPL_GNUSTEP */
4259 /* Handle dock menu requests.  */
4260 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4262   return dockMenu;
4266 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4267 - (void)applicationWillBecomeActive: (NSNotification *)notification
4269   //ns_app_active=YES;
4271 - (void)applicationDidBecomeActive: (NSNotification *)notification
4273   //ns_app_active=YES;
4275 - (void)applicationDidResignActive: (NSNotification *)notification
4277   //ns_app_active=NO;
4278   ns_send_appdefined (-1);
4283 /* ==========================================================================
4285     EmacsApp aux handlers for managing event loop
4287    ========================================================================== */
4290 - (void)timeout_handler: (NSTimer *)timedEntry
4291 /* --------------------------------------------------------------------------
4292      The timeout specified to ns_select has passed.
4293    -------------------------------------------------------------------------- */
4295   /*NSTRACE (timeout_handler); */
4296   ns_send_appdefined (-2);
4299 extern void update_window_cursor (struct window *w, int on);
4301 - (void)fd_handler: (NSTimer *) fdEntry
4302 /* --------------------------------------------------------------------------
4303      Check data waiting on file descriptors and terminate if so
4304    -------------------------------------------------------------------------- */
4306   int result;
4307   /* NSTRACE (fd_handler); */
4309   if (select_nfds == 0)
4310     return;
4312   memcpy (&t_readfds, &select_readfds, sizeof (fd_set));
4314   select_timeout.tv_sec = select_timeout.tv_usec = 0;
4315   result = select (select_nfds, &t_readfds, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
4316                   &select_timeout);
4317   if (result)
4318     {
4319       memcpy (&select_readfds, &t_readfds, sizeof (fd_set));
4320       ns_send_appdefined (result);
4321     }
4326 /* ==========================================================================
4328     Service provision
4330    ========================================================================== */
4332 /* called from system: queue for next pass through event loop */
4333 - (void)requestService: (NSPasteboard *)pboard
4334               userData: (NSString *)userData
4335                  error: (NSString **)error
4337   [ns_pending_service_names addObject: userData];
4338   [ns_pending_service_args addObject: [NSString stringWithUTF8String:
4339       SDATA (ns_string_from_pasteboard (pboard))]];
4343 /* called from ns_read_socket to clear queue */
4344 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
4346   struct frame *emacsframe = SELECTED_FRAME ();
4347   NSEvent *theEvent = [NSApp currentEvent];
4349   if (!emacs_event)
4350     return NO;
4352   emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4353   emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
4354   ns_input_spi_name = build_string ([name UTF8String]);
4355   ns_input_spi_arg = build_string ([arg UTF8String]);
4356   emacs_event->modifiers = EV_MODIFIERS (theEvent);
4357   EV_TRAILER (theEvent);
4359   return YES;
4363 @end  /* EmacsApp */
4367 /* ==========================================================================
4369     EmacsView implementation
4371    ========================================================================== */
4374 @implementation EmacsView
4376 /* needed to inform when window closed from LISP */
4377 - (void) setWindowClosing: (BOOL)closing
4379   windowClosing = closing;
4383 - (void)dealloc
4385   NSTRACE (EmacsView_dealloc);
4386   [toolbar release];
4387   [super dealloc];
4391 /* called on font panel selection */
4392 - (void)changeFont: (id)sender
4394   NSEvent *e =[[self window] currentEvent];
4395   struct face *face =FRAME_DEFAULT_FACE (emacsframe);
4396   id newFont;
4397   float size;
4399   NSTRACE (changeFont);
4400   if (!emacs_event)
4401     return;
4403   if (newFont = [sender convertFont:
4404                            ((struct nsfont_info *)face->font)->nsfont])
4405     {
4406       SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
4408       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4409       emacs_event->modifiers = 0;
4410       emacs_event->code = KEY_NS_CHANGE_FONT;
4412       size = [newFont pointSize];
4413       ns_input_fontsize = make_number (lrint (size));
4414       ns_input_font = build_string ([[newFont familyName] UTF8String]);
4415       EV_TRAILER (e);
4416     }
4420 - (BOOL)acceptsFirstResponder
4422   NSTRACE (acceptsFirstResponder);
4423   return YES;
4427 - (void)resetCursorRects
4429   NSRect visible = [self visibleRect];
4430   NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
4431   NSTRACE (resetCursorRects);
4433   if (currentCursor == nil)
4434     currentCursor = [NSCursor arrowCursor];
4436   if (!NSIsEmptyRect (visible))
4437     [self addCursorRect: visible cursor: currentCursor];
4438   [currentCursor setOnMouseEntered: YES];
4443 /*****************************************************************************/
4444 /* Keyboard handling. */
4445 #define NS_KEYLOG 0
4447 - (void)keyDown: (NSEvent *)theEvent
4449   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4450   int code;
4451   unsigned fnKeysym = 0;
4452   int flags;
4453   static NSMutableArray *nsEvArray;
4454   static BOOL firstTime = YES;
4456   NSTRACE (keyDown);
4458   /* Rhapsody and OS X give up and down events for the arrow keys */
4459   if (ns_fake_keydown == YES)
4460     ns_fake_keydown = NO;
4461   else if ([theEvent type] != NSKeyDown)
4462     return;
4464   if (!emacs_event)
4465     return;
4467  if (![[self window] isKeyWindow])
4468    {
4469      /* XXX: Using NO_SOCK_SIGIO like Carbon causes a condition in which,
4470          when Emacs display updates a different frame from the current one,
4471          and temporarily selects it, then processes some interrupt-driven
4472          input (dispnew.c:3878), OS will send the event to the correct NSWindow,
4473          but for some reason that window has its first responder set to the
4474          NSView most recently updated (I guess), which is not the correct one.
4475          UPDATE: After multi-TTY merge this happens even w/o NO_SOCK_SIGIO */
4476      if ([[theEvent window] isKindOfClass: [EmacsWindow class]])
4477          [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
4478      return;
4479    }
4481   if (nsEvArray == nil)
4482     nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
4484   [NSCursor setHiddenUntilMouseMoves: YES];
4486   if (dpyinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
4487     {
4488       clear_mouse_face (dpyinfo);
4489       dpyinfo->mouse_face_hidden = 1;
4490     }
4492   if (!processingCompose)
4493     {
4494       code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
4495         0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
4496       /* (Carbon way: [theEvent keyCode]) */
4498       /* is it a "function key"? */
4499       fnKeysym = ns_convert_key (code);
4500       if (fnKeysym)
4501         {
4502           /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
4503              because Emacs treats Delete and KP-Delete same (in simple.el). */
4504           if (fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
4505             code = 0xFF08; /* backspace */
4506           else
4507             code = fnKeysym;
4508         }
4510       /* are there modifiers? */
4511       emacs_event->modifiers = 0;
4512       flags = [theEvent modifierFlags];
4514       if (flags & NSHelpKeyMask)
4515           emacs_event->modifiers |= hyper_modifier;
4517       if (flags & NSShiftKeyMask)
4518         emacs_event->modifiers |= shift_modifier;
4520       if (flags & NSCommandKeyMask)
4521         {
4522           emacs_event->modifiers |= parse_solitary_modifier (ns_command_modifier);
4523           /* if super (default), take input manager's word so things like
4524              dvorak / qwerty layout work */
4525           if (EQ (ns_command_modifier, Qsuper)
4526               && !fnKeysym
4527               && [[theEvent characters] length] != 0)
4528             {
4529               /* XXX: the code we get will be unshifted, so if we have
4530                  a shift modifier, must convert ourselves */
4531               if (!(flags & NSShiftKeyMask))
4532                 code = [[theEvent characters] characterAtIndex: 0];
4533 #if 0
4534               /* this is ugly and also requires linking w/Carbon framework
4535                  (for LMGetKbdType) so for now leave this rare (?) case
4536                  undealt with.. in future look into CGEvent methods */
4537               else
4538                 {
4539                   long smv = GetScriptManagerVariable (smKeyScript);
4540                   Handle uchrHandle = GetResource
4541                     ('uchr', GetScriptVariable (smv, smScriptKeys));
4542                   UInt32 dummy = 0;
4543                   UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
4544                                  [[theEvent characters] characterAtIndex: 0],
4545                                  kUCKeyActionDisplay,
4546                                  (flags & ~NSCommandKeyMask) >> 8,
4547                                  LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
4548                                  &dummy, 1, &dummy, &code);
4549                   code &= 0xFF;
4550                 }
4551 #endif
4552             }
4553         }
4555       if (flags & NSControlKeyMask)
4556           emacs_event->modifiers |=
4557             parse_solitary_modifier (ns_control_modifier);
4559       if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
4560           emacs_event->modifiers |=
4561             parse_solitary_modifier (ns_function_modifier);
4563       if (flags & NSAlternateKeyMask) /* default = meta */
4564         {
4565           if ((NILP (ns_alternate_modifier) || EQ (ns_alternate_modifier, Qnone))
4566               && !fnKeysym)
4567             {   /* accept pre-interp alt comb */
4568               if ([[theEvent characters] length] > 0)
4569                 code = [[theEvent characters] characterAtIndex: 0];
4570               /*HACK: clear lone shift modifier to stop next if from firing */
4571               if (emacs_event->modifiers == shift_modifier)
4572                 emacs_event->modifiers = 0;
4573             }
4574           else
4575               emacs_event->modifiers |=
4576                 parse_solitary_modifier (ns_alternate_modifier);
4577         }
4579   if (NS_KEYLOG)
4580     fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
4581              code, fnKeysym, flags, emacs_event->modifiers);
4583       /* if it was a function key or had modifiers, pass it directly to emacs */
4584       if (fnKeysym || (emacs_event->modifiers
4585                        && [[theEvent charactersIgnoringModifiers] length] > 0))
4586 /*[[theEvent characters] length] */
4587         {
4588           emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4589           if (code < 0x20)
4590             code |= (1<<28)|(3<<16);
4591           else if (code == 0x7f)
4592             code |= (1<<28)|(3<<16);
4593           else if (!fnKeysym)
4594             emacs_event->kind = code > 0xFF
4595               ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4597           emacs_event->code = code;
4598           EV_TRAILER (theEvent);
4599           return;
4600         }
4601     }
4603   /* if we get here we should send the key for input manager processing */
4604   if (firstTime && [[NSInputManager currentInputManager]
4605                      wantsToDelayTextChangeNotifications] == NO)
4606     fprintf (stderr,
4607           "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
4608   firstTime = NO;
4610   if (NS_KEYLOG && !processingCompose)
4611     fprintf (stderr, "keyDown: Begin compose sequence.\n");
4613   processingCompose = YES;
4614   [nsEvArray addObject: theEvent];
4615   [self interpretKeyEvents: nsEvArray];
4616   [nsEvArray removeObject: theEvent];
4620 #ifdef NS_IMPL_COCOA
4621 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
4622    decided not to send key-down for.
4623    See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
4624    If it matches one of these, send it on to keyDown. */
4625 -(void)keyUp: (NSEvent *)theEvent
4627   int flags = [theEvent modifierFlags];
4628   int code = [theEvent keyCode];
4629   if (code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
4630     {
4631       if (NS_KEYLOG)
4632         fprintf (stderr, "keyUp: passed test");
4633       ns_fake_keydown = YES;
4634       [self keyDown: theEvent];
4635     }
4637 #endif
4640 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
4643 /* <NSTextInput>: called when done composing;
4644    NOTE: also called when we delete over working text, followed immed.
4645          by doCommandBySelector: deleteBackward: */
4646 - (void)insertText: (id)aString
4648   int code;
4649   int len = [(NSString *)aString length];
4650   int i;
4652   if (NS_KEYLOG)
4653     NSLog (@"insertText '%@'\tlen = %d", aString, len);
4654   processingCompose = NO;
4656   if (!emacs_event)
4657     return;
4659   /* first, clear any working text */
4660   if (workingText != nil)
4661     [self deleteWorkingText];
4663   /* now insert the string as keystrokes */
4664   for (i =0; i<len; i++)
4665     {
4666       code = [aString characterAtIndex: i];
4667       /* TODO: still need this? */
4668       if (code == 0x2DC)
4669         code = '~'; /* 0x7E */
4670       emacs_event->modifiers = 0;
4671       emacs_event->kind
4672         = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4673       emacs_event->code = code;
4674       EV_TRAILER ((id)nil);
4675     }
4679 /* <NSTextInput>: inserts display of composing characters */
4680 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
4682   NSString *str = [aString respondsToSelector: @selector (string)] ?
4683     [aString string] : aString;
4684   if (NS_KEYLOG)
4685     NSLog (@"setMarkedText '%@' len =%d range %d from %d", str, [str length],
4686            selRange.length, selRange.location);
4688   if (workingText != nil)
4689     [self deleteWorkingText];
4690   if ([str length] == 0)
4691     return;
4693   if (!emacs_event)
4694     return;
4696   processingCompose = YES;
4697   workingText = [str copy];
4698   ns_working_text = build_string ([workingText UTF8String]);
4700   emacs_event->kind = NS_TEXT_EVENT;
4701   emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
4702   EV_TRAILER ((id)nil);
4706 /* delete display of composing characters [not in <NSTextInput>] */
4707 - (void)deleteWorkingText
4709   if (workingText == nil)
4710     return;
4711   if (NS_KEYLOG)
4712     NSLog(@"deleteWorkingText len =%d\n", [workingText length]);
4713   [workingText release];
4714   workingText = nil;
4715   processingCompose = NO;
4717   if (!emacs_event)
4718     return;
4720   emacs_event->kind = NS_TEXT_EVENT;
4721   emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
4722   EV_TRAILER ((id)nil);
4726 - (BOOL)hasMarkedText
4728   return workingText != nil;
4732 - (NSRange)markedRange
4734   NSRange rng = workingText != nil
4735     ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
4736   if (NS_KEYLOG)
4737     NSLog (@"markedRange request");
4738   return rng;
4742 - (void)unmarkText
4744   if (NS_KEYLOG)
4745     NSLog (@"unmark (accept) text");
4746   [self deleteWorkingText];
4747   processingCompose = NO;
4751 /* used to position char selection windows, etc. */
4752 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
4754   NSRect rect;
4755   NSPoint pt;
4756   struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
4757   if (NS_KEYLOG)
4758     NSLog (@"firstRectForCharRange request");
4760   rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
4761   rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
4762   pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
4763   pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
4764                                        +FRAME_LINE_HEIGHT (emacsframe));
4766   pt = [self convertPoint: pt toView: nil];
4767   pt = [[self window] convertBaseToScreen: pt];
4768   rect.origin = pt;
4769   return rect;
4773 - (NSInteger)conversationIdentifier
4775   return (NSInteger)self;
4779 - (void)doCommandBySelector: (SEL)aSelector
4781   if (NS_KEYLOG)
4782     NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
4784   if (aSelector == @selector (deleteBackward:))
4785     {
4786       /* happens when user backspaces over an ongoing composition:
4787          throw a 'delete' into the event queue */
4788       if (!emacs_event)
4789         return;
4790       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4791       emacs_event->code = 0xFF08;
4792       EV_TRAILER ((id)nil);
4793     }
4796 - (NSArray *)validAttributesForMarkedText
4798   static NSArray *arr = nil;
4799   if (arr == nil) arr = [NSArray new];
4800  /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
4801   return arr;
4804 - (NSRange)selectedRange
4806   if (NS_KEYLOG)
4807     NSLog (@"selectedRange request");
4808   return NSMakeRange (NSNotFound, 0);
4811 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
4813   if (NS_KEYLOG)
4814     NSLog (@"characterIndexForPoint request");
4815   return 0;
4818 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
4820   static NSAttributedString *str = nil;
4821   if (str == nil) str = [NSAttributedString new];
4822   if (NS_KEYLOG)
4823     NSLog (@"attributedSubstringFromRange request");
4824   return str;
4827 /* End <NSTextInput> impl. */
4828 /*****************************************************************************/
4831 /* This is what happens when the user presses a mouse button.  */
4832 - (void)mouseDown: (NSEvent *)theEvent
4834   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
4835   Lisp_Object window;
4837   NSTRACE (mouseDown);
4839   [self deleteWorkingText];
4841   if (!emacs_event)
4842     return;
4844   last_mouse_frame = emacsframe;
4845   /* appears to be needed to prevent spurious movement events generated on
4846      button clicks */
4847   last_mouse_frame->mouse_moved = 0;
4849   if ([theEvent type] == NSScrollWheel)
4850     {
4851       float delta = [theEvent deltaY];
4852       /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
4853       if (delta == 0)
4854         return;
4855       emacs_event->kind = WHEEL_EVENT;
4856       emacs_event->code = 0;
4857       emacs_event->modifiers = EV_MODIFIERS (theEvent) |
4858         ((delta > 0) ? up_modifier : down_modifier);
4859     }
4860   else
4861     {
4862       emacs_event->kind = MOUSE_CLICK_EVENT;
4863       emacs_event->code = EV_BUTTON (theEvent);
4864       emacs_event->modifiers = EV_MODIFIERS (theEvent)
4865                              | EV_UDMODIFIERS (theEvent);
4866     }
4867   XSETINT (emacs_event->x, lrint (p.x));
4868   XSETINT (emacs_event->y, lrint (p.y));
4869   EV_TRAILER (theEvent);
4873 - (void)rightMouseDown: (NSEvent *)theEvent
4875   NSTRACE (rightMouseDown);
4876   [self mouseDown: theEvent];
4880 - (void)otherMouseDown: (NSEvent *)theEvent
4882   NSTRACE (otherMouseDown);
4883   [self mouseDown: theEvent];
4887 - (void)mouseUp: (NSEvent *)theEvent
4889   NSTRACE (mouseUp);
4890   [self mouseDown: theEvent];
4894 - (void)rightMouseUp: (NSEvent *)theEvent
4896   NSTRACE (rightMouseUp);
4897   [self mouseDown: theEvent];
4901 - (void)otherMouseUp: (NSEvent *)theEvent
4903   NSTRACE (otherMouseUp);
4904   [self mouseDown: theEvent];
4908 - (void) scrollWheel: (NSEvent *)theEvent
4910   NSTRACE (scrollWheel);
4911   [self mouseDown: theEvent];
4915 /* Tell emacs the mouse has moved. */
4916 - (void)mouseMoved: (NSEvent *)e
4918   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4919   Lisp_Object frame;
4921 //  NSTRACE (mouseMoved);
4923   last_mouse_movement_time = EV_TIMESTAMP (e);
4924   last_mouse_motion_position
4925     = [self convertPoint: [e locationInWindow] fromView: nil];
4927   /* update any mouse face */
4928   if (dpyinfo->mouse_face_hidden)
4929     {
4930       dpyinfo->mouse_face_hidden = 0;
4931       clear_mouse_face (dpyinfo);
4932     }
4934   /* tooltip handling */
4935   previous_help_echo_string = help_echo_string;
4936   help_echo_string = Qnil;
4938   if (!note_mouse_movement (emacsframe, last_mouse_motion_position.x,
4939                             last_mouse_motion_position.y))
4940     help_echo_string = previous_help_echo_string;
4942   XSETFRAME (frame, emacsframe);
4943   if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
4944     {
4945       /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
4946          (note_mouse_highlight), which is called through the
4947          note_mouse_movement () call above */
4948       gen_help_event (help_echo_string, frame, help_echo_window,
4949                       help_echo_object, help_echo_pos);
4950     }
4951   else
4952     {
4953       help_echo_string = Qnil;
4954       gen_help_event (Qnil, frame, Qnil, Qnil, 0);
4955     }
4957   if (emacsframe->mouse_moved && send_appdefined)
4958     ns_send_appdefined (-1);
4962 - (void)mouseDragged: (NSEvent *)e
4964   NSTRACE (mouseDragged);
4965   [self mouseMoved: e];
4969 - (void)rightMouseDragged: (NSEvent *)e
4971   NSTRACE (rightMouseDragged);
4972   [self mouseMoved: e];
4976 - (void)otherMouseDragged: (NSEvent *)e
4978   NSTRACE (otherMouseDragged);
4979   [self mouseMoved: e];
4983 - (BOOL)windowShouldClose: (id)sender
4985   NSEvent *e =[[self window] currentEvent];
4987   NSTRACE (windowShouldClose);
4988   windowClosing = YES;
4989   if (!emacs_event)
4990     return NO;
4991   emacs_event->kind = DELETE_WINDOW_EVENT;
4992   emacs_event->modifiers = 0;
4993   emacs_event->code = 0;
4994   EV_TRAILER (e);
4995   /* Don't close this window, let this be done from lisp code.  */
4996   return NO;
5000 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
5001 /* normalize frame to gridded text size */
5003   NSTRACE (windowWillResize);
5004 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
5006   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe,
5007 #ifdef NS_IMPL_GNUSTEP
5008                                         frameSize.width + 3);
5009 #else
5010                                         frameSize.width);
5011 #endif
5012   if (cols < MINWIDTH)
5013     cols = MINWIDTH;
5014   frameSize.width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (emacsframe, cols);
5016   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, frameSize.height
5017 #ifdef NS_IMPL_GNUSTEP
5018       - FRAME_NS_TITLEBAR_HEIGHT (emacsframe) + 3
5019         - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
5020 #else
5021       - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5022         - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
5023 #endif
5024   if (rows < MINHEIGHT)
5025     rows = MINHEIGHT;
5026   frameSize.height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows)
5027                        + FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5028                        + FRAME_NS_TOOLBAR_HEIGHT (emacsframe);
5029 #ifdef NS_IMPL_COCOA
5030   {
5031     /* this sets window title to have size in it; the wm does this under GS */
5032     NSRect r = [[self window] frame];
5033     if (r.size.height == frameSize.height && r.size.width == frameSize.width)
5034       {
5035         if (old_title != 0)
5036           {
5037             xfree (old_title);
5038             old_title = 0;
5039           }
5040       }
5041     else
5042       {
5043         char *size_title;
5044         NSWindow *window = [self window];
5045         if (old_title == 0)
5046           {
5047             const char *t = [[[self window] title] UTF8String];
5048             char *pos = strstr (t, "  â€”  ");
5049             if (pos)
5050               *pos = '\0';
5051             old_title = (char *) xmalloc (strlen (t) + 1);
5052             strcpy (old_title, t);
5053           }
5054         size_title = xmalloc (strlen (old_title) + 40);
5055         sprintf (size_title, "%s  â€”  (%d x %d)", old_title, cols, rows);
5056         [window setTitle: [NSString stringWithUTF8String: size_title]];
5057         [window display];
5058         xfree (size_title);
5059       }
5060   }
5061 #endif /* NS_IMPL_COCOA */
5062 /*fprintf (stderr,"    ...size became %.0f x %.0f  (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
5064   return frameSize;
5068 - (void)windowDidResize: (NSNotification *)notification
5070   NSWindow *theWindow = [notification object];
5072 #ifdef NS_IMPL_GNUSTEP
5073    /* in GNUstep, at least currently, it's possible to get a didResize
5074       without getting a willResize.. therefore we need to act as if we got
5075       the willResize now */
5076   NSSize sz = [theWindow frame].size;
5077   sz = [self windowWillResize: theWindow toSize: sz];
5078 #endif /* NS_IMPL_GNUSTEP */
5080   NSTRACE (windowDidResize);
5081 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
5083 #ifdef NS_IMPL_COCOA
5084   if (old_title != 0)
5085     {
5086       xfree (old_title);
5087       old_title = 0;
5088     }
5089 #endif /* NS_IMPL_COCOA */
5091   if (cols > 0 && rows > 0)
5092     x_set_window_size (emacsframe, 0, cols, rows);
5094   ns_send_appdefined (-1);
5096   /* The following line causes a crash on GNUstep.  Adrian Robert
5097      says he doesn't remember why he added this line, but removing it
5098      doesn't seem to cause problems on OSX, either.  */
5099 #if 0
5100   [NSApp stopModal];
5101 #endif
5105 - (void)windowDidBecomeKey: (NSNotification *)notification
5106 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5108   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5109   struct frame *old_focus = dpyinfo->x_focus_frame;
5111   NSTRACE (windowDidBecomeKey);
5113   if (emacsframe != old_focus)
5114     dpyinfo->x_focus_frame = emacsframe;
5116   ns_frame_rehighlight (emacsframe);
5118   if (emacs_event)
5119     {
5120       emacs_event->kind = FOCUS_IN_EVENT;
5121       EV_TRAILER ((id)nil);
5122     }
5126 - (void)windowDidResignKey: (NSNotification *)notification
5127 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5129   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5130   NSTRACE (windowDidResignKey);
5132   if (dpyinfo->x_focus_frame == emacsframe)
5133     dpyinfo->x_focus_frame = 0;
5135   ns_frame_rehighlight (emacsframe);
5137   /* FIXME: for some reason needed on second and subsequent clicks away
5138             from sole-frame Emacs to get hollow box to show */
5139   if (!windowClosing && [[self window] isVisible] == YES)
5140     {
5141       x_update_cursor (emacsframe, 1);
5142       x_set_frame_alpha (emacsframe);
5143     }
5145   if (emacs_event)
5146     {
5147       [self deleteWorkingText];
5148       emacs_event->kind = FOCUS_IN_EVENT;
5149       EV_TRAILER ((id)nil);
5150     }
5154 - (void)windowWillMiniaturize: sender
5156   NSTRACE (windowWillMiniaturize);
5160 - (BOOL)isFlipped
5162   return YES;
5166 - (BOOL)isOpaque
5168   return NO;
5172 - initFrameFromEmacs: (struct frame *)f
5174   NSRect r, wr;
5175   Lisp_Object tem;
5176   NSWindow *win;
5177   NSButton *toggleButton;
5178   int vbextra = NS_SCROLL_BAR_WIDTH (f);
5179   NSSize sz;
5180   NSColor *col;
5181   NSString *name;
5183   NSTRACE (initFrameFromEmacs);
5185   windowClosing = NO;
5186   processingCompose = NO;
5187   scrollbarsNeedingUpdate = 0;
5189 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
5191   r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
5192                  FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
5193   [self initWithFrame: r];
5195   FRAME_NS_VIEW (f) = self;
5196   emacsframe = f;
5197   old_title = 0;
5199   win = [[EmacsWindow alloc]
5200             initWithContentRect: r
5201                       styleMask: (NSResizableWindowMask |
5202                                   NSMiniaturizableWindowMask |
5203                                   NSClosableWindowMask)
5204                         backing: NSBackingStoreBuffered
5205                           defer: YES];
5207   wr = [win frame];
5208   f->border_width = wr.size.width - r.size.width;
5209   FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
5211   [win setAcceptsMouseMovedEvents: YES];
5212   [win setDelegate: self];
5213   [win useOptimizedDrawing: YES];
5215   sz.width = FRAME_COLUMN_WIDTH (f);
5216   sz.height = FRAME_LINE_HEIGHT (f);
5217   [win setResizeIncrements: sz];
5219   [[win contentView] addSubview: self];
5221   if (ns_drag_types)
5222     [self registerForDraggedTypes: ns_drag_types];
5224   tem = f->name;
5225   name = [NSString stringWithUTF8String:
5226                    NILP (tem) ? (unsigned char *)"Emacs" : SDATA (tem)];
5227   [win setTitle: name];
5229   /* toolbar support */
5230   toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
5231                          [NSString stringWithFormat: @"Emacs Frame %d",
5232                                    ns_window_num]];
5233   [win setToolbar: toolbar];
5234   [toolbar setVisible: NO];
5235 #ifdef NS_IMPL_COCOA
5236   toggleButton = [win standardWindowButton: NSWindowToolbarButton];
5237   [toggleButton setTarget: self];
5238   [toggleButton setAction: @selector (toggleToolbar: )];
5239 #endif
5240   FRAME_NS_TOOLBAR_HEIGHT (f) = 0;
5242   tem = f->icon_name;
5243   if (!NILP (tem))
5244     [win setMiniwindowTitle:
5245            [NSString stringWithUTF8String: SDATA (tem)]];
5247   {
5248     NSScreen *screen = [win screen];
5250     if (screen != 0)
5251       [win setFrameTopLeftPoint: NSMakePoint
5252            (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
5253             IN_BOUND (-SCREENMAX,
5254                      [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
5255   }
5257   [win makeFirstResponder: self];
5259   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5260                                   (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
5261   [win setBackgroundColor: col];
5262   if ([col alphaComponent] != 1.0)
5263     [win setOpaque: NO];
5265   [self allocateGState];
5267   ns_window_num++;
5268   return self;
5272 - (void)windowDidMove: sender
5274   NSWindow *win = [self window];
5275   NSRect r = [win frame];
5276   NSScreen *screen = [win screen];
5277   NSRect sr = [screen frame];
5279   NSTRACE (windowDidMove);
5281   if (!emacsframe->output_data.ns)
5282     return;
5283   if (screen != nil)
5284     {
5285       emacsframe->left_pos = r.origin.x; /* - sr.origin.x; */
5286       emacsframe->top_pos = sr.size.height -
5287         (r.origin.y + r.size.height); /* + sr.origin.y; */
5288     }
5291 #ifdef NS_IMPL_COCOA
5292 /* if we don't do this manually, the window will resize but not move */
5293 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
5295   [[self window] setFrame: newFrame display: NO];
5296   return YES;
5298 #endif
5300 /* Implement this to control size of frame on zoom.
5301 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
5302                         defaultFrame:(NSRect)defaultFrame; */
5305 - (void)windowDidDeminiaturize: sender
5307   NSTRACE (windowDidDeminiaturize);
5308   if (!emacsframe->output_data.ns)
5309     return;
5310   emacsframe->async_visible   = 1;
5311   emacsframe->async_iconified = 0;
5312   windows_or_buffers_changed++;
5314   if (emacs_event)
5315     {
5316       emacs_event->kind = ICONIFY_EVENT;
5317       EV_TRAILER ((id)nil);
5318     }
5322 - (void)windowDidExpose: sender
5324   NSTRACE (windowDidExpose);
5325   if (!emacsframe->output_data.ns)
5326     return;
5327   emacsframe->async_visible = 1;
5328   SET_FRAME_GARBAGED (emacsframe);
5330   if (send_appdefined)
5331     ns_send_appdefined (-1);
5335 - (void)windowDidMiniaturize: sender
5337   NSTRACE (windowDidMiniaturize);
5338   if (!emacsframe->output_data.ns)
5339     return;
5341   emacsframe->async_iconified = 1;
5343   if (emacs_event)
5344     {
5345       emacs_event->kind = ICONIFY_EVENT;
5346       EV_TRAILER ((id)nil);
5347     }
5351 - (void)mouseEntered: (NSEvent *)theEvent
5353   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5354   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5355   NSTRACE (mouseEntered);
5357   last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5361 - (void)mouseExited: (NSEvent *)theEvent
5363   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5364   NSRect r;
5365   struct ns_display_info *dpyinfo
5366     = emacsframe ? FRAME_NS_DISPLAY_INFO (emacsframe) : NULL;
5368   NSTRACE (mouseExited);
5370   if (dpyinfo || !emacsframe)
5371     return;
5373   last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5375   if (emacsframe == dpyinfo->mouse_face_mouse_frame)
5376     {
5377       clear_mouse_face (dpyinfo);
5378       dpyinfo->mouse_face_mouse_frame = 0;
5379     }
5383 - menuDown: sender
5385   NSTRACE (menuDown);
5386   if (context_menu_value == -1)
5387     context_menu_value = [sender tag];
5388   else
5389     find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
5390                                   emacsframe->menu_bar_vector,
5391                                   (void *)[sender tag]);
5392   ns_send_appdefined (-1);
5393   return self;
5397 - (EmacsToolbar *)toolbar
5399   return toolbar;
5403 /* this gets called on toolbar button click */
5404 - toolbarClicked: (id)item
5406   NSEvent *theEvent;
5407   int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
5409   NSTRACE (toolbarClicked);
5411   if (!emacs_event)
5412     return self;
5414   /* send first event (for some reason two needed) */
5415   theEvent = [[self window] currentEvent];
5416   emacs_event->kind = TOOL_BAR_EVENT;
5417   XSETFRAME (emacs_event->arg, emacsframe);
5418   EV_TRAILER (theEvent);
5420   emacs_event->kind = TOOL_BAR_EVENT;
5421 /*   XSETINT (emacs_event->code, 0); */
5422   emacs_event->arg = AREF (emacsframe->tool_bar_items,
5423                           idx + TOOL_BAR_ITEM_KEY);
5424   emacs_event->modifiers = EV_MODIFIERS (theEvent);
5425   EV_TRAILER (theEvent);
5426   return self;
5430 - toggleToolbar: (id)sender
5432   if (!emacs_event)
5433     return self;
5435   emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5436   emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
5437   EV_TRAILER ((id)nil);
5438   return self;
5442 - (void)drawRect: (NSRect)rect
5444   int x = NSMinX (rect), y = NSMinY (rect);
5445   int width = NSWidth (rect), height = NSHeight (rect);
5447   NSTRACE (drawRect);
5449   if (!emacsframe || !emacsframe->output_data.ns)
5450     return;
5452   if (!ns_in_resize)
5453     ns_clear_frame_area (emacsframe, x, y, width, height);
5454   expose_frame (emacsframe, x, y, width, height);
5456   emacsframe->async_visible = 1;
5457   emacsframe->async_iconified = 0;
5459 /*    SET_FRAME_GARBAGED (emacsframe);
5460       ns_send_appdefined (-1); */
5464 /* NSDraggingDestination protocol methods.  Actually this is not really a
5465    protocol, but a category of Object.  O well...  */
5467 -(unsigned int) draggingEntered: (id <NSDraggingInfo>) sender
5469   NSTRACE (draggingEntered);
5470   return NSDragOperationGeneric;
5474 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
5476   return YES;
5480 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
5482   id pb;
5483   int x, y;
5484   NSString *type;
5485   NSEvent *theEvent = [[self window] currentEvent];
5486   NSPoint position;
5488   NSTRACE (performDragOperation);
5490   if (!emacs_event)
5491     return;
5493   position = [self convertPoint: [sender draggingLocation] fromView: nil];
5494   x = lrint (position.x);  y = lrint (position.y);
5496   pb = [sender draggingPasteboard];
5497   type = [pb availableTypeFromArray: ns_drag_types];
5498   if (type == 0)
5499     {
5500       return NO;
5501     }
5502   else if ([type isEqualToString: NSFilenamesPboardType])
5503     {
5504       NSArray *files;
5505       NSEnumerator *fenum;
5506       NSString *file;
5508       if (!(files = [pb propertyListForType: type]))
5509         return NO;
5511       fenum = [files objectEnumerator];
5512       while ( (file = [fenum nextObject]) )
5513         {
5514           emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5515           emacs_event->code = KEY_NS_DRAG_FILE;
5516           XSETINT (emacs_event->x, x);
5517           XSETINT (emacs_event->y, y);
5518           ns_input_file = append2 (ns_input_file,
5519                                    build_string ([file UTF8String]));
5520           emacs_event->modifiers = EV_MODIFIERS (theEvent);
5521           EV_TRAILER (theEvent);
5522         }
5523       return YES;
5524     }
5525   else if ([type isEqualToString: NSURLPboardType])
5526     {
5527       NSString *file;
5528       NSURL *fileURL;
5530       if (!(fileURL = [NSURL URLFromPasteboard: pb]) ||
5531           [fileURL isFileURL] == NO)
5532         return NO;
5534       file = [fileURL path];
5535       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5536       emacs_event->code = KEY_NS_DRAG_FILE;
5537       XSETINT (emacs_event->x, x);
5538       XSETINT (emacs_event->y, y);
5539       ns_input_file = append2 (ns_input_file, build_string ([file UTF8String]));
5540       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5541       EV_TRAILER (theEvent);
5542       return YES;
5543     }
5544   else if ([type isEqualToString: NSStringPboardType]
5545            || [type isEqualToString: NSTabularTextPboardType])
5546     {
5547       NSString *data;
5549       if (! (data = [pb stringForType: type]))
5550         return NO;
5552       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5553       emacs_event->code = KEY_NS_DRAG_TEXT;
5554       XSETINT (emacs_event->x, x);
5555       XSETINT (emacs_event->y, y);
5556       ns_input_text = build_string ([data UTF8String]);
5557       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5558       EV_TRAILER (theEvent);
5559       return YES;
5560     }
5561   else if ([type isEqualToString: NSColorPboardType])
5562     {
5563       NSColor *c = [NSColor colorFromPasteboard: pb];
5564       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5565       emacs_event->code = KEY_NS_DRAG_COLOR;
5566       XSETINT (emacs_event->x, x);
5567       XSETINT (emacs_event->y, y);
5568       ns_input_color = ns_color_to_lisp (c);
5569       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5570       EV_TRAILER (theEvent);
5571       return YES;
5572     }
5573   else if ([type isEqualToString: NSFontPboardType])
5574     {
5575       /* impl based on GNUstep NSTextView.m */
5576       NSData *data = [pb dataForType: NSFontPboardType];
5577       NSDictionary *dict = [NSUnarchiver unarchiveObjectWithData: data];
5578       NSFont *font = [dict objectForKey: NSFontAttributeName];
5579       char fontSize[10];
5581       if (font == nil)
5582         return NO;
5584       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5585       emacs_event->code = KEY_NS_CHANGE_FONT;
5586       XSETINT (emacs_event->x, x);
5587       XSETINT (emacs_event->y, y);
5588       ns_input_font = build_string ([[font fontName] UTF8String]);
5589       snprintf (fontSize, 10, "%f", [font pointSize]);
5590       ns_input_fontsize = build_string (fontSize);
5591       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5592       EV_TRAILER (theEvent);
5593       return YES;
5594     }
5595   else
5596     {
5597       error ("Invalid data type in dragging pasteboard.");
5598       return NO;
5599     }
5603 - validRequestorForSendType: (NSString *)typeSent
5604                  returnType: (NSString *)typeReturned
5606   NSTRACE (validRequestorForSendType);
5607   if ([ns_send_types indexOfObjectIdenticalTo: typeSent] != NSNotFound &&
5608       [ns_return_types indexOfObjectIdenticalTo: typeSent] != NSNotFound)
5609     return self;
5611   return [super validRequestorForSendType: typeSent
5612                                returnType: typeReturned];
5616 /* The next two methods are part of NSServicesRequests informal protocol,
5617    supposedly called when a services menu item is chosen from this app.
5618    But this should not happen because we override the services menu with our
5619    own entries which call ns-perform-service.
5620    Nonetheless, it appeared to happen here (under strange circumstances):
5621    http://emacsbugs.donarmstrong.com/cgi-bin/bugreport.cgi?bug=1435 
5622    So let's at least stub them out until further investigation can be done. */
5624 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
5626   /* we could call ns_string_from_pasteboard(pboard) here but then it should
5627      be written into the buffer in place of the existing selection..
5628      ordinary service calls go through functions defined in ns-win.el */
5629   return NO;
5632 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
5634   /* supposed to write for as many of types as we are able */
5635   return NO;
5639 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
5640    (gives a miniaturized version of the window); currently we use the latter for
5641    frames whose active buffer doesn't correspond to any file
5642    (e.g., '*scratch*') */
5643 - setMiniwindowImage: (BOOL) setMini
5645   id image = [[self window] miniwindowImage];
5646   NSTRACE (setMiniwindowImage);
5648   /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
5649      about "AppleDockIconEnabled" notwithstanding, however the set message
5650      below has its effect nonetheless. */
5651   if (image != emacsframe->output_data.ns->miniimage)
5652     {
5653       if (image && [image isKindOfClass: [EmacsImage class]])
5654         [image release];
5655       [[self window] setMiniwindowImage:
5656                        setMini ? emacsframe->output_data.ns->miniimage : nil];
5657     }
5659   return self;
5663 - (void) setRows: (int) r andColumns: (int) c
5665   rows = r;
5666   cols = c;
5669 @end  /* EmacsView */
5673 /* ==========================================================================
5675     EmacsWindow implementation
5677    ========================================================================== */
5679 @implementation EmacsWindow
5681 /* called only on resize clicks by special case in EmacsApp-sendEvent */
5682 - (void)mouseDown: (NSEvent *)theEvent
5684   if (ns_in_resize)
5685     {
5686       NSSize size = [[theEvent window] frame].size;
5687       grabOffset = [theEvent locationInWindow];
5688       grabOffset.x = size.width - grabOffset.x;
5689     }
5690   else
5691     [super mouseDown: theEvent];
5695 /* stop resizing */
5696 - (void)mouseUp: (NSEvent *)theEvent
5698   if (ns_in_resize)
5699     {
5700       struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
5701       ns_in_resize = NO;
5702       ns_set_name_as_filename (f);
5703       [self display];
5704       ns_send_appdefined (-1);
5705     }
5706   else
5707     [super mouseUp: theEvent];
5711 /* send resize events */
5712 - (void)mouseDragged: (NSEvent *)theEvent
5714   if (ns_in_resize)
5715     {
5716       NSPoint p = [theEvent locationInWindow];
5717       NSSize size, vettedSize, origSize = [self frame].size;
5719       size.width = p.x + grabOffset.x;
5720       size.height = origSize.height - p.y + grabOffset.y;
5722       if (size.width == origSize.width && size.height == origSize.height)
5723         return;
5725       vettedSize = [[self delegate] windowWillResize: self toSize: size];
5726       if (vettedSize.width != size.width || vettedSize.height != size.height)
5727         {
5728           [[NSNotificationCenter defaultCenter]
5729             postNotificationName: NSWindowDidResizeNotification
5730                           object: self];
5731         }
5732     }
5733   else
5734     [super mouseDragged: theEvent];
5737 @end /* EmacsWindow */
5740 /* ==========================================================================
5742     EmacsScroller implementation
5744    ========================================================================== */
5747 @implementation EmacsScroller
5749 /* for repeat button push */
5750 #define SCROLL_BAR_FIRST_DELAY 0.5
5751 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
5753 + (float) scrollerWidth
5755   /* TODO: if we want to allow variable widths, this is the place to do it,
5756            however neither GNUstep nor Cocoa support it very well */
5757   return [NSScroller scrollerWidth];
5761 - initFrame: (NSRect )r window: (Lisp_Object)nwin
5763   NSTRACE (EmacsScroller_initFrame);
5765   r.size.width = [EmacsScroller scrollerWidth];
5766   [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
5767   [self setContinuous: YES];
5768   [self setEnabled: YES];
5770   /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
5771      locked against the right, top and bottom edges. */
5772   [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
5774   win = nwin;
5775   condemned = NO;
5776   pixel_height = NSHeight (r);
5777   min_portion = 20 / pixel_height;
5779   frame = XFRAME (XWINDOW (win)->frame);
5780   if (FRAME_LIVE_P (frame))
5781     {
5782       int i;
5783       EmacsView *view = FRAME_NS_VIEW (frame);
5784       NSView *sview = [[view window] contentView];
5785       NSArray *subs = [sview subviews];
5787       /* disable optimization stopping redraw of other scrollbars */
5788       view->scrollbarsNeedingUpdate = 0;
5789       for (i =[subs count]-1; i >= 0; i--)
5790         if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
5791           view->scrollbarsNeedingUpdate++;
5792       [sview addSubview: self];
5793     }
5795 /*  [self setFrame: r]; */
5797   return self;
5801 - (void)setFrame: (NSRect)newRect
5803   NSTRACE (EmacsScroller_setFrame);
5804 /*  BLOCK_INPUT; */
5805   pixel_height = NSHeight (newRect);
5806   min_portion = 20 / pixel_height;
5807   [super setFrame: newRect];
5808   [self display];
5809 /*  UNBLOCK_INPUT; */
5813 - (void)dealloc
5815   NSTRACE (EmacsScroller_dealloc);
5816   if (!NILP (win))
5817     XWINDOW (win)->vertical_scroll_bar = Qnil;
5818   [super dealloc];
5822 - condemn
5824   NSTRACE (condemn);
5825   condemned =YES;
5826   return self;
5830 - reprieve
5832   NSTRACE (reprieve);
5833   condemned =NO;
5834   return self;
5838 - judge
5840   NSTRACE (judge);
5841   if (condemned)
5842     {
5843       BLOCK_INPUT;
5844       /* ensure other scrollbar updates after deletion */
5845       EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
5846       if (view != nil)
5847         view->scrollbarsNeedingUpdate++;
5848       [self removeFromSuperview];
5849       [self release];
5850       UNBLOCK_INPUT;
5851     }
5852   return self;
5856 - (void)resetCursorRects
5858   NSRect visible = [self visibleRect];
5859   NSTRACE (resetCursorRects);
5861   if (!NSIsEmptyRect (visible))
5862     [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
5863   [[NSCursor arrowCursor] setOnMouseEntered: YES];
5867 - (int) checkSamePosition: (int) position portion: (int) portion
5868                     whole: (int) whole
5870   return em_position ==position && em_portion ==portion && em_whole ==whole
5871     && portion != whole; /* needed for resize empty buf */
5875 - setPosition: (int)position portion: (int)portion whole: (int)whole
5877   NSTRACE (setPosition);
5879   em_position = position;
5880   em_portion = portion;
5881   em_whole = whole;
5883   if (portion >= whole)
5884     [self setFloatValue: 0.0 knobProportion: 1.0];
5885   else
5886     {
5887       float pos, por;
5888       portion = max ((float)whole*min_portion/pixel_height, portion);
5889       pos = (float)position / (whole - portion);
5890       por = (float)portion/whole;
5891       [self setFloatValue: pos knobProportion: por];
5892     }
5893 #ifdef NS_IMPL_GNUSTEP
5894   [self display];
5895 #endif
5896   return self;
5899 /* FIXME: unused at moment (see ns_mouse_position) at the moment because
5900      drag events will go directly to the EmacsScroller.  Leaving in for now. */
5901 -(void)getMouseMotionPart: (int *)part window: (Lisp_Object *)window
5902                         x: (Lisp_Object *)x y: ( Lisp_Object *)y
5904   *part = last_hit_part;
5905   *window = win;
5906   XSETINT (*y, pixel_height);
5907   if ([self floatValue] > 0.999)
5908     XSETINT (*x, pixel_height);
5909   else
5910     XSETINT (*x, pixel_height * [self floatValue]);
5914 /* set up emacs_event */
5915 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
5917   if (!emacs_event)
5918     return;
5920   emacs_event->part = last_hit_part;
5921   emacs_event->code = 0;
5922   emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
5923   emacs_event->frame_or_window = win;
5924   emacs_event->timestamp = EV_TIMESTAMP (e);
5925   emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
5926   emacs_event->arg = Qnil;
5927   XSETINT (emacs_event->x, loc * pixel_height);
5928   XSETINT (emacs_event->y, pixel_height-20);
5930   n_emacs_events_pending++;
5931   kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
5932   EVENT_INIT (*emacs_event);
5933   ns_send_appdefined (-1);
5937 /* called manually thru timer to implement repeated button action w/hold-down */
5938 - repeatScroll: (NSTimer *)scrollEntry
5940   NSEvent *e = [[self window] currentEvent];
5941   NSPoint p =  [[self window] mouseLocationOutsideOfEventStream];
5942   BOOL inKnob = [self testPart: p] == NSScrollerKnob;
5944   /* clear timer if need be */
5945   if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
5946     {
5947         [scroll_repeat_entry invalidate];
5948         [scroll_repeat_entry release];
5949         scroll_repeat_entry = nil;
5951         if (inKnob)
5952           return self;
5954         scroll_repeat_entry
5955           = [[NSTimer scheduledTimerWithTimeInterval:
5956                         SCROLL_BAR_CONTINUOUS_DELAY
5957                                             target: self
5958                                           selector: @selector (repeatScroll:)
5959                                           userInfo: 0
5960                                            repeats: YES]
5961               retain];
5962     }
5964   [self sendScrollEventAtLoc: 0 fromEvent: e];
5965   return self;
5969 /* Asynchronous mouse tracking for scroller.  This allows us to dispatch
5970    mouseDragged events without going into a modal loop. */
5971 - (void)mouseDown: (NSEvent *)e
5973   NSRect sr, kr;
5974   /* hitPart is only updated AFTER event is passed on */
5975   NSScrollerPart part = [self testPart: [e locationInWindow]];
5976   double inc = 0.0, loc, kloc, pos;
5977   int edge = 0;
5979   NSTRACE (EmacsScroller_mouseDown);
5981   switch (part)
5982     {
5983     case NSScrollerDecrementPage:
5984         last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
5985     case NSScrollerIncrementPage:
5986         last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
5987     case NSScrollerDecrementLine:
5988       last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
5989     case NSScrollerIncrementLine:
5990       last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
5991     case NSScrollerKnob:
5992       last_hit_part = scroll_bar_handle; break;
5993     case NSScrollerKnobSlot:  /* GNUstep-only */
5994       last_hit_part = scroll_bar_move_ratio; break;
5995     default:  /* NSScrollerNoPart? */
5996       fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %d\n", part);
5997       return;
5998     }
6000   if (inc != 0.0)
6001     {
6002       pos = 0;      /* ignored */
6004       /* set a timer to repeat, as we can't let superclass do this modally */
6005       scroll_repeat_entry
6006         = [[NSTimer scheduledTimerWithTimeInterval: 0.5
6007                                             target: self
6008                                           selector: @selector (repeatScroll:)
6009                                           userInfo: 0
6010                                            repeats: YES]
6011             retain];
6012     }
6013   else
6014     {
6015       /* handle, or on GNUstep possibly slot */
6016       NSEvent *fake_event;
6018       /* compute float loc in slot and mouse offset on knob */
6019       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6020                       toView: nil];
6021       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6022       if (loc <= 0.0)
6023         {
6024           loc = 0.0;
6025           edge = -1;
6026         }
6027       else if (loc >= NSHeight (sr))
6028         {
6029           loc = NSHeight (sr);
6030           edge = 1;
6031         }
6033       if (edge)
6034         kloc = 0.5 * edge;
6035       else
6036         {
6037           kr = [self convertRect: [self rectForPart: NSScrollerKnob]
6038                           toView: nil];
6039           kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
6040         }
6041       last_mouse_offset = kloc;
6043       /* if knob, tell emacs a location offset by knob pos
6044          (to indicate top of handle) */
6045       if (part == NSScrollerKnob)
6046           pos = (loc - last_mouse_offset) / NSHeight (sr);
6047       else
6048         /* else this is a slot click on GNUstep: go straight there */
6049         pos = loc / NSHeight (sr);
6051       /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
6052       fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
6053                                       location: [e locationInWindow]
6054                                  modifierFlags: [e modifierFlags]
6055                                      timestamp: [e timestamp]
6056                                   windowNumber: [e windowNumber]
6057                                        context: [e context]
6058                                    eventNumber: [e eventNumber]
6059                                     clickCount: [e clickCount]
6060                                       pressure: [e pressure]];
6061       [super mouseUp: fake_event];
6062     }
6064   if (part != NSScrollerKnob)
6065     [self sendScrollEventAtLoc: pos fromEvent: e];
6069 /* Called as we manually track scroller drags, rather than superclass. */
6070 - (void)mouseDragged: (NSEvent *)e
6072     NSRect sr;
6073     double loc, pos;
6074     int edge = 0;
6076     NSTRACE (EmacsScroller_mouseDragged);
6078       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6079                       toView: nil];
6080       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6082       if (loc <= 0.0)
6083         {
6084           loc = 0.0;
6085           edge = -1;
6086         }
6087       else if (loc >= NSHeight (sr) + last_mouse_offset)
6088         {
6089           loc = NSHeight (sr) + last_mouse_offset;
6090           edge = 1;
6091         }
6093       pos = /*(edge ? loc :*/ (loc - last_mouse_offset) / NSHeight (sr);
6094       [self sendScrollEventAtLoc: pos fromEvent: e];
6098 - (void)mouseUp: (NSEvent *)e
6100   if (scroll_repeat_entry)
6101     {
6102       [scroll_repeat_entry invalidate];
6103       [scroll_repeat_entry release];
6104       scroll_repeat_entry = nil;
6105     }
6106   last_hit_part = 0;
6110 /* treat scrollwheel events in the bar as though they were in the main window */
6111 - (void) scrollWheel: (NSEvent *)theEvent
6113   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
6114   [view mouseDown: theEvent];
6117 @end  /* EmacsScroller */
6121 /* ==========================================================================
6123     EmacsPrefsController implementation
6125    ========================================================================== */
6128 @implementation EmacsPrefsController
6130 /* in Tiger+, can just do [popup selectItemWithTag: tag]; */
6131 static void selectItemWithTag (NSPopUpButton *popup, int tag)
6133   NSEnumerator *items = [[popup itemArray] objectEnumerator];
6134   NSMenuItem *item;
6135   while (item = [items nextObject])
6136     {
6137       if ([item tag] == tag)
6138         {
6139           [popup selectItem: item];
6140           return;
6141         }
6142     }
6145 - init
6147   [NSBundle loadNibNamed: @"preferences" owner: self];
6148   return self;
6152 - (void) showForFrame: (struct frame *)f
6154   frame = f;
6155   [self setPanelFromValues];
6156   [prefsWindow makeKeyAndOrderFront: self];
6157   [prefsWindow display];
6161 /* If you change this, change setPanelFromDefaultValues too. */
6162 - (void) setPanelFromValues
6164   int cursorType
6165     = ns_lisp_to_cursor_type (get_frame_param (frame, Qcursor_type));
6166   prevExpandSpace = XFLOATINT (ns_expand_space);
6168 #ifdef NS_IMPL_COCOA
6169   prevUseHighlightColor = ns_use_system_highlight_color;
6170 #endif
6172   [expandSpaceSlider setFloatValue: prevExpandSpace];
6173   [cursorTypeMatrix selectCellWithTag: (cursorType == FILLED_BOX_CURSOR ? 1 :
6174                                         (cursorType == BAR_CURSOR ? 2 :
6175                                          (cursorType == HBAR_CURSOR ? 3 : 4)))];
6176   selectItemWithTag (alternateModMenu,
6177                      parse_solitary_modifier (ns_alternate_modifier));
6178   selectItemWithTag (commandModMenu,
6179                      parse_solitary_modifier (ns_command_modifier));
6180 #ifdef NS_IMPL_COCOA
6181   selectItemWithTag (controlModMenu,
6182                      parse_solitary_modifier (ns_control_modifier));
6183   selectItemWithTag (functionModMenu,
6184                      parse_solitary_modifier (ns_function_modifier));
6185   [smoothFontsCheck setState: (NILP (ns_antialias_text) ? NO : YES)];
6186   [useQuickdrawCheck setState: (NILP (ns_use_qd_smoothing) ? NO : YES)];
6187   [useSysHiliteCheck setState: (NILP (prevUseHighlightColor) ? NO : YES)];
6188 #endif
6192 /* This and ns_set_default_prefs should be changed together. */
6193 - (void) setPanelFromDefaultValues
6195   [expandSpaceSlider setFloatValue: 0.0];
6196   [cursorTypeMatrix selectCellWithTag: 1]; /* filled box */
6197   selectItemWithTag (alternateModMenu, meta_modifier);
6198   selectItemWithTag (commandModMenu, super_modifier);
6199 #ifdef NS_IMPL_COCOA
6200   selectItemWithTag (controlModMenu, ctrl_modifier);
6201   selectItemWithTag (functionModMenu, 0); /* none */
6202   [smoothFontsCheck setState: YES];
6203   [useQuickdrawCheck setState: NO];
6204   [useSysHiliteCheck setState: YES];
6205 #endif
6209 - (void) setValuesFromPanel
6211   int altTag = [[alternateModMenu selectedItem] tag];
6212   int cmdTag = [[commandModMenu selectedItem] tag];
6213 #ifdef NS_IMPL_COCOA
6214   int ctrlTag = [[controlModMenu selectedItem] tag];
6215   int fnTag = [[functionModMenu selectedItem] tag];
6216 #endif
6217   float expandSpace = [expandSpaceSlider floatValue];
6218   int cursorTag = [[cursorTypeMatrix selectedCell] tag];
6219   Lisp_Object cursor_type = ns_cursor_type_to_lisp
6220        ( cursorTag == 1 ? FILLED_BOX_CURSOR
6221        : cursorTag == 2 ? BAR_CURSOR
6222        : cursorTag == 3 ? HBAR_CURSOR : HOLLOW_BOX_CURSOR);
6224   if (expandSpace != prevExpandSpace)
6225     {
6226       ns_expand_space = make_float (expandSpace);
6227       /* TODO: more needed: store needed metrics in nsfont_info, update
6228          frame default font max_bounds and fontp, recompute faces */
6229 /*         FRAME_LINE_HEIGHT (frame) *= (expandSpace / prevExpandSpace);
6230            x_set_window_size (frame, 0, frame->text_cols, frame->text_lines); */
6231       prevExpandSpace = expandSpace;
6232     }
6234   store_frame_param (frame, Qcursor_type, cursor_type);
6235   x_set_cursor_type (frame, cursor_type, Qnil);  /* FIXME: do only if changed */
6237   ns_alternate_modifier = ns_mod_to_lisp (altTag);
6238   ns_command_modifier = ns_mod_to_lisp (cmdTag);
6239 #ifdef NS_IMPL_COCOA
6240   ns_control_modifier = ns_mod_to_lisp (ctrlTag);
6241   ns_function_modifier = ns_mod_to_lisp (fnTag);
6242   ns_antialias_text = [smoothFontsCheck state] ? Qt : Qnil;
6243   ns_use_qd_smoothing = [useQuickdrawCheck state] ? Qt : Qnil;
6244   ns_use_system_highlight_color = [useSysHiliteCheck state] ? Qt : Qnil;
6245   if (! EQ (ns_use_system_highlight_color, prevUseHighlightColor))
6246     {
6247       prevUseHighlightColor = ns_use_system_highlight_color;
6248       if (EQ (ns_use_system_highlight_color, Qt))
6249         {
6250           ns_selection_color = [[NSUserDefaults standardUserDefaults]
6251                                  stringForKey: @"AppleHighlightColor"];
6252           if (ns_selection_color == nil)
6253             ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
6254         }
6255       else
6256         ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
6257     }
6258 #endif /* NS_IMPL_COCOA */
6259   Fcall_interactively (intern ("ns-save-preferences"), Qnil, Qnil);
6263 /* buttons */
6264 - (IBAction)cancel: (id)sender
6266   [prefsWindow close];
6270 - (IBAction)ok: (id)sender
6272   [self setValuesFromPanel];
6273   [prefsWindow close];
6277 - (IBAction)resetToDefaults: (id)sender
6279   [self setPanelFromDefaultValues];
6283 - (IBAction)runHelp: (id)sender
6285   struct frame *emacsframe = frame;
6286   if (!emacs_event)
6287     return;
6288   ns_raise_frame(frame);
6289   emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
6290   emacs_event->code = KEY_NS_INFO_PREFS;
6291   EV_TRAILER ((id)nil);
6295 - (IBAction)setColors: (id)sender
6297   Lisp_Object lispFrame;
6298   XSETFRAME (lispFrame, frame);
6299   ns_raise_frame(frame);
6300   Fns_popup_color_panel (lispFrame);
6304 - (IBAction)setDefaultFont: (id)sender
6306   Lisp_Object lispFrame;
6307   XSETFRAME (lispFrame, frame);
6308   ns_raise_frame(frame);
6309   Fns_popup_font_panel (lispFrame);
6312 @end  /* EmacsPrefsController */
6317 /* ==========================================================================
6319    Font-related functions; these used to be in nsfaces.m
6321    ========================================================================== */
6324 Lisp_Object
6325 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
6327   struct font *font = XFONT_OBJECT (font_object);
6329   if (fontset < 0)
6330     fontset = fontset_from_font (font_object);
6331   FRAME_FONTSET (f) = fontset;
6333   if (FRAME_FONT (f) == font)
6334     /* This font is already set in frame F.  There's nothing more to
6335        do.  */
6336     return font_object;
6338   FRAME_FONT (f) = font;
6340   FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
6341   FRAME_COLUMN_WIDTH (f) = font->average_width;
6342   FRAME_SPACE_WIDTH (f) = font->space_width;
6343   FRAME_LINE_HEIGHT (f) = font->height;
6345   compute_fringe_widths (f, 1);
6347   /* Compute the scroll bar width in character columns.  */
6348   if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
6349     {
6350       int wid = FRAME_COLUMN_WIDTH (f);
6351       FRAME_CONFIG_SCROLL_BAR_COLS (f)
6352         = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
6353     }
6354   else
6355     {
6356       int wid = FRAME_COLUMN_WIDTH (f);
6357       FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
6358     }
6360   /* Now make the frame display the given font.  */
6361   if (FRAME_NS_WINDOW (f) != 0)
6362         x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
6364   return font_object;
6368 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
6369 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
6370          in 1.43. */
6372 const char *
6373 ns_xlfd_to_fontname (const char *xlfd)
6374 /* --------------------------------------------------------------------------
6375     Convert an X font name (XLFD) to an NS font name.
6376     Only family is used.
6377     The string returned is temporarily allocated.
6378    -------------------------------------------------------------------------- */
6380   char *name = xmalloc (180);
6381   int i, len;
6382   const char *ret;
6384   if (!strncmp (xlfd, "--", 2))
6385     sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
6386   else
6387     sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
6389   /* stopgap for malformed XLFD input */
6390   if (strlen (name) == 0)
6391     strcpy (name, "Monaco");
6393   /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
6394      also uppercase after '-' or ' ' */
6395   name[0] = toupper (name[0]);
6396   for (len =strlen (name), i =0; i<len; i++)
6397     {
6398       if (name[i] == '$')
6399         {
6400           name[i] = '-';
6401           if (i+1<len)
6402             name[i+1] = toupper (name[i+1]);
6403         }
6404       else if (name[i] == '_')
6405         {
6406           name[i] = ' ';
6407           if (i+1<len)
6408             name[i+1] = toupper (name[i+1]);
6409         }
6410     }
6411 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name);  */
6412   ret = [[NSString stringWithUTF8String: name] UTF8String];
6413   xfree (name);
6414   return ret;
6418 void
6419 syms_of_nsterm ()
6421   NSTRACE (syms_of_nsterm);
6422   DEFVAR_LISP ("ns-input-file", &ns_input_file,
6423               "The file specified in the last NS event.");
6424   ns_input_file =Qnil;
6426   DEFVAR_LISP ("ns-input-text", &ns_input_text,
6427               "The data received in the last NS text drag event.");
6428   ns_input_text =Qnil;
6430   DEFVAR_LISP ("ns-working-text", &ns_working_text,
6431               "String for visualizing working composition sequence.");
6432   ns_working_text =Qnil;
6434   DEFVAR_LISP ("ns-input-font", &ns_input_font,
6435               "The font specified in the last NS event.");
6436   ns_input_font =Qnil;
6438   DEFVAR_LISP ("ns-input-fontsize", &ns_input_fontsize,
6439               "The fontsize specified in the last NS event.");
6440   ns_input_fontsize =Qnil;
6442   DEFVAR_LISP ("ns-input-line", &ns_input_line,
6443                "The line specified in the last NS event.");
6444   ns_input_line =Qnil;
6446   DEFVAR_LISP ("ns-input-color", &ns_input_color,
6447                "The color specified in the last NS event.");
6448   ns_input_color =Qnil;
6450   DEFVAR_LISP ("ns-input-spi-name", &ns_input_spi_name,
6451                "The service name specified in the last NS event.");
6452   ns_input_spi_name =Qnil;
6454   DEFVAR_LISP ("ns-input-spi-arg", &ns_input_spi_arg,
6455                "The service argument specified in the last NS event.");
6456   ns_input_spi_arg =Qnil;
6458   DEFVAR_LISP ("ns-alternate-modifier", &ns_alternate_modifier,
6459                "This variable describes the behavior of the alternate or option key.\n\
6460 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6461 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6462 at all, allowing it to be used at a lower level for accented character entry.");
6464   DEFVAR_LISP ("ns-command-modifier", &ns_command_modifier,
6465                "This variable describes the behavior of the command key.\n\
6466 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6468   DEFVAR_LISP ("ns-control-modifier", &ns_control_modifier,
6469                "This variable describes the behavior of the control key.\n\
6470 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6472   DEFVAR_LISP ("ns-function-modifier", &ns_function_modifier,
6473                "This variable describes the behavior of the function key (on laptops).\n\
6474 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6475 Set to none means that the function key is not interpreted by Emacs at all,\n\
6476 allowing it to be used at a lower level for accented character entry.");
6478   DEFVAR_LISP ("ns-expand-space", &ns_expand_space,
6479                "Amount by which spacing between lines is expanded (positive)\n\
6480 or shrunk (negative).  Zero (the default) means standard line height.\n\
6481 (This variable should only be read, never set.)");
6483   DEFVAR_LISP ("ns-antialias-text", &ns_antialias_text,
6484                "Non-nil (the default) means to render text antialiased. Only has an effect on OS X Panther and above.");
6486   DEFVAR_LISP ("ns-use-qd-smoothing", &ns_use_qd_smoothing,
6487                "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).");
6489   DEFVAR_LISP ("ns-use-system-highlight-color",
6490                &ns_use_system_highlight_color,
6491                "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'.");
6493   staticpro (&ns_display_name_list);
6494   ns_display_name_list = Qnil;
6496   staticpro (&last_mouse_motion_frame);
6497   last_mouse_motion_frame = Qnil;
6499   /* from 23+ we need to tell emacs what modifiers there are.. */
6500   Qmodifier_value = intern ("modifier-value");
6501   Qalt = intern ("alt");
6502   Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
6503   Qhyper = intern ("hyper");
6504   Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
6505   Qmeta = intern ("meta");
6506   Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
6507   Qsuper = intern ("super");
6508   Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
6509   Qcontrol = intern ("control");
6510   Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
6512   /* TODO: move to common code */
6513   DEFVAR_LISP ("x-toolkit-scroll-bars", &Vx_toolkit_scroll_bars,
6514                doc: /* If not nil, Emacs uses toolkit scroll bars.  */);
6515 #ifdef USE_TOOLKIT_SCROLL_BARS
6516   Vx_toolkit_scroll_bars = Qt;
6517 #else
6518   Vx_toolkit_scroll_bars = Qnil;
6519 #endif
6521   /* these are unsupported but we need the declarations to avoid whining
6522      messages from cus-start.el */
6523   DEFVAR_BOOL ("x-use-underline-position-properties",
6524                &x_use_underline_position_properties,
6525      doc: /* NOT SUPPORTED UNDER NS.
6526 *Non-nil means make use of UNDERLINE_POSITION font properties.
6527 A value of nil means ignore them.  If you encounter fonts with bogus
6528 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
6529 to 4.1, set this to nil.
6531 NOTE: Not supported on Mac yet.  */);
6532   x_use_underline_position_properties = 0;
6534   DEFVAR_BOOL ("x-underline-at-descent-line",
6535                &x_underline_at_descent_line,
6536      doc: /* NOT SUPPORTED UNDER NS.
6537 *Non-nil means to draw the underline at the same place as the descent line.
6538 A value of nil means to draw the underline according to the value of the
6539 variable `x-use-underline-position-properties', which is usually at the
6540 baseline level.  The default value is nil.  */);
6541   x_underline_at_descent_line = 0;
6543   /* Tell emacs about this window system. */
6544   Fprovide (intern ("ns"), Qnil);
6548 // arch-tag: 6eaa8f7d-a69b-4e1c-b43d-ab31defbe0d2