(Man-init-defvars) [windows-nt]: Use a special command list. Don't invoke Awk.
[emacs.git] / src / nsterm.m
blob1b7301084d0f688fc01d1cd7383c4d46983e6ed0
1 /* NeXT/Open/GNUstep / MacOSX communication module.
2    Copyright (C) 1989, 1993, 1994, 2005, 2006, 2008, 2009
3      Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.  */
21 Originally by Carl Edman
22 Updated by Christian Limpach (chris@nice.ch)
23 OpenStep/Rhapsody port by Scott Bender (sbender@harmony-ds.com)
24 MacOSX/Aqua port by Christophe de Dinechin (descubes@earthlink.net)
25 GNUstep port and post-20 update by Adrian Robert (arobert@cogsci.ucsd.edu)
28 /* This should be the first include, as it may set up #defines affecting
29    interpretation of even the system includes. */
30 #include "config.h"
32 #include <math.h>
33 #include <sys/types.h>
34 #include <time.h>
35 #include <signal.h>
36 #include <unistd.h>
38 #include "lisp.h"
39 #include "blockinput.h"
40 #include "sysselect.h"
41 #include "nsterm.h"
42 #include "systime.h"
43 #include "character.h"
44 #include "fontset.h"
45 #include "composite.h"
46 #include "ccl.h"
48 #include "termhooks.h"
49 #include "termopts.h"
50 #include "termchar.h"
52 #include "window.h"
53 #include "keyboard.h"
55 #include "font.h"
57 /* call tracing */
58 #if 0
59 int term_trace_num = 0;
60 #define NSTRACE(x)        fprintf (stderr, "%s:%d: [%d] " #x "\n",         \
61                                 __FILE__, __LINE__, ++term_trace_num)
62 #else
63 #define NSTRACE(x)
64 #endif
67 /* ==========================================================================
69     Local declarations
71    ========================================================================== */
73 /* Convert a symbol indexed with an NSxxx value to a value as defined
74    in keyboard.c (lispy_function_key). I hope this is a correct way
75    of doing things... */
76 static unsigned convert_ns_to_X_keysym[] =
78   NSHomeFunctionKey,            0x50,
79   NSLeftArrowFunctionKey,       0x51,
80   NSUpArrowFunctionKey,         0x52,
81   NSRightArrowFunctionKey,      0x53,
82   NSDownArrowFunctionKey,       0x54,
83   NSPageUpFunctionKey,          0x55,
84   NSPageDownFunctionKey,        0x56,
85   NSEndFunctionKey,             0x57,
86   NSBeginFunctionKey,           0x58,
87   NSSelectFunctionKey,          0x60,
88   NSPrintFunctionKey,           0x61,
89   NSExecuteFunctionKey,         0x62,
90   NSInsertFunctionKey,          0x63,
91   NSUndoFunctionKey,            0x65,
92   NSRedoFunctionKey,            0x66,
93   NSMenuFunctionKey,            0x67,
94   NSFindFunctionKey,            0x68,
95   NSHelpFunctionKey,            0x6A,
96   NSBreakFunctionKey,           0x6B,
98   NSF1FunctionKey,              0xBE,
99   NSF2FunctionKey,              0xBF,
100   NSF3FunctionKey,              0xC0,
101   NSF4FunctionKey,              0xC1,
102   NSF5FunctionKey,              0xC2,
103   NSF6FunctionKey,              0xC3,
104   NSF7FunctionKey,              0xC4,
105   NSF8FunctionKey,              0xC5,
106   NSF9FunctionKey,              0xC6,
107   NSF10FunctionKey,             0xC7,
108   NSF11FunctionKey,             0xC8,
109   NSF12FunctionKey,             0xC9,
110   NSF13FunctionKey,             0xCA,
111   NSF14FunctionKey,             0xCB,
112   NSF15FunctionKey,             0xCC,
114   NSBackspaceCharacter,         0x08,  /* 8: Not on some KBs. */
115   NSDeleteCharacter,            0xFF,  /* 127: Big 'delete' key upper right. */
116   NSDeleteFunctionKey,          0x9F,  /* 63272: Del forw key off main array. */
118   NSTabCharacter,               0x09,
119   0x19,                         0x09,  /* left tab->regular since pass shift */
120   NSCarriageReturnCharacter,    0x0D,
121   NSNewlineCharacter,           0x0D,
122   NSEnterCharacter,             0x8D,
124   0x1B,                         0x1B   /* escape */
128 /* Lisp communications */
129 Lisp_Object ns_input_file, ns_input_font, ns_input_fontsize, ns_input_line;
130 Lisp_Object ns_input_color, ns_input_text, ns_working_text;
131 Lisp_Object ns_input_spi_name, ns_input_spi_arg;
132 Lisp_Object Vx_toolkit_scroll_bars;
133 static Lisp_Object Qmodifier_value;
134 /* TODO: unsure why these defined in term files, anyway we need in keymap.c */
135 Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper;
136 extern Lisp_Object Qcursor_color, Qcursor_type, Qns;
139 EmacsPrefsController *prefsController;
141 /* Preferences equivalent to those set by X resources under X are managed
142    through the OpenStep defaults system.  These pertain to behavior of the
143    graphical interface components.  The one difference from X is that the
144    values below are SET when the user chooses save-options. This makes
145    things easier for users, but sometimes violates expectations when some
146    user-set options appear when running under -q/Q.  Therefore we depart
147    from X behavior and refuse to read defaults when started under these
148    options. */
150 /* Set in emacs.c. */
151 char ns_no_defaults;
153 /* Specifies which emacs modifier should be generated when NS receives
154    the Alternate modifer.  May be Qnone or any of the modifier lisp symbols. */
155 Lisp_Object ns_alternate_modifier;
157 /* Specifies which emacs modifier should be generated when NS receives
158    the Command modifer.  May be any of the modifier lisp symbols. */
159 Lisp_Object ns_command_modifier;
161 /* Specifies which emacs modifier should be generated when NS receives
162    the Control modifer.  May be any of the modifier lisp symbols. */
163 Lisp_Object ns_control_modifier;
165 /* Specifies which emacs modifier should be generated when NS receives
166    the Function modifer (laptops).  May be any of the modifier lisp symbols. */
167 Lisp_Object ns_function_modifier;
169 /* A floating point value specifying vertical stretch (positive) or shrink
170   (negative) of text line spacing.  Zero means default spacing.
171   YES indicates 0.5, NO indicates 0.0. */
172 Lisp_Object ns_expand_space;
174 /* Control via default 'GSFontAntiAlias' on OS X and GNUstep. */
175 Lisp_Object ns_antialias_text;
177 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
178    the maximum font size to NOT antialias.  On GNUstep there is currently
179    no way to control this behavior. */
180 float ns_antialias_threshold;
182 /* Controls use of an undocumented CG function to do Quickdraw-style font
183    smoothing (less heavy) instead of regular Quartz smoothing. */
184 Lisp_Object ns_use_qd_smoothing;
186 /* Used to pick up AppleHighlightColor on OS X */
187 Lisp_Object ns_use_system_highlight_color;
188 NSString *ns_selection_color;
190 /* Confirm on exit. */
191 Lisp_Object ns_confirm_quit;
193 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
195 /* Display variables */
196 struct ns_display_info *x_display_list; /* Chain of existing displays */
197 Lisp_Object ns_display_name_list;
198 long context_menu_value = 0;
200 /* display update */
201 NSPoint last_mouse_motion_position;
202 static NSRect last_mouse_glyph;
203 static unsigned long last_mouse_movement_time = 0;
204 static Lisp_Object last_mouse_motion_frame;
205 static EmacsScroller *last_mouse_scroll_bar = nil;
206 static struct frame *ns_updating_frame;
207 static NSView *focus_view = NULL;
208 static int ns_window_num =0;
209 static NSRect uRect;
210 static BOOL gsaved = NO;
211 BOOL ns_in_resize = NO;
212 static BOOL ns_fake_keydown = NO;
213 int ns_tmp_flags; /* FIXME */
214 struct nsfont_info *ns_tmp_font; /* FIXME */
215 /*static int debug_lock = 0; */
217 #ifdef NS_IMPL_COCOA
218 /* This undocumented Quartz function controls how fonts are anti-aliased.
219    (Found from code in Mac wxWindows impl, discovered by running `nm' on
220    the "QD" framework.)
221    Mode 0 is normal anti-aliasing, mode 1 is no anti-aliasing, and mode 2 is
222    4-bit pixel-aligned anti-aliasing (the old QuickDraw standard). */
223 extern void CGContextSetFontRenderingMode (CGContextRef cg, int v);
224 #endif
227 /* event loop */
228 static BOOL send_appdefined = YES;
229 static NSEvent *last_appdefined_event = 0;
230 static NSTimer *timed_entry = 0;
231 static NSTimer *fd_entry = nil;
232 static NSTimer *scroll_repeat_entry = nil;
233 static fd_set select_readfds, t_readfds;
234 static struct timeval select_timeout;
235 static int select_nfds;
236 static NSAutoreleasePool *outerpool;
237 static BOOL ns_shutdown_properly = NO;
238 static struct input_event *emacs_event = NULL;
239 static struct input_event *q_event_ptr = NULL;
240 static int n_emacs_events_pending = 0;
241 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
242   *ns_pending_service_args;
243 static BOOL inNsSelect = 0;
245 /* Convert modifiers in a NeXTSTEP event to emacs style modifiers.  */
246 #define NS_FUNCTION_KEY_MASK 0x800000
247 #define EV_MODIFIERS(e)                               \
248     ((([e modifierFlags] & NSHelpKeyMask) ?           \
249            hyper_modifier : 0)                        \
250      | (([e modifierFlags] & NSAlternateKeyMask) ?    \
251            parse_solitary_modifier (ns_alternate_modifier) : 0)   \
252      | (([e modifierFlags] & NSShiftKeyMask) ?        \
253            shift_modifier : 0)                        \
254      | (([e modifierFlags] & NSControlKeyMask) ?      \
255            parse_solitary_modifier (ns_control_modifier) : 0)     \
256      | (([e modifierFlags] & NS_FUNCTION_KEY_MASK) ?  \
257            parse_solitary_modifier (ns_function_modifier) : 0)    \
258      | (([e modifierFlags] & NSCommandKeyMask) ?      \
259            parse_solitary_modifier (ns_command_modifier):0))
261 #define EV_UDMODIFIERS(e)                                      \
262     ((([e type] == NSLeftMouseDown) ? down_modifier : 0)       \
263      | (([e type] == NSRightMouseDown) ? down_modifier : 0)    \
264      | (([e type] == NSOtherMouseDown) ? down_modifier : 0)    \
265      | (([e type] == NSLeftMouseDragged) ? down_modifier : 0)  \
266      | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
267      | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
268      | (([e type] == NSLeftMouseUp)   ? up_modifier   : 0)     \
269      | (([e type] == NSRightMouseUp)   ? up_modifier   : 0)    \
270      | (([e type] == NSOtherMouseUp)   ? up_modifier   : 0))
272 #define EV_BUTTON(e)                                                         \
273     ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 :    \
274       (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
275      [e buttonNumber] - 1)
277 /* Convert the time field to a timestamp in milliseconds. */
278 #ifdef NS_IMPL_GNUSTEP
279 /* Apple says timestamp is in seconds, but GNUstep seems to be returning msec */
280 #define EV_TIMESTAMP(e) ([e timestamp])
281 #else
282 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
283 #endif /* not gnustep */
285 /* This is a piece of code which is common to all the event handling
286    methods.  Maybe it should even be a function.  */
287 #define EV_TRAILER(e)                                         \
288   {                                                           \
289   XSETFRAME (emacs_event->frame_or_window, emacsframe);       \
290   if (e) emacs_event->timestamp = EV_TIMESTAMP (e);           \
291   n_emacs_events_pending++;                                   \
292   kbd_buffer_store_event_hold (emacs_event, q_event_ptr);     \
293   EVENT_INIT (*emacs_event);                                  \
294   ns_send_appdefined (-1);                                    \
295   }
297 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
299 /* TODO: get rid of need for these forward declarations */
300 static void ns_condemn_scroll_bars (struct frame *f);
301 static void ns_judge_scroll_bars (struct frame *f);
302 void x_set_frame_alpha (struct frame *f);
304 /* unused variables needed for compatibility reasons */
305 int x_use_underline_position_properties, x_underline_at_descent_line;
306 /* FIXME: figure out what to do with underline_minimum_offset. */
309 /* ==========================================================================
311     Utilities
313    ========================================================================== */
316 static Lisp_Object
317 append2 (Lisp_Object list, Lisp_Object item)
318 /* --------------------------------------------------------------------------
319    Utility to append to a list
320    -------------------------------------------------------------------------- */
322   Lisp_Object array[2];
323   array[0] = list;
324   array[1] = Fcons (item, Qnil);
325   return Fnconc (2, &array[0]);
329 void
330 ns_init_paths ()
331 /* --------------------------------------------------------------------------
332    Used to allow emacs to find its resources under Emacs.app
333    Called from emacs.c at startup.
334    -------------------------------------------------------------------------- */
336   NSBundle *bundle = [NSBundle mainBundle];
337   NSString *binDir = [bundle bundlePath], *resourceDir = [bundle resourcePath];
338   NSString *resourcePath, *resourcePaths;
339   NSRange range;
340   BOOL onWindows = NO; /* how do I determine this? */
341   NSString *pathSeparator = onWindows ? @";" : @":";
342   NSFileManager *fileManager = [NSFileManager defaultManager];
343   BOOL isDir;
344 /*NSLog (@"ns_init_paths: '%@'\n%@\n", [[NSBundle mainBundle] bundlePath], [[NSBundle mainBundle] resourcePath]); */
346   /* get bindir from base */
347   range = [resourceDir rangeOfString: @"Contents"];
348   if (range.location != NSNotFound)
349     {
350       binDir = [binDir stringByAppendingPathComponent: @"Contents"];
351 #ifdef NS_IMPL_COCOA
352       binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
353 #endif
354     }
356   /* the following based on Andrew Choi's init_mac_osx_environment () */
357   if (!getenv ("EMACSLOADPATH"))
358     {
359       NSArray *paths = [resourceDir stringsByAppendingPaths:
360                                   [NSArray arrayWithObjects:
361                                          @"site-lisp", @"lisp", @"leim", nil]];
362       NSEnumerator *pathEnum = [paths objectEnumerator];
363       resourcePaths = @"";
364       while (resourcePath = [pathEnum nextObject])
365         {
366           if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
367             if (isDir)
368               {
369                 if ([resourcePaths length] > 0)
370                   resourcePaths
371                     = [resourcePaths stringByAppendingString: pathSeparator];
372                 resourcePaths
373                   = [resourcePaths stringByAppendingString: resourcePath];
374               }
375         }
376       if ([resourcePaths length] > 0)
377         setenv ("EMACSLOADPATH", [resourcePaths UTF8String], 1);
378 /*NSLog (@"loadPath: '%s'\n", resourcePaths); */
379     }
381   if (!getenv ("EMACSPATH"))
382     {
383       NSArray *paths = [binDir stringsByAppendingPaths:
384                                   [NSArray arrayWithObjects: @"bin",
385                                                              @"lib-exec", nil]];
386       NSEnumerator *pathEnum = [paths objectEnumerator];
387       resourcePaths = @"";
388       while (resourcePath = [pathEnum nextObject])
389         {
390           if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
391             if (isDir)
392               {
393                 if ([resourcePaths length] > 0)
394                   resourcePaths
395                     = [resourcePaths stringByAppendingString: pathSeparator];
396                 resourcePaths
397                   = [resourcePaths stringByAppendingString: resourcePath];
398               }
399         }
400       if ([resourcePaths length] > 0)
401         setenv ("EMACSPATH", [resourcePaths UTF8String], 1);
402     }
404   resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
405   if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
406     {
407       if (isDir)
408         {
409           if (!getenv ("EMACSDATA"))
410             setenv ("EMACSDATA", [resourcePath UTF8String], 1);
411           if (!getenv ("EMACSDOC"))
412             setenv ("EMACSDOC", [resourcePath UTF8String], 1);
413         }
414     }
416   if (!getenv ("INFOPATH"))
417     {
418       resourcePath = [resourceDir stringByAppendingPathComponent: @"info"];
419       if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
420         if (isDir)
421           setenv ("INFOPATH", [resourcePath UTF8String], 1);
422     }
426 static int
427 timeval_subtract (struct timeval *result, struct timeval x, struct timeval y)
428 /* --------------------------------------------------------------------------
429    Subtract the `struct timeval' values X and Y, storing the result in RESULT.
430    Return 1 if the difference is negative, otherwise 0.
431    -------------------------------------------------------------------------- */
433   /* Perform the carry for the later subtraction by updating y.
434      This is safer because on some systems
435      the tv_sec member is unsigned.  */
436   if (x.tv_usec < y.tv_usec)
437     {
438       int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
439       y.tv_usec -= 1000000 * nsec;
440       y.tv_sec += nsec;
441     }
442   if (x.tv_usec - y.tv_usec > 1000000)
443     {
444       int nsec = (y.tv_usec - x.tv_usec) / 1000000;
445       y.tv_usec += 1000000 * nsec;
446       y.tv_sec -= nsec;
447     }
449   /* Compute the time remaining to wait.  tv_usec is certainly positive.  */
450   result->tv_sec = x.tv_sec - y.tv_sec;
451   result->tv_usec = x.tv_usec - y.tv_usec;
453   /* Return indication of whether the result should be considered negative.  */
454   return x.tv_sec < y.tv_sec;
457 static void
458 ns_timeout (int usecs)
459 /* --------------------------------------------------------------------------
460      Blocking timer utility used by ns_ring_bell
461    -------------------------------------------------------------------------- */
463   struct timeval wakeup;
465   EMACS_GET_TIME (wakeup);
467   /* Compute time to wait until, propagating carry from usecs.  */
468   wakeup.tv_usec += usecs;
469   wakeup.tv_sec += (wakeup.tv_usec / 1000000);
470   wakeup.tv_usec %= 1000000;
472   /* Keep waiting until past the time wakeup.  */
473   while (1)
474     {
475       struct timeval timeout;
477       EMACS_GET_TIME (timeout);
479       /* In effect, timeout = wakeup - timeout.
480          Break if result would be negative.  */
481       if (timeval_subtract (&timeout, wakeup, timeout))
482         break;
484       /* Try to wait that long--but we might wake up sooner.  */
485       select (0, NULL, NULL, NULL, &timeout);
486     }
490 void
491 ns_release_object (void *obj)
492 /* --------------------------------------------------------------------------
493     Release an object (callable from C)
494    -------------------------------------------------------------------------- */
496     [(id)obj release];
500 void
501 ns_retain_object (void *obj)
502 /* --------------------------------------------------------------------------
503     Retain an object (callable from C)
504    -------------------------------------------------------------------------- */
506     [(id)obj retain];
510 void *
511 ns_alloc_autorelease_pool ()
512 /* --------------------------------------------------------------------------
513      Allocate a pool for temporary objects (callable from C)
514    -------------------------------------------------------------------------- */
516   return [[NSAutoreleasePool alloc] init];
520 void
521 ns_release_autorelease_pool (void *pool)
522 /* --------------------------------------------------------------------------
523      Free a pool and temporary objects it refers to (callable from C)
524    -------------------------------------------------------------------------- */
526   ns_release_object (pool);
531 /* ==========================================================================
533     Focus (clipping) and screen update
535    ========================================================================== */
537 static NSRect
538 ns_resize_handle_rect (NSWindow *window)
540   NSRect r = [window frame];
541   r.origin.x = r.size.width - RESIZE_HANDLE_SIZE;
542   r.origin.y = 0;
543   r.size.width = r.size.height = RESIZE_HANDLE_SIZE;
544   return r;
548 static void
549 ns_update_begin (struct frame *f)
550 /* --------------------------------------------------------------------------
551    Prepare for a grouped sequence of drawing calls
552    external (RIF) call; whole frame, called before update_window_begin
553    -------------------------------------------------------------------------- */
555   NSView *view = FRAME_NS_VIEW (f);
556   NSTRACE (ns_update_begin);
558   ns_updating_frame = f;
559   [view lockFocus];
561 #ifdef NS_IMPL_GNUSTEP
562   uRect = NSMakeRect (0, 0, 0, 0);
563 #endif
567 static void
568 ns_update_window_begin (struct window *w)
569 /* --------------------------------------------------------------------------
570    Prepare for a grouped sequence of drawing calls
571    external (RIF) call; for one window, called after update_begin
572    -------------------------------------------------------------------------- */
574   struct frame *f = XFRAME (WINDOW_FRAME (w));
575   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
576   NSTRACE (ns_update_window_begin);
578   updated_window = w;
579   set_output_cursor (&w->cursor);
581   BLOCK_INPUT;
583   if (f == dpyinfo->mouse_face_mouse_frame)
584     {
585       /* Don't do highlighting for mouse motion during the update.  */
586       dpyinfo->mouse_face_defer = 1;
588         /* If the frame needs to be redrawn,
589            simply forget about any prior mouse highlighting.  */
590       if (FRAME_GARBAGED_P (f))
591         dpyinfo->mouse_face_window = Qnil;
593       /* (further code for mouse faces ifdef'd out in other terms elided) */
594     }
596   UNBLOCK_INPUT;
600 static void
601 ns_update_window_end (struct window *w, int cursor_on_p,
602                       int mouse_face_overwritten_p)
603 /* --------------------------------------------------------------------------
604    Finished a grouped sequence of drawing calls
605    external (RIF) call; for one window called before update_end
606    -------------------------------------------------------------------------- */
608   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (XFRAME (w->frame));
610   /* note: this fn is nearly identical in all terms */
611   if (!w->pseudo_window_p)
612     {
613       BLOCK_INPUT;
615       if (cursor_on_p)
616         display_and_set_cursor (w, 1,
617                                 output_cursor.hpos, output_cursor.vpos,
618                                 output_cursor.x, output_cursor.y);
620       if (draw_window_fringes (w, 1))
621         x_draw_vertical_border (w);
623       UNBLOCK_INPUT;
624     }
626   /* If a row with mouse-face was overwritten, arrange for
627      frame_up_to_date to redisplay the mouse highlight.  */
628   if (mouse_face_overwritten_p)
629     {
630       dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
631       dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
632       dpyinfo->mouse_face_window = Qnil;
633     }
635   updated_window = NULL;
636   NSTRACE (update_window_end);
640 static void
641 ns_update_end (struct frame *f)
642 /* --------------------------------------------------------------------------
643    Finished a grouped sequence of drawing calls
644    external (RIF) call; for whole frame, called after update_window_end
645    -------------------------------------------------------------------------- */
647   NSView *view = FRAME_NS_VIEW (f);
649 /*   if (f == FRAME_NS_DISPLAY_INFO (f)->mouse_face_mouse_frame) */
650     FRAME_NS_DISPLAY_INFO (f)->mouse_face_defer = 0;
652   BLOCK_INPUT;
654 #ifdef NS_IMPL_GNUSTEP
655   /* trigger flush only in the rectangle we tracked as being drawn */
656   [view unlockFocusNeedsFlush: NO];
657 /*fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", uRect.origin.x, uRect.origin.y, uRect.size.width, uRect.size.height); */
658   [view lockFocusInRect: uRect];
659 #endif
661   [view unlockFocus];
662   [[view window] flushWindow];
664   UNBLOCK_INPUT;
665   ns_updating_frame = NULL;
666   NSTRACE (ns_update_end);
670 static void
671 ns_flush (struct frame *f)
672 /* --------------------------------------------------------------------------
673    external (RIF) call
674    NS impl is no-op since currently we flush in ns_update_end and elsewhere
675    -------------------------------------------------------------------------- */
677     NSTRACE (ns_flush);
681 static void
682 ns_focus (struct frame *f, NSRect *r, int n)
683 /* --------------------------------------------------------------------------
684    Internal: Focus on given frame.  During small local updates this is used to
685      draw, however during large updates, ns_update_begin and ns_update_end are
686      called to wrap the whole thing, in which case these calls are stubbed out.
687      Except, on GNUstep, we accumulate the rectangle being drawn into, because
688      the back end won't do this automatically, and will just end up flushing
689      the entire window.
690    -------------------------------------------------------------------------- */
692 //  NSTRACE (ns_focus);
693 #ifdef NS_IMPL_GNUSTEP
694   NSRect u;
695     if (n == 2)
696       u = NSUnionRect (r[0], r[1]);
697     else if (r)
698       u = *r;
699 #endif
700 /* static int c =0;
701    fprintf (stderr, "focus: %d", c++);
702    if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
703    fprintf (stderr, "\n"); */
705   if (f != ns_updating_frame)
706     {
707       NSView *view = FRAME_NS_VIEW (f);
708       if (view != focus_view)
709         {
710           if (focus_view != NULL)
711             {
712               [focus_view unlockFocus];
713               [[focus_view window] flushWindow];
714 /*debug_lock--; */
715             }
717           if (view)
718 #ifdef NS_IMPL_GNUSTEP
719             r ? [view lockFocusInRect: u] : [view lockFocus];
720 #else
721             [view lockFocus];
722 #endif
723           focus_view = view;
724 /*if (view) debug_lock++; */
725         }
726 #ifdef NS_IMPL_GNUSTEP
727       else
728         {
729           /* more than one rect being drawn into */
730           if (view && r)
731             {
732               [view unlockFocus]; /* add prev rect to redraw list */
733               [view lockFocusInRect: u]; /* focus for draw in new rect */
734             }
735         }
736 #endif
737     }
738 #ifdef NS_IMPL_GNUSTEP
739   else
740     {
741       /* in batch mode, but in GNUstep must still track rectangles explicitly */
742       uRect = (r ? NSUnionRect (uRect, u) : [FRAME_NS_VIEW (f) visibleRect]);
743     }
744 #endif
746   /* clipping */
747   if (r)
748     {
749       [[NSGraphicsContext currentContext] saveGraphicsState];
750       if (n == 2)
751         NSRectClipList (r, 2);
752       else
753         NSRectClip (*r);
754       gsaved = YES;
755     }
759 static void
760 ns_unfocus (struct frame *f)
761 /* --------------------------------------------------------------------------
762      Internal: Remove focus on given frame
763    -------------------------------------------------------------------------- */
765 //  NSTRACE (ns_unfocus);
767   if (gsaved)
768     {
769       [[NSGraphicsContext currentContext] restoreGraphicsState];
770       gsaved = NO;
771     }
773   if (f != ns_updating_frame)
774     {
775       if (focus_view != NULL)
776         {
777           [focus_view unlockFocus];
778           [[focus_view window] flushWindow];
779           focus_view = NULL;
780 /*debug_lock--; */
781         }
782     }
786 static void
787 ns_clip_to_row (struct window *w, struct glyph_row *row, int area, BOOL gc)
788 /* --------------------------------------------------------------------------
789      Internal (but parallels other terms): Focus drawing on given row
790    -------------------------------------------------------------------------- */
792   struct frame *f = XFRAME (WINDOW_FRAME (w));
793   NSRect clip_rect;
794   int window_x, window_y, window_width;
796   window_box (w, area, &window_x, &window_y, &window_width, 0);
798   clip_rect.origin.x = window_x - FRAME_INTERNAL_BORDER_WIDTH (f);
799   clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
800   clip_rect.origin.y = max (clip_rect.origin.y, window_y);
801   clip_rect.size.width = window_width + 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
802   clip_rect.size.height = row->visible_height;
804   /* allow a full-height row at the top when requested
805      (used to draw fringe all the way through internal border area) */
806   if (gc && clip_rect.origin.y < 5)
807     {
808       clip_rect.origin.y -= FRAME_INTERNAL_BORDER_WIDTH (f);
809       clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
810     }
812   /* likewise at bottom */
813   if (gc &&
814       FRAME_PIXEL_HEIGHT (f) - (clip_rect.origin.y + clip_rect.size.height) < 5)
815     clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
817   ns_focus (f, &clip_rect, 1);
821 static void
822 ns_ring_bell ()
823 /* --------------------------------------------------------------------------
824      "Beep" routine
825    -------------------------------------------------------------------------- */
827   NSTRACE (ns_ring_bell);
828   if (visible_bell)
829     {
830       NSAutoreleasePool *pool;
831       struct frame *frame = SELECTED_FRAME ();
832       NSView *view;
834       BLOCK_INPUT;
835       pool = [[NSAutoreleasePool alloc] init];
837       view = FRAME_NS_VIEW (frame);
838       if (view != nil)
839         {
840           NSRect r, surr;
841           NSPoint dim = NSMakePoint (128, 128);
843           r = [view bounds];
844           r.origin.x += (r.size.width - dim.x) / 2;
845           r.origin.y += (r.size.height - dim.y) / 2;
846           r.size.width = dim.x;
847           r.size.height = dim.y;
848           surr = NSInsetRect (r, -2, -2);
849           ns_focus (frame, &surr, 1);
850           [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
851           [ns_lookup_indexed_color (NS_FACE_FOREGROUND
852                                       (FRAME_DEFAULT_FACE (frame)), frame) set];
853           NSRectFill (r);
854           [[view window] flushWindow];
855           ns_timeout (150000);
856           [[view window] restoreCachedImage];
857           [[view window] flushWindow];
858           ns_unfocus (frame);
859         }
860       [pool release];
861       UNBLOCK_INPUT;
862     }
863   else
864     {
865       NSBeep ();
866     }
870 static void
871 ns_reset_terminal_modes (struct terminal *terminal)
872 /*  Externally called as hook */
874   NSTRACE (ns_reset_terminal_modes);
877 static void
878 ns_set_terminal_modes (struct terminal *terminal)
879 /*  Externally called as hook */
881   NSTRACE (ns_set_terminal_modes);
886 /* ==========================================================================
888     Frame / window manager related functions
890    ========================================================================== */
893 static void
894 ns_raise_frame (struct frame *f)
895 /* --------------------------------------------------------------------------
896      Bring window to foreground and make it active
897    -------------------------------------------------------------------------- */
899   NSView *view = FRAME_NS_VIEW (f);
900   check_ns ();
901   BLOCK_INPUT;
902   [[view window] makeKeyAndOrderFront: NSApp];
903   UNBLOCK_INPUT;
907 static void
908 ns_lower_frame (struct frame *f)
909 /* --------------------------------------------------------------------------
910      Send window to back
911    -------------------------------------------------------------------------- */
913   NSView *view = FRAME_NS_VIEW (f);
914   check_ns ();
915   BLOCK_INPUT;
916   [[view window] orderBack: NSApp];
917   UNBLOCK_INPUT;
921 static void
922 ns_frame_raise_lower (struct frame *f, int raise)
923 /* --------------------------------------------------------------------------
924      External (hook)
925    -------------------------------------------------------------------------- */
927   NSTRACE (ns_frame_raise_lower);
929   if (raise)
930     ns_raise_frame (f);
931   else
932     ns_lower_frame (f);
936 static void
937 ns_frame_rehighlight (struct frame *frame)
938 /* --------------------------------------------------------------------------
939      External (hook): called on things like window switching within frame
940    -------------------------------------------------------------------------- */
942   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
943   struct frame *old_highlight = dpyinfo->x_highlight_frame;
945   NSTRACE (ns_frame_rehighlight);
946   if (dpyinfo->x_focus_frame)
947     {
948       dpyinfo->x_highlight_frame
949         = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
950            ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
951            : dpyinfo->x_focus_frame);
952       if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
953         {
954           FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
955           dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
956         }
957     }
958   else
959       dpyinfo->x_highlight_frame = 0;
961   if (dpyinfo->x_highlight_frame &&
962          dpyinfo->x_highlight_frame != old_highlight)
963     {
964       if (old_highlight)
965         {
966           x_update_cursor (old_highlight, 1);
967           x_set_frame_alpha (old_highlight);
968         }
969       if (dpyinfo->x_highlight_frame)
970         {
971           x_update_cursor (dpyinfo->x_highlight_frame, 1);
972           x_set_frame_alpha (dpyinfo->x_highlight_frame);
973         }
974     }
978 void
979 x_make_frame_visible (struct frame *f)
980 /* --------------------------------------------------------------------------
981      External: Show the window (X11 semantics)
982    -------------------------------------------------------------------------- */
984   NSTRACE (x_make_frame_visible);
985   /* XXX: at some points in past this was not needed, as the only place that
986      called this (frame.c:Fraise_frame ()) also called raise_lower;
987      if this ends up the case again, comment this out again. */
988   if (!FRAME_VISIBLE_P (f))
989     ns_raise_frame (f);
993 void
994 x_make_frame_invisible (struct frame *f)
995 /* --------------------------------------------------------------------------
996      External: Hide the window (X11 semantics)
997    -------------------------------------------------------------------------- */
999   NSView * view = FRAME_NS_VIEW (f);
1000   NSTRACE (x_make_frame_invisible);
1001   check_ns ();
1002   [[view window] orderOut: NSApp];
1003   f->async_visible = 0;
1004   f->async_iconified = 0;
1008 void
1009 x_iconify_frame (struct frame *f)
1010 /* --------------------------------------------------------------------------
1011      External: Iconify window
1012    -------------------------------------------------------------------------- */
1014   NSView * view = FRAME_NS_VIEW (f);
1015   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1016   NSTRACE (x_iconify_frame);
1017   check_ns ();
1019   if (dpyinfo->x_highlight_frame == f)
1020     dpyinfo->x_highlight_frame = 0;
1022   if ([[view window] windowNumber] <= 0)
1023     {
1024       /* the window is still deferred.  Make it very small, bring it
1025          on screen and order it out. */
1026       NSRect s = { { 100, 100}, {0, 0} };
1027       NSRect t;
1028       t = [[view window] frame];
1029       [[view window] setFrame: s display: NO];
1030       [[view window] orderBack: NSApp];
1031       [[view window] orderOut: NSApp];
1032       [[view window] setFrame: t display: NO];
1033     }
1034   [[view window] miniaturize: NSApp];
1038 void
1039 x_destroy_window (struct frame *f)
1040 /* --------------------------------------------------------------------------
1041      External: Delete the window
1042    -------------------------------------------------------------------------- */
1044   NSView *view = FRAME_NS_VIEW (f);
1045   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1046   NSTRACE (x_destroy_window);
1047   check_ns ();
1049   [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1051   BLOCK_INPUT;
1053   free_frame_menubar (f);
1055   if (FRAME_FACE_CACHE (f))
1056     free_frame_faces (f);
1058   if (f == dpyinfo->x_focus_frame)
1059     dpyinfo->x_focus_frame = 0;
1060   if (f == dpyinfo->x_highlight_frame)
1061     dpyinfo->x_highlight_frame = 0;
1062   if (f == dpyinfo->mouse_face_mouse_frame)
1063     {
1064       dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
1065       dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
1066       dpyinfo->mouse_face_window = Qnil;
1067       dpyinfo->mouse_face_deferred_gc = 0;
1068       dpyinfo->mouse_face_mouse_frame = 0;
1069     }
1071   xfree (f->output_data.ns);
1073   [[view window] close];
1074   [view release];
1076   ns_window_num--;
1077   UNBLOCK_INPUT;
1081 void
1082 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1083 /* --------------------------------------------------------------------------
1084      External: Position the window
1085    -------------------------------------------------------------------------- */
1087   NSScreen *screen;
1088   NSView *view = FRAME_NS_VIEW (f);
1090   NSTRACE (x_set_offset);
1092   BLOCK_INPUT;
1094   f->left_pos = xoff;
1095   f->top_pos = yoff;
1096 #ifdef NS_IMPL_GNUSTEP
1097   if (xoff < 100)
1098     f->left_pos = 100;  /* don't overlap menu */
1099 #endif
1100   if (view != nil && (screen = [[view window] screen]))
1101     [[view window] setFrameTopLeftPoint:
1102         NSMakePoint (SCREENMAXBOUND (f->left_pos),
1103                      SCREENMAXBOUND ([screen frame].size.height
1104                                      - NS_TOP_POS (f)))];
1105   UNBLOCK_INPUT;
1109 void
1110 x_set_window_size (struct frame *f, int change_grav, int cols, int rows)
1111 /* --------------------------------------------------------------------------
1112      Adjust window pixel size based on given character grid size
1113      Impl is a bit more complex than other terms, need to do some
1114      internal clipping and also pay attention to screen constraints.
1115    -------------------------------------------------------------------------- */
1117   EmacsView *view = FRAME_NS_VIEW (f);
1118   EmacsToolbar *toolbar = [view toolbar];
1119   NSWindow *window = [view window];
1120   NSScreen *screen = [window screen];
1121   NSRect wr = [window frame];
1122   int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1123   int pixelwidth, pixelheight;
1124   static int oldRows, oldCols, oldFontWidth, oldFontHeight;
1125   static int oldTB;
1126   static struct frame *oldF;
1128   NSTRACE (x_set_window_size);
1130   if (view == nil ||
1131       (f == oldF
1132        && rows == oldRows && cols == oldCols
1133        && oldFontWidth == FRAME_COLUMN_WIDTH (f)
1134        && oldFontHeight == FRAME_LINE_HEIGHT (f)
1135        && oldTB == tb))
1136     return;
1138 /*fprintf (stderr, "\tsetWindowSize: %d x %d, font size %d x %d\n", cols, rows, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f)); */
1140   BLOCK_INPUT;
1142   check_frame_size (f, &rows, &cols);
1143   oldF = f;
1144   oldRows = rows;
1145   oldCols = cols;
1146   oldFontWidth = FRAME_COLUMN_WIDTH (f);
1147   oldFontHeight = FRAME_LINE_HEIGHT (f);
1148   oldTB = tb;
1150   f->scroll_bar_actual_width = NS_SCROLL_BAR_WIDTH (f);
1151   compute_fringe_widths (f, 0);
1153   pixelwidth =  FRAME_TEXT_COLS_TO_PIXEL_WIDTH   (f, cols);
1154   pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
1156   /* If we have a toolbar, take its height into account. */
1157   /* XXX: GNUstep has not yet implemented the first method below, added
1158           in Panther, however the second is incorrect under Cocoa. */
1159   if (tb)
1160     FRAME_NS_TOOLBAR_HEIGHT (f) =
1161 #ifdef NS_IMPL_COCOA
1162       NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1163       /* NOTE: previously this would generate wrong result if toolbar not
1164                yet displayed and fixing toolbar_height=32 helped, but
1165                now (200903) seems no longer needed */
1166 #else
1167       NSHeight ([NSWindow frameRectForContentRect: NSMakeRect (0, 0, 0, 0)
1168                                         styleMask: [window styleMask]])
1169 #endif
1170             - FRAME_NS_TITLEBAR_HEIGHT (f);
1171   else
1172     FRAME_NS_TOOLBAR_HEIGHT (f) = 0;
1174   wr.size.width = pixelwidth + f->border_width;
1175   wr.size.height = pixelheight + FRAME_NS_TITLEBAR_HEIGHT (f) 
1176                   + FRAME_NS_TOOLBAR_HEIGHT (f);
1178   /* constrain to screen if we can */
1179   if (screen)
1180     {
1181       NSSize sz = [screen visibleFrame].size;
1182       NSSize ez = { wr.size.width - sz.width, wr.size.height - sz.height };
1183       if (ez.width > 0)
1184         {
1185           int cr = ez.width / FRAME_COLUMN_WIDTH (f) + 1;
1186           cols -= cr;
1187           oldCols = cols;
1188           wr.size.width -= cr * FRAME_COLUMN_WIDTH (f);
1189           pixelwidth -= cr * FRAME_COLUMN_WIDTH (f);
1190         }
1191       if (ez.height > 0)
1192         {
1193           int rr = ez.height / FRAME_LINE_HEIGHT (f) + 1;
1194           rows -= rr;
1195           oldRows = rows;
1196           wr.size.height -= rr * FRAME_LINE_HEIGHT (f);
1197           pixelheight -= rr * FRAME_LINE_HEIGHT (f);
1198         }
1199       wr.origin.x = f->left_pos;
1200       wr.origin.y = [screen frame].size.height - NS_TOP_POS (f)
1201         - wr.size.height;
1202     }
1204   [view setRows: rows andColumns: cols];
1205   [window setFrame: wr display: YES];
1207 /*fprintf (stderr, "\tx_set_window_size %d, %d\t%d, %d\n", cols, rows, pixelwidth, pixelheight); */
1209   /* This is a trick to compensate for Emacs' managing the scrollbar area
1210      as a fixed number of standard character columns.  Instead of leaving
1211      blank space for the extra, we chopped it off above.  Now for
1212      left-hand scrollbars, we shift all rendering to the left by the
1213      difference between the real width and Emacs' imagined one.  For
1214      right-hand bars, don't worry about it since the extra is never used.
1215      (Obviously doesn't work for vertically split windows tho..) */
1216   NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1217     ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1218                   - NS_SCROLL_BAR_WIDTH (f), 0)
1219     : NSMakePoint (0, 0);
1220   [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1221   [view setBoundsOrigin: origin];
1223   change_frame_size (f, rows, cols, 0, 1, 0); /* pretend, delay, safe */
1224   FRAME_PIXEL_WIDTH (f) = pixelwidth;
1225   FRAME_PIXEL_HEIGHT (f) = pixelheight;
1226 /*  SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */
1228   mark_window_cursors_off (XWINDOW (f->root_window));
1229   cancel_mouse_face (f);
1231   UNBLOCK_INPUT;
1236 /* ==========================================================================
1238     Color management
1240    ========================================================================== */
1243 NSColor *
1244 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1246   struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1247   return color_table->colors[idx];
1251 unsigned long
1252 ns_index_color (NSColor *color, struct frame *f)
1254   struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1255   int idx;
1256   NSNumber *index;
1258   if (!color_table->colors)
1259     {
1260       color_table->size = NS_COLOR_CAPACITY;
1261       color_table->avail = 1; /* skip idx=0 as marker */
1262       color_table->colors
1263         = (NSColor **)xmalloc (color_table->size * sizeof (NSColor *));
1264       color_table->empty_indices = [[NSMutableSet alloc] init];
1265     }
1267   /* do we already have this color ? */
1268   {
1269     int i;
1270     for (i = 1; i < color_table->avail; i++)
1271       {
1272         if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1273           {
1274             [color_table->colors[i] retain];
1275             return i;
1276           }
1277       }
1278   }
1280   if ([color_table->empty_indices count] > 0)
1281     {
1282       index = [color_table->empty_indices anyObject];
1283       [color_table->empty_indices removeObject: index];
1284       idx = [index unsignedIntValue];
1285     }
1286   else
1287     {
1288       if (color_table->avail == color_table->size)
1289         {
1290           color_table->size += NS_COLOR_CAPACITY;
1291           color_table->colors
1292             = (NSColor **)xrealloc (color_table->colors,
1293                                     color_table->size * sizeof (NSColor *));
1294         }
1295       idx = color_table->avail++;
1296     }
1298   color_table->colors[idx] = color;
1299   [color retain];
1300 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1301   return idx;
1305 void
1306 ns_free_indexed_color (unsigned long idx, struct frame *f)
1308   struct ns_color_table *color_table;
1309   NSColor *color;
1310   NSNumber *index;
1312   if (!f)
1313     return;
1315   color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1317   if (idx <= 0 || idx >= color_table->size) {
1318     message1("ns_free_indexed_color: Color index out of range.\n");
1319     return;
1320   }
1322   index = [NSNumber numberWithUnsignedInt: idx];
1323   if ([color_table->empty_indices containsObject: index]) {
1324     message1("ns_free_indexed_color: attempt to free already freed color.\n");
1325     return;
1326   }
1328   color = color_table->colors[idx];
1329   [color release];
1330   color_table->colors[idx] = nil;
1331   [color_table->empty_indices addObject: [NSNumber numberWithUnsignedInt: idx]];
1332 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1336 static int
1337 ns_get_color (const char *name, NSColor **col)
1338 /* --------------------------------------------------------------------------
1339      Parse a color name
1340 /* --------------------------------------------------------------------------
1341 /* On *Step, we recognize several color formats, in addition to a catalog
1342    of colors found in the file Emacs.clr. Color formats include:
1343    - #rrggbb or RGBrrggbb where rr, gg, bb specify red, green and blue in hex
1344    - ARGBaarrggbb is similar, with aa being the alpha channel (FF = opaque)
1345    - HSVhhssvv and AHSVaahhssvv (or HSB/AHSB) are similar for hue, saturation,
1346      value;
1347    - CMYKccmmyykk is similar for cyan, magenta, yellow, black. */
1349   NSColor * new = nil;
1350   const char *hex = NULL;
1351   enum { rgb, argb, hsv, ahsv, cmyk, gray } color_space;
1352   NSString *nsname = [NSString stringWithUTF8String: name];
1354 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1355   BLOCK_INPUT;
1357   if ([nsname isEqualToString: @"ns_selection_color"])
1358     {
1359       nsname = ns_selection_color;
1360       name = [ns_selection_color UTF8String];
1361     }
1363   if (name[0] == '0' || name[0] == '1' || name[0] == '.')
1364     {
1365       /* RGB decimal */
1366       NSScanner *scanner = [NSScanner scannerWithString: nsname];
1367       float r, g, b;
1368       [scanner scanFloat: &r];
1369       [scanner scanFloat: &g];
1370       [scanner scanFloat: &b];
1371       *col = [NSColor colorWithCalibratedRed: r green: g blue: b alpha: 1.0];
1372       UNBLOCK_INPUT;
1373       return 0;
1374     }
1376   /*  FIXME: emacs seems to downcase everything before passing it here,
1377         which we can work around, except for GRAY, since gray##, where ## is
1378         decimal between 0 and 99, is also an X11 colorname. */
1379   if (name[0] == '#')             /* X11 format */
1380     {
1381       hex = name + 1;
1382       color_space = rgb;
1383     }
1384   else if (!memcmp (name, "RGB", 3) || !memcmp (name, "rgb", 3))
1385     {
1386       hex = name + 3;
1387       color_space = rgb;
1388     }
1389   else if (!memcmp (name, "ARGB", 4) || !memcmp (name, "argb", 4))
1390     {
1391       hex = name + 4;
1392       color_space = argb;
1393     }
1394   else if (!memcmp (name, "HSV", 3) || !memcmp (name, "hsv", 3) || 
1395            !memcmp (name, "HSB", 3) || !memcmp (name, "hsb", 3))
1396     {
1397       hex = name + 3;
1398       color_space = hsv;
1399     }
1400   else if (!memcmp (name, "AHSV", 4) || !memcmp (name, "ahsv", 4) ||
1401            !memcmp (name, "AHSB", 4) || !memcmp (name, "ahsb", 4))
1402     {
1403       hex = name + 4;
1404       color_space = ahsv;
1405     }
1406   else if (!memcmp (name, "CMYK", 4) || !memcmp (name, "cmyk", 4))
1407     {
1408       hex = name + 4;
1409       color_space = cmyk;
1410     }
1411   else if (!memcmp (name, "GRAY", 4) /*|| !memcmp (name, "gray", 4)*/)
1412     {
1413       hex = name + 4;
1414       color_space = gray;
1415     }
1417   /* Direct colors (hex values) */
1418   if (hex)
1419     {
1420       unsigned long long color = 0;
1421       if (sscanf (hex, "%x", &color))
1422         {
1423           float f1, f2, f3, f4;
1424           /* Assume it's either 1 byte or 2 per channel... */
1425           if (strlen(hex) > 8) {
1426             f1 = ((color >> 48) & 0xffff) / 65535.0;
1427             f2 = ((color >> 32) & 0xffff) / 65535.0;
1428             f3 = ((color >> 16) & 0xffff) / 65535.0;
1429             f4 = ((color      ) & 0xffff) / 65535.0;
1430           } else {
1431             f1 = ((color >> 24) & 0xff) / 255.0;
1432             f2 = ((color >> 16) & 0xff) / 255.0;
1433             f3 = ((color >>  8) & 0xff) / 255.0;
1434             f4 = ((color      ) & 0xff) / 255.0;
1435           }
1437           switch (color_space)
1438             {
1439             case rgb:
1440               *col = [NSColor colorWithCalibratedRed: f2
1441                                                green: f3
1442                                                 blue: f4
1443                                                alpha: 1.0];
1444               break;
1445             case argb:
1446               *col = [NSColor colorWithCalibratedRed: f2
1447                                                green: f3
1448                                                 blue: f4
1449                                                alpha: f1];
1450               break;
1451             case hsv:
1452               *col = [NSColor colorWithCalibratedHue: f2
1453                                           saturation: f3
1454                                           brightness: f4
1455                                                alpha: 1.0];
1456               break;
1457             case ahsv:
1458               *col = [NSColor colorWithCalibratedHue: f2
1459                                           saturation: f3
1460                                           brightness: f4
1461                                                alpha: f1];
1462               break;
1463             case gray:
1464               *col = [NSColor colorWithCalibratedWhite: f3 alpha: f4];
1465               break;
1466             case cmyk:
1467               *col = [NSColor colorWithDeviceCyan: f1
1468                                           magenta: f2
1469                                            yellow: f3
1470                                             black: f4
1471                                             alpha: 1.0];
1472               break;
1473             }
1474           *col = [*col colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1475           UNBLOCK_INPUT;
1476           return 0;
1477         }
1478     }
1480   /* Otherwise, color is expected to be from a list */
1481   {
1482     NSEnumerator *lenum, *cenum;
1483     NSString *name;
1484     NSColorList *clist;
1486 #ifdef NS_IMPL_GNUSTEP
1487     /* XXX: who is wrong, the requestor or the implementation? */
1488     if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1489         == NSOrderedSame)
1490       nsname = @"highlightColor";
1491 #endif
1493     lenum = [[NSColorList availableColorLists] objectEnumerator];
1494     while ( (clist = [lenum nextObject]) && new == nil)
1495       {
1496         cenum = [[clist allKeys] objectEnumerator];
1497         while ( (name = [cenum nextObject]) && new == nil )
1498           {
1499             if ([name compare: nsname
1500                       options: NSCaseInsensitiveSearch] == NSOrderedSame )
1501               new = [clist colorWithKey: name];
1502           }
1503       }
1504   }
1506   if ( new )
1507     *col = [new colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1508 /*     else
1509        NSLog (@"Failed to find color '%@'", nsname); */
1510   UNBLOCK_INPUT;
1511   return new ? 0 : 1;
1515 static NSColor *
1516 ns_get_color_default (const char *name, NSColor *dflt)
1517 /* --------------------------------------------------------------------------
1518      Parse a color or use a default value
1519    -------------------------------------------------------------------------- */
1521   NSColor * col;
1523   if (ns_get_color (name, &col))
1524     return dflt;
1525   else
1526     return col;
1531 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1532 /* --------------------------------------------------------------------------
1533      Convert a Lisp string object to a NS color
1534    -------------------------------------------------------------------------- */
1536   NSTRACE (ns_lisp_to_color);
1537   if (STRINGP (color))
1538     return ns_get_color (SDATA (color), col);
1539   else if (SYMBOLP (color))
1540     return ns_get_color (SDATA (SYMBOL_NAME (color)), col);
1541   return 1;
1545 Lisp_Object
1546 ns_color_to_lisp (NSColor *col)
1547 /* --------------------------------------------------------------------------
1548      Convert a color to a lisp string with the RGB equivalent
1549    -------------------------------------------------------------------------- */
1551   float red, green, blue, alpha, gray;
1552   char buf[1024];
1553   const char *str;
1554   NSTRACE (ns_color_to_lisp);
1556   BLOCK_INPUT;
1557   if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1559       if ((str =[[col colorNameComponent] UTF8String]))
1560         {
1561           UNBLOCK_INPUT;
1562           return build_string ((char *)str);
1563         }
1565     [[col colorUsingColorSpaceName: NSCalibratedRGBColorSpace]
1566         getRed: &red green: &green blue: &blue alpha: &alpha];
1567   if (red ==green && red ==blue)
1568     {
1569       [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1570             getWhite: &gray alpha: &alpha];
1571       snprintf (buf, sizeof (buf), "GRAY%02.2lx%02.2lx",
1572                lrint (gray * 0xff), lrint (alpha * 0xff));
1573       UNBLOCK_INPUT;
1574       return build_string (buf);
1575     }
1577   snprintf (buf, sizeof (buf), "ARGB%02.2lx%02.2lx%02.2lx%02.2lx",
1578             lrint (alpha*0xff),
1579             lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1581   UNBLOCK_INPUT;
1582   return build_string (buf);
1586 void
1587 ns_query_color(void *col, XColor *color_def, int setPixel)
1588 /* --------------------------------------------------------------------------
1589          Get ARGB values out of NSColor col and put them into color_def.
1590          If setPixel, set the pixel to a concatenated version.
1591          and set color_def pixel to the resulting index.
1592    -------------------------------------------------------------------------- */
1594   float r, g, b, a;
1596   [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1597   color_def->red   = r * 65535;
1598   color_def->green = g * 65535;
1599   color_def->blue  = b * 65535;
1601   if (setPixel == YES)
1602     color_def->pixel
1603       = ARGB_TO_ULONG((int)(a*255),
1604                       (int)(r*255), (int)(g*255), (int)(b*255));
1609 ns_defined_color (struct frame *f, char *name, XColor *color_def, int alloc,
1610                   char makeIndex)
1611 /* --------------------------------------------------------------------------
1612          Return 1 if named color found, and set color_def rgb accordingly.
1613          If makeIndex and alloc are nonzero put the color in the color_table,
1614          and set color_def pixel to the resulting index.
1615          If makeIndex is zero, set color_def pixel to ARGB.
1616          Return 0 if not found
1617    -------------------------------------------------------------------------- */
1619   NSColor *temp;
1620   int notFound = ns_get_color (name, &temp);
1622   NSTRACE (ns_defined_color);
1624   if (notFound)
1625     return 0;
1627   if (makeIndex && alloc)
1628       color_def->pixel = ns_index_color(temp, f); /* [temp retain]; */
1630   ns_query_color (temp, color_def, !makeIndex);
1632   return 1;
1636 unsigned long
1637 ns_get_rgb_color (struct frame *f, float r, float g, float b, float a)
1638 /* --------------------------------------------------------------------------
1639     return an autoreleased RGB color
1640    -------------------------------------------------------------------------- */
1642 /*static int c = 1; fprintf (stderr, "color request %d\n", c++); */
1643   if (r < 0.0) r = 0.0;
1644   else if (r > 1.0) r = 1.0;
1645   if (g < 0.0) g = 0.0;
1646   else if (g > 1.0) g = 1.0;
1647   if (b < 0.0) b = 0.0;
1648   else if (b > 1.0) b = 1.0;
1649   if (a < 0.0) a = 0.0;
1650   else if (a > 1.0) a = 1.0;
1651   return (unsigned long) ns_index_color(
1652     [NSColor colorWithCalibratedRed: r green: g blue: b alpha: a], f);
1656 void
1657 x_set_frame_alpha (struct frame *f)
1658 /* --------------------------------------------------------------------------
1659      change the entire-frame transparency
1660    -------------------------------------------------------------------------- */
1662   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1663   EmacsView *view = FRAME_NS_VIEW (f);
1664   double alpha = 1.0;
1665   double alpha_min = 1.0;
1667   if (dpyinfo->x_highlight_frame == f)
1668     alpha = f->alpha[0];
1669   else
1670     alpha = f->alpha[1];
1672   if (FLOATP (Vframe_alpha_lower_limit))
1673     alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1674   else if (INTEGERP (Vframe_alpha_lower_limit))
1675     alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1677   if (alpha < 0.0)
1678     return;
1679   else if (1.0 < alpha)
1680     alpha = 1.0;
1681   else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1682     alpha = alpha_min;
1684 #ifdef NS_IMPL_COCOA
1685   [[view window] setAlphaValue: alpha];
1686 #endif
1690 /* ==========================================================================
1692     Mouse handling
1694    ========================================================================== */
1697 void
1698 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1699 /* --------------------------------------------------------------------------
1700      Programmatically reposition mouse pointer in pixel coordinates
1701    -------------------------------------------------------------------------- */
1703   NSTRACE (x_set_mouse_pixel_position);
1704   ns_raise_frame (f);
1705 #if 0
1706   /* FIXME: this does not work, and what about GNUstep? */
1707 #ifdef NS_IMPL_COCOA
1708   [FRAME_NS_VIEW (f) lockFocus];
1709   PSsetmouse ((float)pix_x, (float)pix_y);
1710   [FRAME_NS_VIEW (f) unlockFocus];
1711 #endif
1712 #endif
1716 void
1717 x_set_mouse_position (struct frame *f, int h, int v)
1718 /* --------------------------------------------------------------------------
1719      Programmatically reposition mouse pointer in character coordinates
1720    -------------------------------------------------------------------------- */
1722   int pix_x, pix_y;
1724   pix_x = FRAME_COL_TO_PIXEL_X (f, h) + FRAME_COLUMN_WIDTH (f) / 2;
1725   pix_y = FRAME_LINE_TO_PIXEL_Y (f, v) + FRAME_LINE_HEIGHT (f) / 2;
1727   if (pix_x < 0) pix_x = 0;
1728   if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
1730   if (pix_y < 0) pix_y = 0;
1731   if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
1733   x_set_mouse_pixel_position (f, pix_x, pix_y);
1737 static int
1738 note_mouse_movement (struct frame *frame, float x, float y)
1739 /*   ------------------------------------------------------------------------
1740      Called by EmacsView on mouseMovement events.  Passes on
1741      to emacs mainstream code if we moved off of a rect of interest
1742      known as last_mouse_glyph.
1743      ------------------------------------------------------------------------ */
1745 //  NSTRACE (note_mouse_movement);
1747   XSETFRAME (last_mouse_motion_frame, frame);
1749   /* Note, this doesn't get called for enter/leave, since we don't have a
1750      position.  Those are taken care of in the corresponding NSView methods. */
1752   /* has movement gone beyond last rect we were tracking? */
1753   if (x < last_mouse_glyph.origin.x ||
1754       x >= (last_mouse_glyph.origin.x + last_mouse_glyph.size.width) ||
1755       y < last_mouse_glyph.origin.y ||
1756       y >= (last_mouse_glyph.origin.y + last_mouse_glyph.size.height))
1757     {
1758       frame->mouse_moved = 1;
1759       note_mouse_highlight (frame, x, y);
1760       remember_mouse_glyph (frame, x, y, &last_mouse_glyph);
1761       return 1;
1762     }
1764   return 0;
1768 static void
1769 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1770                    enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1771                    unsigned long *time)
1772 /* --------------------------------------------------------------------------
1773     External (hook): inform emacs about mouse position and hit parts.
1774     If a scrollbar is being dragged, set bar_window, part, x, y, time.
1775     x & y should be position in the scrollbar (the whole bar, not the handle)
1776     and length of scrollbar respectively
1777    -------------------------------------------------------------------------- */
1779   id view;
1780   NSPoint position;
1781   int xchar, ychar;
1782   Lisp_Object frame, tail;
1783   struct frame *f;
1784   struct ns_display_info *dpyinfo;
1786   NSTRACE (ns_mouse_position);
1788   if (*fp == NULL)
1789     {
1790       fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1791       return;
1792     }
1794   dpyinfo = FRAME_NS_DISPLAY_INFO (*fp);
1796   BLOCK_INPUT;
1798   if (last_mouse_scroll_bar != nil && insist == 0)
1799     {
1800       /* TODO: we do not use this path at the moment because drag events will
1801            go directly to the EmacsScroller.  Leaving code in for now. */
1802       [last_mouse_scroll_bar getMouseMotionPart: (int *)part window: bar_window
1803                                               x: x y: y];
1804       if (time) *time = last_mouse_movement_time;
1805       last_mouse_scroll_bar = nil;
1806     }
1807   else
1808     {
1809       /* Clear the mouse-moved flag for every frame on this display.  */
1810       FOR_EACH_FRAME (tail, frame)
1811         if (FRAME_NS_P (XFRAME (frame))
1812             && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1813           XFRAME (frame)->mouse_moved = 0;
1815       last_mouse_scroll_bar = nil;
1816       if (last_mouse_frame && FRAME_LIVE_P (last_mouse_frame))
1817         f = last_mouse_frame;
1818       else
1819         f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame
1820                                     : SELECTED_FRAME ();
1822       if (f && f->output_data.ns)  /* TODO: 2nd check no longer needed? */
1823         {
1824           view = FRAME_NS_VIEW (*fp);
1826           position = [[view window] mouseLocationOutsideOfEventStream];
1827           position = [view convertPoint: position fromView: nil];
1828           remember_mouse_glyph (f, position.x, position.y, &last_mouse_glyph);
1829 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1831           if (bar_window) *bar_window = Qnil;
1832           if (part) *part = 0; /*scroll_bar_handle; */
1834           if (x) XSETINT (*x, lrint (position.x));
1835           if (y) XSETINT (*y, lrint (position.y));
1836           if (time) *time = last_mouse_movement_time;
1837           *fp = f;
1838         }
1839     }
1841   UNBLOCK_INPUT;
1845 static void
1846 ns_frame_up_to_date (struct frame *f)
1847 /* --------------------------------------------------------------------------
1848     External (hook): Fix up mouse highlighting right after a full update.
1849     Some highlighting was deferred if GC was happening during
1850     note_mouse_highlight (), while other highlighting was deferred for update.
1851    -------------------------------------------------------------------------- */
1853   NSTRACE (ns_frame_up_to_date);
1855   if (FRAME_NS_P (f))
1856     {
1857       struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1858       if ((dpyinfo->mouse_face_deferred_gc||f ==dpyinfo->mouse_face_mouse_frame)
1859       /*&& dpyinfo->mouse_face_mouse_frame*/)
1860         {
1861           BLOCK_INPUT;
1862           if (dpyinfo->mouse_face_mouse_frame)
1863             note_mouse_highlight (dpyinfo->mouse_face_mouse_frame,
1864                                   dpyinfo->mouse_face_mouse_x,
1865                                   dpyinfo->mouse_face_mouse_y);
1866           dpyinfo->mouse_face_deferred_gc = 0;
1867           UNBLOCK_INPUT;
1868         }
1869     }
1873 void
1874 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1875 /* --------------------------------------------------------------------------
1876     External (RIF): set frame mouse pointer type.
1877    -------------------------------------------------------------------------- */
1879   NSTRACE (ns_define_frame_cursor);
1880   if (FRAME_POINTER_TYPE (f) != cursor)
1881     {
1882       EmacsView *view = FRAME_NS_VIEW (f);
1883       FRAME_POINTER_TYPE (f) = cursor;
1884       [[view window] invalidateCursorRectsForView: view];
1885     }
1890 /* ==========================================================================
1892     Keyboard handling
1894    ========================================================================== */
1897 static unsigned
1898 ns_convert_key (unsigned code)
1899 /* --------------------------------------------------------------------------
1900     Internal call used by NSView-keyDown.
1901    -------------------------------------------------------------------------- */
1903   const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym)
1904                                 / sizeof (convert_ns_to_X_keysym[0]));
1905   unsigned keysym;
1906   /* An array would be faster, but less easy to read. */
1907   for (keysym = 0; keysym < last_keysym; keysym += 2)
1908     if (code == convert_ns_to_X_keysym[keysym])
1909       return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
1910   return 0;
1911 /* if decide to use keyCode and Carbon table, use this line:
1912      return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
1916 char *
1917 x_get_keysym_name (int keysym)
1918 /* --------------------------------------------------------------------------
1919     Called by keyboard.c.  Not sure if the return val is important, except
1920     that it be unique.
1921    -------------------------------------------------------------------------- */
1923   static char value[16];
1924   NSTRACE (x_get_keysym_name);
1925   sprintf (value, "%d", keysym);
1926   return value;
1931 /* ==========================================================================
1933     Block drawing operations
1935    ========================================================================== */
1938 static void
1939 ns_redraw_scroll_bars (struct frame *f)
1941   int i;
1942   id view;
1943   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
1944   NSTRACE (ns_judge_scroll_bars);
1945   for (i =[subviews count]-1; i >= 0; i--)
1946     {
1947       view = [subviews objectAtIndex: i];
1948       if (![view isKindOfClass: [EmacsScroller class]]) continue;
1949       [view display];
1950     }
1954 void
1955 ns_clear_frame (struct frame *f)
1956 /* --------------------------------------------------------------------------
1957       External (hook): Erase the entire frame
1958    -------------------------------------------------------------------------- */
1960   NSView *view = FRAME_NS_VIEW (f);
1961   NSRect r;
1963   NSTRACE (ns_clear_frame);
1964   if (ns_in_resize)
1965     return;
1967  /* comes on initial frame because we have
1968     after-make-frame-functions = select-frame */
1969  if (!FRAME_DEFAULT_FACE (f))
1970    return;
1972   mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
1974   output_cursor.hpos = output_cursor.vpos = 0;
1975   output_cursor.x = -1;
1977   r = [view bounds];
1979   BLOCK_INPUT;
1980   ns_focus (f, &r, 1);
1981   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
1982   NSRectFill (r);
1983   ns_unfocus (f);
1985 #ifdef NS_IMPL_COCOA
1986   [[view window] display];  /* redraw resize handle */
1987 #endif
1989   /* as of 2006/11 or so this is now needed */
1990   ns_redraw_scroll_bars (f);
1991   UNBLOCK_INPUT;
1995 void
1996 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
1997 /* --------------------------------------------------------------------------
1998     External (RIF):  Clear section of frame
1999    -------------------------------------------------------------------------- */
2001   NSRect r = NSMakeRect (x, y, width, height);
2002   NSView *view = FRAME_NS_VIEW (f);
2003   struct face *face = FRAME_DEFAULT_FACE (f);
2005   if (!view || !face)
2006     return;
2008   NSTRACE (ns_clear_frame_area);
2010   r = NSIntersectionRect (r, [view frame]);
2011   ns_focus (f, &r, 1);
2012   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2014 #ifdef NS_IMPL_COCOA
2015   {
2016     /* clip out the resize handle */
2017     NSWindow *window = [FRAME_NS_VIEW (f) window];
2018     NSRect ir
2019       = [view convertRect: ns_resize_handle_rect (window) fromView: nil];
2021     ir = NSIntersectionRect (r, ir);
2022     if (NSIsEmptyRect (ir))
2023       {
2024 #endif
2026   NSRectFill (r);
2028 #ifdef NS_IMPL_COCOA
2029       }
2030     else
2031       {
2032         NSRect r1 = r, r2 = r; /* upper and lower non-intersecting */
2033         r1.size.height -= ir.size.height;
2034         r2.origin.y += r1.size.height;
2035         r2.size.width -= ir.size.width;
2036         r2.size.height = ir.size.height;
2037         NSRectFill (r1);
2038         NSRectFill (r2);
2039       }
2040   }
2041 #endif
2043   ns_unfocus (f);
2044   return;
2048 static void
2049 ns_scroll_run (struct window *w, struct run *run)
2050 /* --------------------------------------------------------------------------
2051     External (RIF):  Insert or delete n lines at line vpos
2052    -------------------------------------------------------------------------- */
2054   struct frame *f = XFRAME (w->frame);
2055   int x, y, width, height, from_y, to_y, bottom_y;
2057   NSTRACE (ns_scroll_run);
2059   /* begin copy from other terms */
2060   /* Get frame-relative bounding box of the text display area of W,
2061      without mode lines.  Include in this box the left and right
2062      fringe of W.  */
2063   window_box (w, -1, &x, &y, &width, &height);
2065   from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2066   to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2067   bottom_y = y + height;
2069   if (to_y < from_y)
2070     {
2071       /* Scrolling up.  Make sure we don't copy part of the mode
2072          line at the bottom.  */
2073       if (from_y + run->height > bottom_y)
2074         height = bottom_y - from_y;
2075       else
2076         height = run->height;
2077     }
2078   else
2079     {
2080       /* Scolling down.  Make sure we don't copy over the mode line.
2081          at the bottom.  */
2082       if (to_y + run->height > bottom_y)
2083         height = bottom_y - to_y;
2084       else
2085         height = run->height;
2086     }
2087   /* end copy from other terms */
2089   if (height == 0)
2090       return;
2092   BLOCK_INPUT;
2094   updated_window = w;
2095   x_clear_cursor (w);
2097   {
2098     NSRect srcRect = NSMakeRect (x, from_y, width, height);
2099     NSRect dstRect = NSMakeRect (x, to_y, width, height);
2100     NSPoint dstOrigin = NSMakePoint (x, to_y);
2102     ns_focus (f, &dstRect, 1);
2103     NSCopyBits (0, srcRect , dstOrigin);
2104     ns_unfocus (f);
2105   }
2107   UNBLOCK_INPUT;
2111 static void
2112 ns_after_update_window_line (struct glyph_row *desired_row)
2113 /* --------------------------------------------------------------------------
2114     External (RIF): preparatory to fringe update after text was updated
2115    -------------------------------------------------------------------------- */
2117   struct window *w = updated_window;
2118   struct frame *f;
2119   int width, height;
2121   NSTRACE (ns_after_update_window_line);
2123   /* begin copy from other terms */
2124   xassert (w);
2126   if (!desired_row->mode_line_p && !w->pseudo_window_p)
2127     desired_row->redraw_fringe_bitmaps_p = 1;
2129   /* When a window has disappeared, make sure that no rest of
2130      full-width rows stays visible in the internal border.
2131      Under NS this is drawn inside the fringes. */
2132   if (windows_or_buffers_changed
2133       && (f = XFRAME (w->frame),
2134           width = FRAME_INTERNAL_BORDER_WIDTH (f),
2135           width != 0)
2136       && (height = desired_row->visible_height,
2137           height > 0))
2138     {
2139       int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2141       /* Internal border is drawn below the tool bar.  */
2142       if (WINDOWP (f->tool_bar_window)
2143           && w == XWINDOW (f->tool_bar_window))
2144         y -= width;
2145       /* end copy from other terms */
2147       BLOCK_INPUT;
2148       if (!desired_row->full_width_p)
2149         {
2150           int x1 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2151             + WINDOW_LEFT_FRINGE_WIDTH (w);
2152           int x2 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2153             + FRAME_PIXEL_WIDTH (f) - NS_SCROLL_BAR_WIDTH (f)
2154             - WINDOW_RIGHT_FRINGE_WIDTH (w)
2155             - FRAME_INTERNAL_BORDER_WIDTH (f);
2156           ns_clear_frame_area (f, x1, y, width, height);
2157           ns_clear_frame_area (f, x2, y, width, height);
2158         }
2159       UNBLOCK_INPUT;
2160     }
2164 static void
2165 ns_shift_glyphs_for_insert (struct frame *f,
2166                            int x, int y, int width, int height,
2167                            int shift_by)
2168 /* --------------------------------------------------------------------------
2169     External (RIF): copy an area horizontally, don't worry about clearing src
2170    -------------------------------------------------------------------------- */
2172   NSRect srcRect = NSMakeRect (x, y, width, height);
2173   NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2174   NSPoint dstOrigin = dstRect.origin;
2176   NSTRACE (ns_shift_glyphs_for_insert);
2178   ns_focus (f, &dstRect, 1);
2179   NSCopyBits (0, srcRect, dstOrigin);
2180   ns_unfocus (f);
2185 /* ==========================================================================
2187     Character encoding and metrics
2189    ========================================================================== */
2192 static inline void
2193 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2194 /* --------------------------------------------------------------------------
2195      External (RIF); compute left/right overhang of whole string and set in s
2196    -------------------------------------------------------------------------- */
2198   struct face *face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2199   struct font *font = s->font; /*face->font; */
2201   if (s->char2b)
2202     {
2203       struct font_metrics metrics;
2204       unsigned int codes[2];
2205       codes[0] = *(s->char2b);
2206       codes[1] = *(s->char2b + s->nchars - 1);
2208       font->driver->text_extents (font, codes, 2, &metrics);
2209       s->left_overhang = -metrics.lbearing;
2210       s->right_overhang
2211         = metrics.rbearing > metrics.width
2212         ? metrics.rbearing - metrics.width : 0;
2213     }
2214   else
2215     {
2216       s->left_overhang = 0;
2217       s->right_overhang = ((struct nsfont_info *)font)->ital ?
2218         FONT_HEIGHT (font) * 0.2 : 0;
2219     }
2224 /* ==========================================================================
2226     Fringe and cursor drawing
2228    ========================================================================== */
2231 extern int max_used_fringe_bitmap;
2232 static void
2233 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2234                       struct draw_fringe_bitmap_params *p)
2235 /* --------------------------------------------------------------------------
2236     External (RIF); fringe-related
2237    -------------------------------------------------------------------------- */
2239   struct frame *f = XFRAME (WINDOW_FRAME (w));
2240   struct face *face = p->face;
2241   int rowY;
2242   static EmacsImage **bimgs = NULL;
2243   static int nBimgs = 0;
2244   /* NS-specific: move internal border inside fringe */
2245   int x = p->bx < 0 ? p->x : p->bx;
2246   int wd = p->bx < 0 ? p->wd : p->nx;
2247   BOOL fringeOnVeryLeft
2248     = x - WINDOW_LEFT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w)
2249       - FRAME_INTERNAL_BORDER_WIDTH (f) < 10;
2250   BOOL fringeOnVeryRight
2251     = FRAME_PIXEL_WIDTH (f) - x - wd - FRAME_INTERNAL_BORDER_WIDTH (f)
2252       - WINDOW_RIGHT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w) < 10;
2253   int xAdjust = FRAME_INTERNAL_BORDER_WIDTH (f) *
2254     (fringeOnVeryLeft ? -1 : (fringeOnVeryRight ? 1 : 0));
2256   /* grow bimgs if needed */
2257   if (nBimgs < max_used_fringe_bitmap)
2258     {
2259       EmacsImage **newBimgs
2260         = xmalloc (max_used_fringe_bitmap * sizeof (EmacsImage *));
2261       bzero (newBimgs, max_used_fringe_bitmap * sizeof (EmacsImage *));
2263       if (nBimgs)
2264         {
2265           bcopy (bimgs, newBimgs, nBimgs * sizeof (EmacsImage *));
2266           xfree (bimgs);
2267         }
2269       bimgs = newBimgs;
2270       nBimgs = max_used_fringe_bitmap;
2271     }
2273   /* Must clip because of partially visible lines.  */
2274   rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
2275   if (p->y < rowY)
2276     {
2277       /* Adjust position of "bottom aligned" bitmap on partially
2278          visible last row.  */
2279       int oldY = row->y;
2280       int oldVH = row->visible_height;
2281       row->visible_height = p->h;
2282       row->y -= rowY - p->y;
2283       ns_clip_to_row (w, row, -1, NO);
2284       row->y = oldY;
2285       row->visible_height = oldVH;
2286     }
2287   else
2288     ns_clip_to_row (w, row, -1, YES);
2290   if (p->bx >= 0 && !p->overlay_p)
2291     {
2292       int yAdjust = rowY - FRAME_INTERNAL_BORDER_WIDTH (f) < 5 ?
2293         -FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2294       int yIncr = FRAME_PIXEL_HEIGHT (f) - (p->by+yAdjust + p->ny) < 5 ?
2295         FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2296       if (yAdjust)
2297         yIncr += FRAME_INTERNAL_BORDER_WIDTH (f);
2298       NSRect r = NSMakeRect (p->bx+xAdjust, p->by+yAdjust, p->nx, p->ny+yIncr);
2299       NSRectClip (r);
2300       [ns_lookup_indexed_color(face->background, f) set];
2301       NSRectFill (r);
2302     }
2304   if (p->which)
2305     {
2306       NSRect r = NSMakeRect (p->x+xAdjust, p->y, p->wd, p->h);
2307       NSPoint pt = r.origin;
2308       EmacsImage *img = bimgs[p->which - 1];
2310       if (!img)
2311         {
2312           unsigned short *bits = p->bits + p->dh;
2313           int len = 8 * p->h/8;
2314           int i;
2315           unsigned char *cbits = xmalloc (len);
2317           for (i =0; i<len; i++)
2318             cbits[i] = ~(bits[i] & 0xff);
2319           img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2320                                            flip: NO];
2321           bimgs[p->which - 1] = img;
2322           xfree (cbits);
2323         }
2325       NSRectClip (r);
2326       /* Since we composite the bitmap instead of just blitting it, we need
2327          to erase the whole background. */
2328       [ns_lookup_indexed_color(face->background, f) set];
2329       NSRectFill (r);
2330       pt.y += p->h;
2331       [img setXBMColor: ns_lookup_indexed_color(face->foreground, f)];
2332       [img compositeToPoint: pt operation: NSCompositeSourceOver];
2333     }
2334   ns_unfocus (f);
2338 void
2339 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2340                        int x, int y, int cursor_type, int cursor_width,
2341                        int on_p, int active_p)
2342 /* --------------------------------------------------------------------------
2343      External call (RIF): draw cursor
2344      (modeled after x_draw_window_cursor
2345      FIXME: cursor_width is effectively bogus -- it sometimes gets set
2346      in xdisp.c set_frame_cursor_types, sometimes left uninitialized;
2347      DON'T USE IT (no other terms do)
2348    -------------------------------------------------------------------------- */
2350   NSRect r, s;
2351   int fx, fy, h;
2352   struct frame *f = WINDOW_XFRAME (w);
2353   struct glyph *phys_cursor_glyph;
2354   int overspill, cursorToDraw;
2356   NSTRACE (dumpcursor);
2357 //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);
2359   if (!on_p)
2360         return;
2362   w->phys_cursor_type = cursor_type;
2363   w->phys_cursor_on_p = on_p;
2365   if (cursor_type == NO_CURSOR)
2366     {
2367       w->phys_cursor_width = 0;
2368       return;
2369     }
2371   if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2372     {
2373       if (glyph_row->exact_window_width_line_p
2374           && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2375         {
2376           glyph_row->cursor_in_fringe_p = 1;
2377           draw_fringe_bitmap (w, glyph_row, 0);
2378         }
2379       return;
2380     }
2382   get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2384   r.origin.x = fx, r.origin.y = fy;
2385   r.size.height = h;
2386   r.size.width = w->phys_cursor_width;
2388   /* FIXME: if we overwrite the internal border area, it does not get erased;
2389      fix by truncating cursor, but better would be to erase properly */
2390   overspill = r.origin.x + r.size.width -
2391     WINDOW_TEXT_TO_FRAME_PIXEL_X (w, WINDOW_BOX_RIGHT_EDGE_X (w) 
2392       - WINDOW_TOTAL_FRINGE_WIDTH (w) - FRAME_INTERNAL_BORDER_WIDTH (f));
2393   if (overspill > 0)
2394     r.size.width -= overspill;
2396   /* TODO: only needed in rare cases with last-resort font in HELLO..
2397      should we do this more efficiently? */
2398   ns_clip_to_row (w, glyph_row, -1, NO); /* do ns_focus(f, &r, 1); if remove */
2399   [FRAME_CURSOR_COLOR (f) set];
2401 #ifdef NS_IMPL_COCOA
2402   /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2403            atomic.  Cleaner ways of doing this should be investigated.
2404            One way would be to set a global variable DRAWING_CURSOR
2405            when making the call to draw_phys..(), don't focus in that
2406            case, then move the ns_unfocus() here after that call. */
2407   NSDisableScreenUpdates ();
2408 #endif
2410   cursorToDraw = active_p ? cursor_type : HOLLOW_BOX_CURSOR;
2411   switch (cursorToDraw)
2412     {
2413     case NO_CURSOR:
2414       break;
2415     case FILLED_BOX_CURSOR:
2416       NSRectFill (r);
2417       break;
2418     case HOLLOW_BOX_CURSOR:
2419       NSRectFill (r);
2420       [FRAME_BACKGROUND_COLOR (f) set];
2421       NSRectFill (NSInsetRect (r, 1, 1));
2422       [FRAME_CURSOR_COLOR (f) set];
2423       break;
2424     case HBAR_CURSOR:
2425       s = r;
2426       s.origin.y += lrint (0.75 * s.size.height);
2427       s.size.width = min (FRAME_COLUMN_WIDTH (f), s.size.width);
2428       s.size.height = lrint (s.size.height * 0.25);
2429       NSRectFill (s);
2430       break;
2431     case BAR_CURSOR:
2432       s = r;
2433       s.size.width = min (cursor_width, 2); //FIXME(see above)
2434       NSRectFill (s);
2435       break;
2436     }
2437   ns_unfocus (f);
2439   /* draw the character under the cursor */
2440   if (cursorToDraw != NO_CURSOR)
2441     draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2443 #ifdef NS_IMPL_COCOA
2444   NSEnableScreenUpdates ();
2445 #endif
2450 static void
2451 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2452 /* --------------------------------------------------------------------------
2453      External (RIF): Draw a vertical line.
2454    -------------------------------------------------------------------------- */
2456   struct frame *f = XFRAME (WINDOW_FRAME (w));
2457   struct face *face;
2458   NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2460   NSTRACE (ns_draw_vertical_window_border);
2462   face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2463   if (face)
2464       [ns_lookup_indexed_color(face->foreground, f) set];
2466   ns_focus (f, &r, 1);
2467   NSRectFill(r);
2468   ns_unfocus (f);
2472 void
2473 show_hourglass (struct atimer *timer)
2475   if (hourglass_shown_p)
2476     return;
2478   BLOCK_INPUT;
2480   /* TODO: add NSProgressIndicator to selected frame (see macfns.c) */
2482   hourglass_shown_p = 1;
2483   UNBLOCK_INPUT;
2487 void
2488 hide_hourglass ()
2490   if (!hourglass_shown_p)
2491     return;
2493   BLOCK_INPUT;
2495   /* TODO: remove NSProgressIndicator from all frames */
2497   hourglass_shown_p = 0;
2498   UNBLOCK_INPUT;
2503 /* ==========================================================================
2505     Glyph drawing operations
2507    ========================================================================== */
2510 static inline NSRect
2511 ns_fix_rect_ibw (NSRect r, int fibw, int frame_pixel_width)
2512 /* --------------------------------------------------------------------------
2513     Under NS we draw internal borders inside fringes, and want full-width
2514     rendering to go all the way to edge.  This function makes that correction.
2515    -------------------------------------------------------------------------- */
2517   if (r.origin.y <= fibw+1)
2518     {
2519       r.size.height += r.origin.y;
2520       r.origin.y = 0;
2521     }
2522   if (r.origin.x <= fibw+1)
2523     {
2524       r.size.width += r.origin.x;
2525       r.origin.x = 0;
2526     }
2527   if (frame_pixel_width - (r.origin.x+r.size.width) <= fibw+1)
2528     r.size.width += fibw;
2530   return r;
2534 static int
2535 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2536 /* --------------------------------------------------------------------------
2537     Wrapper utility to account for internal border width on full-width lines,
2538     and allow top full-width rows to hit the frame top.  nr should be pointer
2539     to two successive NSRects.  Number of rects actually used is returned.
2540    -------------------------------------------------------------------------- */
2542   int n = get_glyph_string_clip_rects (s, nr, 2);
2543   if (s->row->full_width_p)
2544     {
2545       *nr = ns_fix_rect_ibw (*nr, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2546                             FRAME_PIXEL_WIDTH (s->f));
2547       if (n == 2)
2548         *nr = ns_fix_rect_ibw (*(nr+1), FRAME_INTERNAL_BORDER_WIDTH (s->f),
2549                               FRAME_PIXEL_WIDTH (s->f));
2550     }
2551   return n;
2555 static void
2556 ns_draw_box (NSRect r, float thickness, NSColor *col, char left_p, char right_p)
2557 /* --------------------------------------------------------------------------
2558     Draw an unfilled rect inside r, optionally leaving left and/or right open.
2559     Note we can't just use an NSDrawRect command, because of the possibility
2560     of some sides not being drawn, and because the rect will be filled.
2561    -------------------------------------------------------------------------- */
2563   NSRect s = r;
2564   [col set];
2566   /* top, bottom */
2567   s.size.height = thickness;
2568   NSRectFill (s);
2569   s.origin.y += r.size.height - thickness;
2570   NSRectFill (s);
2572   s.size.height = r.size.height;
2573   s.origin.y = r.origin.y;
2575   /* left, right (optional) */
2576   s.size.width = thickness;
2577   if (left_p)
2578     NSRectFill (s);
2579   if (right_p)
2580     {
2581       s.origin.x += r.size.width - thickness;
2582       NSRectFill (s);
2583     }
2587 static void
2588 ns_draw_relief (NSRect r, int thickness, char raised_p,
2589                char top_p, char bottom_p, char left_p, char right_p,
2590                struct glyph_string *s)
2591 /* --------------------------------------------------------------------------
2592     Draw a relief rect inside r, optionally leaving some sides open.
2593     Note we can't just use an NSDrawBezel command, because of the possibility
2594     of some sides not being drawn, and because the rect will be filled.
2595    -------------------------------------------------------------------------- */
2597   static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2598   NSColor *newBaseCol = nil;
2599   NSRect sr = r;
2601   NSTRACE (ns_draw_relief);
2603   /* set up colors */
2605   if (s->face->use_box_color_for_shadows_p)
2606     {
2607       newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2608     }
2609 /*     else if (s->first_glyph->type == IMAGE_GLYPH
2610            && s->img->pixmap
2611            && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2612        {
2613          newBaseCol = IMAGE_BACKGROUND  (s->img, s->f, 0);
2614        } */
2615   else
2616     {
2617       newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2618     }
2620   if (newBaseCol == nil)
2621     newBaseCol = [NSColor grayColor];
2623   if (newBaseCol != baseCol)  /* TODO: better check */
2624     {
2625       [baseCol release];
2626       baseCol = [newBaseCol retain];
2627       [lightCol release];
2628       lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2629       [darkCol release];
2630       darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2631     }
2633   [(raised_p ? lightCol : darkCol) set];
2635   /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2637   /* top */
2638   sr.size.height = thickness;
2639   if (top_p) NSRectFill (sr);
2641   /* left */
2642   sr.size.height = r.size.height;
2643   sr.size.width = thickness;
2644   if (left_p) NSRectFill (sr);
2646   [(raised_p ? darkCol : lightCol) set];
2648   /* bottom */
2649   sr.size.width = r.size.width;
2650   sr.size.height = thickness;
2651   sr.origin.y += r.size.height - thickness;
2652   if (bottom_p) NSRectFill (sr);
2654   /* right */
2655   sr.size.height = r.size.height;
2656   sr.origin.y = r.origin.y;
2657   sr.size.width = thickness;
2658   sr.origin.x += r.size.width - thickness;
2659   if (right_p) NSRectFill (sr);
2663 static void
2664 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2665 /* --------------------------------------------------------------------------
2666       Function modeled after x_draw_glyph_string_box ().
2667       Sets up parameters for drawing.
2668    -------------------------------------------------------------------------- */
2670   int right_x, last_x;
2671   char left_p, right_p;
2672   struct glyph *last_glyph;
2673   NSRect r;
2674   int thickness;
2675   struct face *face;
2677   if (s->hl == DRAW_MOUSE_FACE)
2678     {
2679       face = FACE_FROM_ID
2680         (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2681       if (!face)
2682         face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2683     }
2684   else
2685     face = s->face;
2687   thickness = face->box_line_width;
2689   NSTRACE (ns_dumpglyphs_box_or_relief);
2691   last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2692             ? WINDOW_RIGHT_EDGE_X (s->w)
2693             : window_box_right (s->w, s->area));
2694   last_glyph = (s->cmp || s->img
2695                 ? s->first_glyph : s->first_glyph + s->nchars-1);
2697   right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2698               ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2700   left_p = (s->first_glyph->left_box_line_p
2701             || (s->hl == DRAW_MOUSE_FACE
2702                 && (s->prev == NULL || s->prev->hl != s->hl)));
2703   right_p = (last_glyph->right_box_line_p
2704              || (s->hl == DRAW_MOUSE_FACE
2705                  && (s->next == NULL || s->next->hl != s->hl)));
2707   r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2709   /* expand full-width row over internal borders */
2710   if (s->row->full_width_p)
2711     r = ns_fix_rect_ibw (r, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2712                         FRAME_PIXEL_WIDTH (s->f));
2714   if (s->face->box == FACE_SIMPLE_BOX)
2715     {
2716       xassert (s->face->box_color != nil);
2717       ns_draw_box (r, abs (thickness),
2718                    ns_lookup_indexed_color (face->box_color, s->f),
2719                   left_p, right_p);
2720     }
2721   else
2722     {
2723       ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2724                      1, 1, left_p, right_p, s);
2725     }
2729 static void
2730 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2731 /* --------------------------------------------------------------------------
2732       Modeled after x_draw_glyph_string_background, which draws BG in
2733       certain cases.  Others are left to the text rendering routine.
2734    -------------------------------------------------------------------------- */
2736   NSTRACE (ns_maybe_dumpglyphs_background);
2738   if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2739     {
2740       int box_line_width = max (s->face->box_line_width, 0);
2741       if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2742           || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2743         {
2744           struct face *face;
2745           if (s->hl == DRAW_MOUSE_FACE)
2746             {
2747               face = FACE_FROM_ID
2748                 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2749               if (!face)
2750                 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2751             }
2752           else
2753             face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2754           if (!face->stipple)
2755             [(NS_FACE_BACKGROUND (face) != 0
2756               ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2757               : FRAME_BACKGROUND_COLOR (s->f)) set];
2758           else
2759             {
2760               struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (s->f);
2761               [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2762             }
2764           if (s->hl != DRAW_CURSOR)
2765             {
2766               NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2767                                     s->background_width,
2768                                     s->height-2*box_line_width);
2770               /* expand full-width row over internal borders */
2771               if (s->row->full_width_p)
2772                 {
2773                   int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2774                   if (r.origin.y <= fibw+1 + box_line_width)
2775                     {
2776                       r.size.height += r.origin.y;
2777                       r.origin.y = 0;
2778                     }
2779                   if (r.origin.x <= fibw+1)
2780                     {
2781                       r.size.width += 2*r.origin.x;
2782                       r.origin.x = 0;
2783                     }
2784                   if (FRAME_PIXEL_WIDTH (s->f) - (r.origin.x + r.size.width)
2785                       <= fibw+1)
2786                     r.size.width += fibw;
2787                 }
2789               NSRectFill (r);
2790             }
2792           s->background_filled_p = 1;
2793         }
2794     }
2798 static void
2799 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2800 /* --------------------------------------------------------------------------
2801       Renders an image and associated borders.
2802    -------------------------------------------------------------------------- */
2804   EmacsImage *img = s->img->pixmap;
2805   int box_line_vwidth = max (s->face->box_line_width, 0);
2806   int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2807   int bg_x, bg_y, bg_height;
2808   int th;
2809   char raised_p;
2810   NSRect br;
2812   NSTRACE (ns_dumpglyphs_image);
2814   if (s->face->box != FACE_NO_BOX
2815       && s->first_glyph->left_box_line_p && s->slice.x == 0)
2816     x += abs (s->face->box_line_width);
2818   bg_x = x;
2819   bg_y =  s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2820   bg_height = s->height;
2821   /* other terms have this, but was causing problems w/tabbar mode */
2822   /* - 2 * box_line_vwidth; */
2824   if (s->slice.x == 0) x += s->img->hmargin;
2825   if (s->slice.y == 0) y += s->img->vmargin;
2827   /* Draw BG: if we need larger area than image itself cleared, do that,
2828      otherwise, since we composite the image under NS (instead of mucking
2829      with its background color), we must clear just the image area. */
2830   [ns_lookup_indexed_color (NS_FACE_BACKGROUND
2831             (FACE_FROM_ID (s->f, s->first_glyph->face_id)), s->f) set];
2833   if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
2834       || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
2835     {
2836       br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
2837       s->background_filled_p = 1;
2838     }
2839   else
2840     {
2841       br = NSMakeRect (x, y, s->slice.width, s->slice.height);
2842     }
2844   /* expand full-width row over internal borders */
2845   if (s->row->full_width_p)
2846     {
2847       int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2848       if (br.origin.y <= fibw+1 + box_line_vwidth)
2849         {
2850           br.size.height += br.origin.y;
2851           br.origin.y = 0;
2852         }
2853       if (br.origin.x <= fibw+1 + box_line_vwidth)
2854         {
2855           br.size.width += br.origin.x;
2856           br.origin.x = 0;
2857         }
2858       if (FRAME_PIXEL_WIDTH (s->f) - (br.origin.x + br.size.width) <= fibw+1)
2859         br.size.width += fibw;
2860     }
2862   NSRectFill (br);
2864   /* Draw the image.. do we need to draw placeholder if img ==nil? */
2865   if (img != nil)
2866     [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
2867                 operation: NSCompositeSourceOver];
2869   /* Draw relief, if requested */
2870   if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
2871     {
2872       if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
2873         {
2874           th = tool_bar_button_relief >= 0 ?
2875             tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2876           raised_p = (s->hl == DRAW_IMAGE_RAISED);
2877         }
2878       else
2879         {
2880           th = abs (s->img->relief);
2881           raised_p = (s->img->relief > 0);
2882         }
2884       r.origin.x = x - th;
2885       r.origin.y = y - th;
2886       r.size.width = s->slice.width + 2*th-1;
2887       r.size.height = s->slice.height + 2*th-1;
2888       ns_draw_relief (r, th, raised_p,
2889                       s->slice.y == 0,
2890                       s->slice.y + s->slice.height == s->img->height,
2891                       s->slice.x == 0,
2892                       s->slice.x + s->slice.width == s->img->width, s);
2893     }
2897 static void
2898 ns_dumpglyphs_stretch (struct glyph_string *s)
2900   NSRect r[2];
2901   int n, i;
2903   if (!s->background_filled_p)
2904     {
2905       n = ns_get_glyph_string_clip_rect (s, r);
2906       *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
2908       for (i=0; i<n; i++)
2909         {
2910           if (!s->row->full_width_p)
2911             {
2912               /* truncate to avoid overwriting fringe and/or scrollbar */
2913               int overrun = max (0, (s->x + s->background_width)
2914                                   - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
2915                                     - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
2916               r[i].size.width -= overrun;
2918               /* XXX: Try to work between problem where a stretch glyph on
2919                  a partially-visible bottom row will clear part of the
2920                  modeline, and another where list-buffers headers and similar
2921                  rows erroneously have visible_height set to 0.  Not sure
2922                  where this is coming from as other terms seem not to show. */
2923               r[i].size.height = min (s->height, s->row->visible_height);
2924             }
2926           /* expand full-width rows over internal borders */
2927           else
2928             {
2929               r[i] = ns_fix_rect_ibw (r[i], FRAME_INTERNAL_BORDER_WIDTH (s->f),
2930                                       FRAME_PIXEL_WIDTH (s->f));
2931             }
2933           /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
2934              overwriting cursor (usually when cursor on a tab) */
2935           if (s->hl == DRAW_CURSOR)
2936             {
2937               r[i].origin.x += s->width;
2938               r[i].size.width -= s->width;
2939             }
2940         }
2942       ns_focus (s->f, r, n);
2943       [ns_lookup_indexed_color (NS_FACE_BACKGROUND
2944            (FACE_FROM_ID (s->f, s->first_glyph->face_id)), s->f) set];
2945       NSRectFill (r[0]);
2946       NSRectFill (r[1]);
2947       ns_unfocus (s->f);
2948       s->background_filled_p = 1;
2949     }
2953 static void
2954 ns_draw_glyph_string (struct glyph_string *s)
2955 /* --------------------------------------------------------------------------
2956       External (RIF): Main draw-text call.
2957    -------------------------------------------------------------------------- */
2959   /* TODO (optimize): focus for box and contents draw */
2960   NSRect r[2];
2961   int n;
2962   char box_drawn_p = 0;
2964   NSTRACE (ns_draw_glyph_string);
2966   if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
2967     {
2968       int width;
2969       struct glyph_string *next;
2971       for (width = 0, next = s->next;
2972            next && width < s->right_overhang;
2973            width += next->width, next = next->next)
2974         if (next->first_glyph->type != IMAGE_GLYPH)
2975           {
2976             if (next->first_glyph->type != STRETCH_GLYPH)
2977               {
2978                 n = ns_get_glyph_string_clip_rect (s->next, r);
2979                 ns_focus (s->f, r, n);
2980                 ns_maybe_dumpglyphs_background (s->next, 1);
2981                 ns_unfocus (s->f);
2982               }
2983             else
2984               {
2985                 ns_dumpglyphs_stretch (s->next);
2986               }
2987             next->num_clips = 0;
2988           }
2989     }
2991   if (!s->for_overlaps && s->face->box != FACE_NO_BOX
2992         && (s->first_glyph->type == CHAR_GLYPH
2993             || s->first_glyph->type == COMPOSITE_GLYPH))
2994     {
2995       n = ns_get_glyph_string_clip_rect (s, r);
2996       ns_focus (s->f, r, n);
2997       ns_maybe_dumpglyphs_background (s, 1);
2998       ns_dumpglyphs_box_or_relief (s);
2999       ns_unfocus (s->f);
3000       box_drawn_p = 1;
3001     }
3003   switch (s->first_glyph->type)
3004     {
3006     case IMAGE_GLYPH:
3007       n = ns_get_glyph_string_clip_rect (s, r);
3008       ns_focus (s->f, r, n);
3009       ns_dumpglyphs_image (s, r[0]);
3010       ns_unfocus (s->f);
3011       break;
3013     case STRETCH_GLYPH:
3014       ns_dumpglyphs_stretch (s);
3015       break;
3017     case CHAR_GLYPH:
3018     case COMPOSITE_GLYPH:
3019       n = ns_get_glyph_string_clip_rect (s, r);
3020       ns_focus (s->f, r, n);
3022       if (s->for_overlaps || (s->cmp_from > 0
3023                               && ! s->first_glyph->u.cmp.automatic))
3024         s->background_filled_p = 1;
3025       else      /* 1 */
3026         ns_maybe_dumpglyphs_background
3027           (s, s->first_glyph->type == COMPOSITE_GLYPH);
3029       ns_tmp_flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3030                     (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3031                      (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3032                       NS_DUMPGLYPH_NORMAL));
3033       ns_tmp_font = (struct nsfont_info *)s->face->font;
3034       if (ns_tmp_font == NULL)
3035           ns_tmp_font = (struct nsfont_info *)FRAME_FONT (s->f);
3037       ns_tmp_font->font.driver->draw
3038         (s, 0, s->nchars, s->x, s->y,
3039          (ns_tmp_flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3040          || ns_tmp_flags == NS_DUMPGLYPH_MOUSEFACE);
3042       ns_unfocus (s->f);
3043       break;
3045     default:
3046       abort ();
3047     }
3049   /* Draw box if not done already. */
3050   if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3051     {
3052       n = ns_get_glyph_string_clip_rect (s, r);
3053       ns_focus (s->f, r, n);
3054       ns_dumpglyphs_box_or_relief (s);
3055       ns_unfocus (s->f);
3056     }
3058   s->num_clips = 0;
3063 /* ==========================================================================
3065     Event loop
3067    ========================================================================== */
3070 static void
3071 ns_send_appdefined (int value)
3072 /* --------------------------------------------------------------------------
3073     Internal: post an appdefined event which EmacsApp-sendEvent will
3074               recognize and take as a command to halt the event loop.
3075    -------------------------------------------------------------------------- */
3077   /*NSTRACE (ns_send_appdefined); */
3079   /* Only post this event if we haven't already posted one.  This will end
3080        the [NXApp run] main loop after having processed all events queued at
3081        this moment.  */
3082   if (send_appdefined)
3083     {
3084       NSEvent *nxev;
3086       /* We only need one NX_APPDEFINED event to stop NXApp from running.  */
3087       send_appdefined = NO;
3089       /* Don't need wakeup timer any more */
3090       if (timed_entry)
3091         {
3092           [timed_entry invalidate];
3093           [timed_entry release];
3094           timed_entry = nil;
3095         }
3097       /* Ditto for file descriptor poller */
3098       if (fd_entry)
3099         {
3100           [fd_entry invalidate];
3101           [fd_entry release];
3102           fd_entry = nil;
3103         }
3105       nxev = [NSEvent otherEventWithType: NSApplicationDefined
3106                                 location: NSMakePoint (0, 0)
3107                            modifierFlags: 0
3108                                timestamp: 0
3109                             windowNumber: [[NSApp mainWindow] windowNumber]
3110                                  context: [NSApp context]
3111                                  subtype: 0
3112                                    data1: value
3113                                    data2: 0];
3115       /* Post an application defined event on the event queue.  When this is
3116          received the [NXApp run] will return, thus having processed all
3117          events which are currently queued.  */
3118       [NSApp postEvent: nxev atStart: NO];
3119     }
3123 static int
3124 ns_read_socket (struct terminal *terminal, int expected,
3125                 struct input_event *hold_quit)
3126 /* --------------------------------------------------------------------------
3127      External (hook): Post an event to ourself and keep reading events until
3128      we read it back again.  In effect process all events which were waiting.
3129      From 21+ we have to manage the event buffer ourselves.
3130    -------------------------------------------------------------------------- */
3132   struct input_event ev;
3133   int nevents;
3134   static NSDate *lastCheck = nil;
3136 /* NSTRACE (ns_read_socket); */
3138   if (interrupt_input_blocked)
3139     {
3140       interrupt_input_pending = 1;
3141 #ifdef SYNC_INPUT
3142       pending_signals = 1;
3143 #endif
3144       return -1;
3145     }
3147   interrupt_input_pending = 0;
3148 #ifdef SYNC_INPUT
3149   pending_signals = pending_atimers;
3150 #endif
3152   BLOCK_INPUT;
3153   n_emacs_events_pending = 0;
3154   EVENT_INIT (ev);
3155   emacs_event = &ev;
3156   q_event_ptr = hold_quit;
3158   /* we manage autorelease pools by allocate/reallocate each time around
3159      the loop; strict nesting is occasionally violated but seems not to
3160      matter.. earlier methods using full nesting caused major memory leaks */
3161   [outerpool release];
3162   outerpool = [[NSAutoreleasePool alloc] init];
3164   /* If have pending open-file requests, attend to the next one of those. */
3165   if (ns_pending_files && [ns_pending_files count] != 0
3166       && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3167     {
3168       [ns_pending_files removeObjectAtIndex: 0];
3169     }
3170   /* Deal with pending service requests. */
3171   else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3172     && [(EmacsApp *)
3173          NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3174                       withArg: [ns_pending_service_args objectAtIndex: 0]])
3175     {
3176       [ns_pending_service_names removeObjectAtIndex: 0];
3177       [ns_pending_service_args removeObjectAtIndex: 0];
3178     }
3179   else
3180     {
3181       /* Run and wait for events.  We must always send one NX_APPDEFINED event
3182          to ourself, otherwise [NXApp run] will never exit.  */
3183       send_appdefined = YES;
3185       /* If called via ns_select, this is called once with expected=1,
3186          because we expect either the timeout or file descriptor activity.
3187          In this case the first event through will either be real input or
3188          one of these.  read_avail_input() then calls once more with expected=0
3189          and in that case we need to return quickly if there is nothing.
3190          If we're being called outside of that, it's also OK to return quickly
3191          after one iteration through the event loop, since other terms do
3192          this and emacs expects it. */
3193       if (!(inNsSelect && expected))  // (!inNsSelect || !expected)
3194         {
3195           /* Post an application defined event on the event queue.  When this is
3196              received the [NXApp run] will return, thus having processed all
3197              events which are currently queued, if any.  */
3198           ns_send_appdefined (-1);
3199         }
3201       [NSApp run];
3202     }
3204   nevents = n_emacs_events_pending;
3205   n_emacs_events_pending = 0;
3206   emacs_event = q_event_ptr = NULL;
3207   UNBLOCK_INPUT;
3209   return nevents;
3214 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3215            fd_set *exceptfds, struct timeval *timeout)
3216 /* --------------------------------------------------------------------------
3217      Replacement for select, checking for events
3218    -------------------------------------------------------------------------- */
3220   int result;
3221   double time;
3222   NSEvent *ev;
3223 /*  NSTRACE (ns_select); */
3225   if (NSApp == nil || inNsSelect == 1 /* || ([NSApp isActive] == NO &&
3226                       [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
3227  inMode:NSDefaultRunLoopMode dequeue:NO] == nil) */)
3228     return select (nfds, readfds, writefds, exceptfds, timeout);
3230   /* Save file descriptor set, which gets overwritten in calls to select ()
3231      Note, this is called from process.c, and only readfds is ever set */
3232   if (readfds)
3233     {
3234       memcpy (&select_readfds, readfds, sizeof (fd_set));
3235       select_nfds = nfds;
3236     }
3237   else
3238     select_nfds = 0;
3240     /* Try an initial select for pending data on input files */
3241   select_timeout.tv_sec = select_timeout.tv_usec = 0;
3242   result = select (nfds, readfds, writefds, exceptfds, &select_timeout);
3243   if (result)
3244     return result;
3246   /* if (!timeout || timed_entry || fd_entry)
3247        fprintf (stderr, "assertion failed: timeout null or timed_entry/fd_entry non-null in ns_select\n"); */
3249     /* set a timeout and run the main AppKit event loop while continuing
3250        to monitor the files */
3251   time = ((double) timeout->tv_sec) + ((double) timeout->tv_usec)/1000000.0;
3252   timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3253                                            target: NSApp
3254                                          selector: @selector (timeout_handler:)
3255                                          userInfo: 0
3256                                           repeats: YES] /* for safe removal */
3257                                                          retain];
3259   /* set a periodic task to try the select () again */
3260   fd_entry = [[NSTimer scheduledTimerWithTimeInterval: 0.1
3261                                                target: NSApp
3262                                              selector: @selector (fd_handler:)
3263                                              userInfo: 0
3264                                               repeats: YES]
3265                retain];
3267   /* Let Application dispatch events until it receives an event of the type
3268      NX_APPDEFINED, which should only be sent by timeout_handler.
3269      We tell read_avail_input() that input is "expected" because we do expect
3270      either the timeout or fd handler to fire, and if they don't, the original
3271      call from process.c that got us here expects us to wait until some input
3272      comes. */
3273   inNsSelect = 1;
3274   gobble_input (1);
3275   ev = last_appdefined_event;
3276   inNsSelect = 0;
3278   if (ev)
3279     {
3280       int t;
3281       if ([ev type] != NSApplicationDefined)
3282         abort ();
3284       t = [ev data1];
3285       last_appdefined_event = 0;
3287       if (t == -2)
3288         {
3289           /* The NX_APPDEFINED event we received was a timeout. */
3290           return 0;
3291         }
3292       else if (t == -1)
3293         {
3294           /* The NX_APPDEFINED event we received was the result of
3295              at least one real input event arriving.  */
3296           errno = EINTR;
3297           return -1;
3298         }
3299       else
3300         {
3301           /* Received back from select () in fd_handler; copy the results */
3302           if (readfds)
3303             memcpy (readfds, &select_readfds, sizeof (fd_set));
3304           return t;
3305         }
3306     }
3307   /* never reached, shut compiler up */
3308   return 0;
3313 /* ==========================================================================
3315     Scrollbar handling
3317    ========================================================================== */
3320 static void
3321 ns_set_vertical_scroll_bar (struct window *window,
3322                            int portion, int whole, int position)
3323 /* --------------------------------------------------------------------------
3324       External (hook): Update or add scrollbar
3325    -------------------------------------------------------------------------- */
3327   Lisp_Object win;
3328   NSRect r, v;
3329   struct frame *f = XFRAME (WINDOW_FRAME (window));
3330   EmacsView *view = FRAME_NS_VIEW (f);
3331   int window_y, window_height;
3332   BOOL barOnVeryLeft, barOnVeryRight;
3333   int top, left, height, width, sb_width, sb_left;
3334   EmacsScroller *bar;
3335 static int count = 0;
3337   /* optimization; display engine sends WAY too many of these.. */
3338   if (!NILP (window->vertical_scroll_bar))
3339     {
3340       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3341       if ([bar checkSamePosition: position portion: portion whole: whole])
3342         {
3343           if (view->scrollbarsNeedingUpdate == 0)
3344             {
3345               if (!windows_or_buffers_changed)
3346                   return;
3347             }
3348           else
3349             view->scrollbarsNeedingUpdate--;
3350         }
3351     }
3353   NSTRACE (ns_set_vertical_scroll_bar);
3355   /* Get dimensions.  */
3356   window_box (window, -1, 0, &window_y, 0, &window_height);
3357   top = window_y;
3358   height = window_height;
3359   width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3360   left = WINDOW_SCROLL_BAR_AREA_X (window);
3362   if (top < 5) /* top scrollbar adjustment */
3363     {
3364       top -= FRAME_INTERNAL_BORDER_WIDTH (f);
3365       height += FRAME_INTERNAL_BORDER_WIDTH (f);
3366     }
3368   /* allow for displaying a skinnier scrollbar than char area allotted */
3369   sb_width = (WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) > 0) ?
3370     WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) : width;
3372   barOnVeryLeft = left < 5;
3373   barOnVeryRight = FRAME_PIXEL_WIDTH (f) - left - width < 5;
3374   sb_left = left + FRAME_INTERNAL_BORDER_WIDTH (f)
3375       * (barOnVeryLeft ? -1 : (barOnVeryRight ? 1 : 0));
3377   r = NSMakeRect (sb_left, top, sb_width, height);
3378   /* the parent view is flipped, so we need to flip y value */
3379   v = [view frame];
3380   r.origin.y = (v.size.height - r.size.height - r.origin.y);
3382   XSETWINDOW (win, window);
3383   BLOCK_INPUT;
3385   /* we want at least 5 lines to display a scrollbar */
3386   if (WINDOW_TOTAL_LINES (window) < 5)
3387     {
3388       if (!NILP (window->vertical_scroll_bar))
3389         {
3390           bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3391           [bar removeFromSuperview];
3392           window->vertical_scroll_bar = Qnil;
3393         }
3394       ns_clear_frame_area (f, sb_left, top, width, height);
3395       UNBLOCK_INPUT;
3396       return;
3397     }
3399   if (NILP (window->vertical_scroll_bar))
3400     {
3401       ns_clear_frame_area (f, sb_left, top, width, height);
3402       bar = [[EmacsScroller alloc] initFrame: r window: win];
3403       window->vertical_scroll_bar = make_save_value (bar, 0);
3404     }
3405   else
3406     {
3407       NSRect oldRect;
3408       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3409       oldRect = [bar frame];
3410       r.size.width = oldRect.size.width;
3411       if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3412         {
3413           if (oldRect.origin.x != r.origin.x)
3414               ns_clear_frame_area (f, sb_left, top, width, height);
3415           [bar setFrame: r];
3416         }
3417     }
3419   [bar setPosition: position portion: portion whole: whole];
3420   UNBLOCK_INPUT;
3424 static void
3425 ns_condemn_scroll_bars (struct frame *f)
3426 /* --------------------------------------------------------------------------
3427      External (hook): arrange for all frame's scrollbars to be removed
3428      at next call to judge_scroll_bars, except for those redeemed.
3429    -------------------------------------------------------------------------- */
3431   int i;
3432   id view;
3433   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3435   NSTRACE (ns_condemn_scroll_bars);
3437   for (i =[subviews count]-1; i >= 0; i--)
3438     {
3439       view = [subviews objectAtIndex: i];
3440       if ([view isKindOfClass: [EmacsScroller class]])
3441         [view condemn];
3442     }
3446 static void
3447 ns_redeem_scroll_bar (struct window *window)
3448 /* --------------------------------------------------------------------------
3449      External (hook): arrange to spare this window's scrollbar
3450      at next call to judge_scroll_bars.
3451    -------------------------------------------------------------------------- */
3453   id bar;
3454   NSTRACE (ns_redeem_scroll_bar);
3455   if (!NILP (window->vertical_scroll_bar))
3456     {
3457       bar =XNS_SCROLL_BAR (window->vertical_scroll_bar);
3458       [bar reprieve];
3459     }
3463 static void
3464 ns_judge_scroll_bars (struct frame *f)
3465 /* --------------------------------------------------------------------------
3466      External (hook): destroy all scrollbars on frame that weren't
3467      redeemed after call to condemn_scroll_bars.
3468    -------------------------------------------------------------------------- */
3470   int i;
3471   id view;
3472   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3473   NSTRACE (ns_judge_scroll_bars);
3474   for (i =[subviews count]-1; i >= 0; i--)
3475     {
3476       view = [subviews objectAtIndex: i];
3477       if (![view isKindOfClass: [EmacsScroller class]]) continue;
3478       [view judge];
3479     }
3483 void
3484 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
3486   /* XXX irrelevant under NS */
3491 /* ==========================================================================
3493     Initialization
3495    ========================================================================== */
3498 x_display_pixel_height (dpyinfo)
3499      struct ns_display_info *dpyinfo;
3501   NSScreen *screen = [NSScreen mainScreen];
3502   return [screen frame].size.height;
3506 x_display_pixel_width (dpyinfo)
3507      struct ns_display_info *dpyinfo;
3509   NSScreen *screen = [NSScreen mainScreen];
3510   return [screen frame].size.width;
3514 static Lisp_Object ns_string_to_lispmod (const char *s)
3515 /* --------------------------------------------------------------------------
3516      Convert modifier name to lisp symbol
3517    -------------------------------------------------------------------------- */
3519   if (!strncmp (SDATA (SYMBOL_NAME (Qmeta)), s, 10))
3520     return Qmeta;
3521   else if (!strncmp (SDATA (SYMBOL_NAME (Qsuper)), s, 10))
3522     return Qsuper;
3523   else if (!strncmp (SDATA (SYMBOL_NAME (Qcontrol)), s, 10))
3524     return Qcontrol;
3525   else if (!strncmp (SDATA (SYMBOL_NAME (Qalt)), s, 10))
3526     return Qalt;
3527   else if (!strncmp (SDATA (SYMBOL_NAME (Qhyper)), s, 10))
3528     return Qhyper;
3529   else if (!strncmp (SDATA (SYMBOL_NAME (Qnone)), s, 10))
3530     return Qnone;
3531   else
3532     return Qnil;
3536 static Lisp_Object ns_mod_to_lisp (int m)
3537 /* --------------------------------------------------------------------------
3538      Convert modifier code (see lisp.h) to lisp symbol
3539    -------------------------------------------------------------------------- */
3541   if (m == CHAR_META)
3542     return Qmeta;
3543   else if (m == CHAR_SUPER)
3544     return Qsuper;
3545   else if (m == CHAR_CTL)
3546     return Qcontrol;
3547   else if (m == CHAR_ALT)
3548     return Qalt;
3549   else if (m == CHAR_HYPER)
3550     return Qhyper;
3551   else /* if (m == 0) */
3552     return Qnone;
3556 static void
3557 ns_set_default_prefs ()
3558 /* --------------------------------------------------------------------------
3559       Initialize preference variables to defaults
3560    -------------------------------------------------------------------------- */
3562   ns_alternate_modifier = Qmeta;
3563   ns_command_modifier = Qsuper;
3564   ns_control_modifier = Qcontrol;
3565   ns_function_modifier = Qnone;
3566   ns_expand_space = make_float (0.0);
3567   ns_antialias_text = Qt;
3568   ns_antialias_threshold = 10.0; /* not exposed to lisp side */
3569   ns_use_qd_smoothing = Qnil;
3570   ns_use_system_highlight_color = Qt;
3571   ns_confirm_quit = Qnil;
3575 static void
3576 ns_default (const char *parameter, Lisp_Object *result,
3577            Lisp_Object yesval, Lisp_Object noval,
3578            BOOL is_float, BOOL is_modstring)
3579 /* --------------------------------------------------------------------------
3580       Check a parameter value in user's preferences
3581    -------------------------------------------------------------------------- */
3583   const char *value;
3585   if ( (value =[[[NSUserDefaults standardUserDefaults]
3586                    stringForKey: [NSString stringWithUTF8String: parameter]]
3587                 UTF8String]) )
3588     {
3589       double f;
3590       char *pos;
3591       if (strcasecmp (value, "YES") == 0)
3592         *result = yesval;
3593       else if (strcasecmp (value, "NO") == 0)
3594         *result = noval;
3595       else if (is_float && (f = strtod (value, &pos), pos != value))
3596         *result = make_float (f);
3597       else if (is_modstring && value)
3598         *result = ns_string_to_lispmod (value);
3599       else fprintf (stderr,
3600                    "Bad value for default \"%s\": \"%s\"\n", parameter, value);
3601     }
3605 void
3606 ns_initialize_display_info (struct ns_display_info *dpyinfo)
3607 /* --------------------------------------------------------------------------
3608       Initialize global info and storage for display.
3609    -------------------------------------------------------------------------- */
3611     NSScreen *screen = [NSScreen mainScreen];
3612     NSWindowDepth depth = [screen depth];
3614     dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
3615     dpyinfo->resy = 72.27;
3616     dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
3617                                                   NSColorSpaceFromDepth (depth)]
3618                 && ![NSCalibratedWhiteColorSpace isEqualToString:
3619                                                  NSColorSpaceFromDepth (depth)];
3620     dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
3621     dpyinfo->image_cache = make_image_cache ();
3622     dpyinfo->color_table
3623       = (struct ns_color_table *)xmalloc (sizeof (struct ns_color_table));
3624     dpyinfo->color_table->colors = NULL;
3625     dpyinfo->root_window = 42; /* a placeholder.. */
3627     dpyinfo->mouse_face_mouse_frame = NULL;
3628     dpyinfo->mouse_face_deferred_gc = 0;
3629     dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
3630     dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
3631     dpyinfo->mouse_face_face_id = DEFAULT_FACE_ID;
3632     dpyinfo->mouse_face_window = dpyinfo->mouse_face_overlay = Qnil;
3633     dpyinfo->mouse_face_hidden = 0;
3635     dpyinfo->mouse_face_mouse_x = dpyinfo->mouse_face_mouse_y = 0;
3636     dpyinfo->mouse_face_defer = 0;
3638     dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
3640     dpyinfo->n_fonts = 0;
3641     dpyinfo->smallest_font_height = 1;
3642     dpyinfo->smallest_char_width = 1;
3646 /* This and next define (many of the) public functions in this file. */
3647 /* x_... are generic versions in xdisp.c that we, and other terms, get away
3648          with using despite presence in the "system dependent" redisplay
3649          interface.  In addition, many of the ns_ methods have code that is
3650          shared with all terms, indicating need for further refactoring. */
3651 extern frame_parm_handler ns_frame_parm_handlers[];
3652 static struct redisplay_interface ns_redisplay_interface =
3654   ns_frame_parm_handlers,
3655   x_produce_glyphs,
3656   x_write_glyphs,
3657   x_insert_glyphs,
3658   x_clear_end_of_line,
3659   ns_scroll_run,
3660   ns_after_update_window_line,
3661   ns_update_window_begin,
3662   ns_update_window_end,
3663   x_cursor_to,
3664   ns_flush,
3665   0, /* flush_display_optional */
3666   x_clear_window_mouse_face,
3667   x_get_glyph_overhangs,
3668   x_fix_overlapping_area,
3669   ns_draw_fringe_bitmap,
3670   0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
3671   0, /* destroy_fringe_bitmap */
3672   ns_compute_glyph_string_overhangs,
3673   ns_draw_glyph_string, /* interface to nsfont.m */
3674   ns_define_frame_cursor,
3675   ns_clear_frame_area,
3676   ns_draw_window_cursor,
3677   ns_draw_vertical_window_border,
3678   ns_shift_glyphs_for_insert
3682 static void
3683 ns_delete_display (struct ns_display_info *dpyinfo)
3685   /* TODO... */
3689 /* This function is called when the last frame on a display is deleted. */
3690 static void
3691 ns_delete_terminal (struct terminal *terminal)
3693   struct ns_display_info *dpyinfo = terminal->display_info.ns;
3694   int i;
3696   /* Protect against recursive calls.  delete_frame in
3697      delete_terminal calls us back when it deletes our last frame.  */
3698   if (!terminal->name)
3699     return;
3701   BLOCK_INPUT;
3703   x_destroy_all_bitmaps (dpyinfo);
3704   ns_delete_display (dpyinfo);
3705   UNBLOCK_INPUT;
3709 static struct terminal *
3710 ns_create_terminal (struct ns_display_info *dpyinfo)
3711 /* --------------------------------------------------------------------------
3712       Set up use of NS before we make the first connection.
3713    -------------------------------------------------------------------------- */
3715   struct terminal *terminal;
3717   NSTRACE (ns_create_terminal);
3719   terminal = create_terminal ();
3721   terminal->type = output_ns;
3722   terminal->display_info.ns = dpyinfo;
3723   dpyinfo->terminal = terminal;
3725   terminal->rif = &ns_redisplay_interface;
3727   terminal->clear_frame_hook = ns_clear_frame;
3728   terminal->ins_del_lines_hook = 0; /* XXX vestigial? */
3729   terminal->delete_glyphs_hook = 0; /* XXX vestigial? */
3730   terminal->ring_bell_hook = ns_ring_bell;
3731   terminal->reset_terminal_modes_hook = ns_reset_terminal_modes;
3732   terminal->set_terminal_modes_hook = ns_set_terminal_modes;
3733   terminal->update_begin_hook = ns_update_begin;
3734   terminal->update_end_hook = ns_update_end;
3735   terminal->set_terminal_window_hook = NULL; /* XXX vestigial? */
3736   terminal->read_socket_hook = ns_read_socket;
3737   terminal->frame_up_to_date_hook = ns_frame_up_to_date;
3738   terminal->mouse_position_hook = ns_mouse_position;
3739   terminal->frame_rehighlight_hook = ns_frame_rehighlight;
3740   terminal->frame_raise_lower_hook = ns_frame_raise_lower;
3742   terminal->fullscreen_hook = 0; /* see XTfullscreen_hook */
3744   terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
3745   terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
3746   terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
3747   terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
3749   terminal->delete_frame_hook = x_destroy_window;
3750   terminal->delete_terminal_hook = ns_delete_terminal;
3752   terminal->scroll_region_ok = 1;
3753   terminal->char_ins_del_ok = 1;
3754   terminal->line_ins_del_ok = 1;
3755   terminal->fast_clear_end_of_line = 1;
3756   terminal->memory_below_frame = 0;
3758   return terminal;
3762 struct ns_display_info *
3763 ns_term_init (Lisp_Object display_name)
3764 /* --------------------------------------------------------------------------
3765      Start the Application and get things rolling.
3766    -------------------------------------------------------------------------- */
3768   struct terminal *terminal;
3769   struct ns_display_info *dpyinfo;
3770   static int ns_initialized = 0;
3771   Lisp_Object tmp;
3773   NSTRACE (ns_term_init);
3775   /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
3776   /*GSDebugAllocationActive (YES); */
3777   BLOCK_INPUT;
3778   handling_signal = 0;
3780   if (!ns_initialized)
3781     {
3782       baud_rate = 38400;
3783       Fset_input_interrupt_mode (Qnil);
3784       ns_initialized = 1;
3785     }
3787   ns_pending_files = [[NSMutableArray alloc] init];
3788   ns_pending_service_names = [[NSMutableArray alloc] init];
3789   ns_pending_service_args = [[NSMutableArray alloc] init];
3791   /* Start app and create the main menu, window, view.
3792      Needs to be here because ns_initialize_display_info () uses AppKit classes.
3793      The view will then ask the NSApp to stop and return to Emacs. */
3794   [EmacsApp sharedApplication];
3795   if (NSApp == nil)
3796     return NULL;
3797   [NSApp setDelegate: NSApp];
3799   /* debugging: log all notifications */
3800   /*   [[NSNotificationCenter defaultCenter] addObserver: NSApp
3801                                          selector: @selector (logNotification:)
3802                                              name: nil object: nil]; */
3804   dpyinfo = (struct ns_display_info *)xmalloc (sizeof (struct ns_display_info));
3805   bzero (dpyinfo, sizeof (struct ns_display_info));
3807   ns_initialize_display_info (dpyinfo);
3808   terminal = ns_create_terminal (dpyinfo);
3810   terminal->kboard = (KBOARD *) xmalloc (sizeof (KBOARD));
3811   init_kboard (terminal->kboard);
3812   terminal->kboard->Vwindow_system = Qns;
3813   terminal->kboard->next_kboard = all_kboards;
3814   all_kboards = terminal->kboard;
3815   /* Don't let the initial kboard remain current longer than necessary.
3816      That would cause problems if a file loaded on startup tries to
3817      prompt in the mini-buffer.  */
3818   if (current_kboard == initial_kboard)
3819     current_kboard = terminal->kboard;
3820   terminal->kboard->reference_count++;
3822   dpyinfo->next = x_display_list;
3823   x_display_list = dpyinfo;
3825   /* Put it on ns_display_name_list */
3826   ns_display_name_list = Fcons (Fcons (display_name, Qnil),
3827                                 ns_display_name_list);
3828   dpyinfo->name_list_element = XCAR (ns_display_name_list);
3830   /* Set the name of the terminal. */
3831   terminal->name = (char *) xmalloc (SBYTES (display_name) + 1);
3832   strncpy (terminal->name, SDATA (display_name), SBYTES (display_name));
3833   terminal->name[SBYTES (display_name)] = 0;
3835   UNBLOCK_INPUT; 
3837   /* Read various user defaults. */
3838   ns_set_default_prefs ();
3839   if (!ns_no_defaults)
3840     {
3841       ns_default ("AlternateModifier", &ns_alternate_modifier,
3842                  Qnil, Qnil, NO, YES);
3843       if (NILP (ns_alternate_modifier))
3844         ns_alternate_modifier = Qmeta;
3845       ns_default ("CommandModifier", &ns_command_modifier,
3846                  Qnil, Qnil, NO, YES);
3847       if (NILP (ns_command_modifier))
3848         ns_command_modifier = Qsuper;
3849       ns_default ("ControlModifier", &ns_control_modifier,
3850                  Qnil, Qnil, NO, YES);
3851       if (NILP (ns_control_modifier))
3852         ns_control_modifier = Qcontrol;
3853       ns_default ("FunctionModifier", &ns_function_modifier,
3854                  Qnil, Qnil, NO, YES);
3855       if (NILP (ns_function_modifier))
3856         ns_function_modifier = Qnone;
3857       ns_default ("ExpandSpace", &ns_expand_space,
3858                  make_float (0.5), make_float (0.0), YES, NO);
3859       ns_default ("GSFontAntiAlias", &ns_antialias_text,
3860                  Qt, Qnil, NO, NO);
3861       tmp = Qnil;
3862       ns_default ("AppleAntiAliasingThreshold", &tmp,
3863                  make_float (10.0), make_float (6.0), YES, NO);
3864       ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
3865       ns_default ("UseQuickdrawSmoothing", &ns_use_qd_smoothing,
3866                  Qt, Qnil, NO, NO);
3867       ns_default ("UseSystemHighlightColor", &ns_use_system_highlight_color,
3868                  Qt, Qnil, NO, NO);
3869       ns_default ("ConfirmQuit", &ns_confirm_quit,
3870                  Qt, Qnil, NO, NO);
3871     }
3873   if (EQ (ns_use_system_highlight_color, Qt))
3874     {
3875       ns_selection_color = [[NSUserDefaults standardUserDefaults]
3876                                stringForKey: @"AppleHighlightColor"];
3877       if (ns_selection_color == nil)
3878         ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
3879     }
3880   else
3881     ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
3883   {
3884     NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
3886     if ( cl == nil )
3887       {
3888         Lisp_Object color_file, color_map, color;
3889         int r,g,b;
3890         unsigned long c;
3891         char *name;
3893         color_file = Fexpand_file_name (build_string ("rgb.txt"),
3894                          Fsymbol_value (intern ("data-directory")));
3895         if (NILP (Ffile_readable_p (color_file)))
3896           fatal ("Could not find %s.\n", SDATA (color_file));
3898         color_map = Fx_load_color_file (color_file);
3899         if (NILP (color_map))
3900           fatal ("Could not read %s.\n", SDATA (color_file));
3902         cl = [[NSColorList alloc] initWithName: @"Emacs"];
3903         for ( ; CONSP (color_map); color_map = XCDR (color_map))
3904           {
3905             color = XCAR (color_map);
3906             name = SDATA (XCAR (color));
3907             c = XINT (XCDR (color));
3908             [cl setColor:
3909                   [NSColor colorWithCalibratedRed: RED_FROM_ULONG (c) / 255.0
3910                                             green: GREEN_FROM_ULONG (c) / 255.0
3911                                              blue: BLUE_FROM_ULONG (c) / 255.0
3912                                             alpha: 1.0]
3913                   forKey: [NSString stringWithUTF8String: name]];
3914           }
3915         [cl writeToFile: nil];
3916       }
3917   }
3919   {
3920     char c[128];
3921 #ifdef NS_IMPL_GNUSTEP
3922     strncpy (c, gnustep_base_version, sizeof (c));
3923 #else
3924     /*PSnextrelease (128, c); */
3925     snprintf (c, sizeof (c), "%g", NSAppKitVersionNumber);
3926 #endif
3927     Vwindow_system_version = build_string (c);
3928   }
3930   delete_keyboard_wait_descriptor (0);
3932 /* Set up OS X app menu */
3933 #ifdef NS_IMPL_COCOA
3934   {
3935     NSMenu *appMenu;
3936     NSMenuItem *item;
3937     /* set up the application menu */
3938     svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
3939     [svcsMenu setAutoenablesItems: NO];
3940     appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
3941     [appMenu setAutoenablesItems: NO];
3942     mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
3943     dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
3945     [appMenu insertItemWithTitle: @"About Emacs"
3946                           action: @selector (orderFrontStandardAboutPanel:)
3947                    keyEquivalent: @""
3948                          atIndex: 0];
3949     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
3950     [appMenu insertItemWithTitle: @"Preferences..."
3951                           action: @selector (showPreferencesWindow:)
3952                    keyEquivalent: @","
3953                          atIndex: 2];
3954     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
3955     item = [appMenu insertItemWithTitle: @"Services"
3956                                  action: @selector (menuDown:)
3957                           keyEquivalent: @""
3958                                 atIndex: 4];
3959     [appMenu setSubmenu: svcsMenu forItem: item];
3960 /*    [svcsMenu setSupercell: item]; */
3961     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
3962     [appMenu insertItemWithTitle: @"Hide Emacs"
3963                           action: @selector (hide:)
3964                    keyEquivalent: @"h"
3965                          atIndex: 6];
3966     item =  [appMenu insertItemWithTitle: @"Hide Others"
3967                           action: @selector (hideOtherApplications:)
3968                    keyEquivalent: @"h"
3969                          atIndex: 7];
3970     [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
3971     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
3972     [appMenu insertItemWithTitle: @"Quit Emacs"
3973                           action: @selector (terminate:)
3974                    keyEquivalent: @"q"
3975                          atIndex: 9];
3977     item = [mainMenu insertItemWithTitle: @"Emacs"
3978                                   action: @selector (menuDown:)
3979                            keyEquivalent: @""
3980                                  atIndex: 0];
3981     [mainMenu setSubmenu: appMenu forItem: item];
3982     [dockMenu insertItemWithTitle: @"New Frame"
3983                            action: @selector (newFrame:)
3984                     keyEquivalent: @""
3985                           atIndex: 0];
3987     [NSApp setMainMenu: mainMenu];
3988     [NSApp setAppleMenu: appMenu];
3989     [NSApp setServicesMenu: svcsMenu];
3990     /* Needed at least on Cocoa, to get dock menu to show windows */
3991     [NSApp setWindowsMenu: [[NSMenu alloc] init]];
3992   }
3993 #endif /* MAC OS X menu setup */
3995   [NSApp run];
3997   return dpyinfo;
4001 extern Lisp_Object Vauto_save_list_file_name;
4002 void
4003 ns_term_shutdown (int sig)
4005   /* code not reached in emacs.c after this is called by shut_down_emacs: */
4006   if (STRINGP (Vauto_save_list_file_name))
4007     unlink (SDATA (Vauto_save_list_file_name));
4009   if (sig == 0 || sig == SIGTERM)
4010     {
4011       ns_shutdown_properly = YES;
4012       [NSApp terminate: NSApp];
4013     }
4014   else // force a stack trace to happen
4015     {
4016       abort();
4017     }
4021 /* ==========================================================================
4023     EmacsApp implementation
4025    ========================================================================== */
4028 @implementation EmacsApp
4030 - (void)logNotification: (NSNotification *)notification
4032   const char *name = [[notification name] UTF8String];
4033   if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4034       && !strstr (name, "WindowNumber"))
4035     NSLog (@"notification: '%@'", [notification name]);
4039 - (void)sendEvent: (NSEvent *)theEvent
4040 /* --------------------------------------------------------------------------
4041      Called when NSApp is running for each event received.  Used to stop
4042      the loop when we choose, since there's no way to just run one iteration.
4043    -------------------------------------------------------------------------- */
4045   int type = [theEvent type];
4046   NSWindow *window = [theEvent window];
4047 /*  NSTRACE (sendEvent); */
4048 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4050   if (type == NSCursorUpdate && window == nil)
4051     {
4052       fprintf (stderr, "Dropping external cursor update event.\n");
4053       return;
4054     }
4056 #ifdef NS_IMPL_COCOA
4057   /* pass mouse down in resize handle and subsequent drags directly to
4058      EmacsWindow so we can generate continuous redisplays */
4059   if (ns_in_resize)
4060     {
4061       if (type == NSLeftMouseDragged)
4062         {
4063           [window mouseDragged: theEvent];
4064           return;
4065         }
4066       else if (type == NSLeftMouseUp)
4067         {
4068           [window mouseUp: theEvent];
4069           return;
4070         }
4071     }
4072   else if (type == NSLeftMouseDown)
4073     {
4074       NSRect r = ns_resize_handle_rect (window);
4075       if (NSPointInRect ([theEvent locationInWindow], r))
4076         {
4077           ns_in_resize = YES;
4078           [window mouseDown: theEvent];
4079           return;
4080         }
4081     }
4082 #endif
4084   if (type == NSApplicationDefined)
4085     {
4086       /* Events posted by ns_send_appdefined interrupt the run loop here.
4087          But, if a modal window is up, an appdefined can still come through,
4088          (e.g., from a makeKeyWindow event) but stopping self also stops the
4089          modal loop. Just defer it until later. */
4090       if ([NSApp modalWindow] == nil)
4091         {
4092           last_appdefined_event = theEvent;
4093           [self stop: self];
4094         }
4095       else
4096         {
4097           send_appdefined = YES;
4098         }
4099     }
4101   [super sendEvent: theEvent];
4105 - (void)showPreferencesWindow: (id)sender
4107   if (prefsController == nil)
4108     prefsController = [[EmacsPrefsController alloc] init];
4109   [prefsController showForFrame: SELECTED_FRAME ()];
4113 - (void)newFrame: (id)sender
4115   struct frame *emacsframe = SELECTED_FRAME ();
4116   NSEvent *theEvent = [NSApp currentEvent];
4118   if (!emacs_event)
4119     return;
4120   emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4121   emacs_event->code = KEY_NS_NEW_FRAME;
4122   emacs_event->modifiers = 0;
4123   EV_TRAILER (theEvent);
4127 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4128 - (BOOL) openFile: (NSString *)fileName
4130   struct frame *emacsframe = SELECTED_FRAME ();
4131   NSEvent *theEvent = [NSApp currentEvent];
4133   if (!emacs_event)
4134     return NO;
4136   emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4137   emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4138   ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4139   ns_input_line = Qnil; /* can be start or cons start,end */
4140   emacs_event->modifiers =0;
4141   EV_TRAILER (theEvent);
4143   return YES;
4147 /* **************************************************************************
4149       EmacsApp delegate implementation
4151    ************************************************************************** */
4153 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4154 /* --------------------------------------------------------------------------
4155      When application is loaded, terminate event loop in ns_term_init
4156    -------------------------------------------------------------------------- */
4158   NSTRACE (applicationDidFinishLaunching);
4159   [NSApp setServicesProvider: NSApp];
4160   ns_send_appdefined (-2);
4164 /* Termination sequences (ns_shutdown_properly):
4165     C-x C-c:
4166     Cmd-Q:
4167     MenuBar | File | Exit:
4168         ns_term_shutdown: 0
4169         -terminate: 1
4170         -appShouldTerminate: 1
4172     Select Quit from App menubar:
4173         received -terminate: 0
4174         ns_term_shutdown: 0
4175         -terminate: 1
4176         -appShouldTerminate: 1
4178     Select Quit from Dock menu:
4179     Logout attempt:
4180         -appShouldTerminate: 0
4181           Cancel -> Nothing else
4182           Accept ->
4183             -terminate: 0
4184             ns_term_shutdown: 0
4185             -terminate: 1
4186             -appShouldTerminate: 1
4189 - (void) terminate: (id)sender
4191   if (ns_shutdown_properly)
4192     [super terminate: sender];
4193   else
4194     {
4195       struct frame *emacsframe = SELECTED_FRAME ();
4197       if (!emacs_event)
4198         return;
4200       ns_shutdown_properly = YES;
4201       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4202       emacs_event->code = KEY_NS_POWER_OFF;
4203       EV_TRAILER ((id)nil);
4204     }
4208 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4210   int ret;
4212   if (ns_shutdown_properly || NILP (ns_confirm_quit))
4213     return NSTerminateNow;
4215     ret = NSRunAlertPanel([[NSProcessInfo processInfo] processName],
4216                           [NSString stringWithUTF8String:"Exit requested.  Would you like to Save Buffers and Exit, or Cancel the request?"],
4217                           @"Save Buffers and Exit", @"Cancel", nil);
4219     if (ret == NSAlertDefaultReturn)
4220         return NSTerminateNow;
4221     else if (ret == NSAlertAlternateReturn)
4222         return NSTerminateCancel;
4223     return NSTerminateNow;  /* just in case */
4227 /*   Notification from the Workspace to open a file */
4228 - (BOOL)application: sender openFile: (NSString *)file
4230   [ns_pending_files addObject: file];
4231   return YES;
4235 /*   Open a file as a temporary file */
4236 - (BOOL)application: sender openTempFile: (NSString *)file
4238   [ns_pending_files addObject: file];
4239   return YES;
4243 /*   Notification from the Workspace to open a file noninteractively (?) */
4244 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4246   [ns_pending_files addObject: file];
4247   return YES;
4251 /*   Notification from the Workspace to open multiple files */
4252 - (void)application: sender openFiles: (NSArray *)fileList
4254   NSEnumerator *files = [fileList objectEnumerator];
4255   NSString *file;
4256   while ((file = [files nextObject]) != nil)
4257     [ns_pending_files addObject: file];
4259 /* TODO: when GNUstep implements this (and we require that version of
4260          GNUstep), remove. */
4261 #ifndef NS_IMPL_GNUSTEP
4262   [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4263 #endif /* !NS_IMPL_GNUSTEP */
4268 /* Handle dock menu requests.  */
4269 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4271   return dockMenu;
4275 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4276 - (void)applicationWillBecomeActive: (NSNotification *)notification
4278   //ns_app_active=YES;
4280 - (void)applicationDidBecomeActive: (NSNotification *)notification
4282   //ns_app_active=YES;
4284 - (void)applicationDidResignActive: (NSNotification *)notification
4286   //ns_app_active=NO;
4287   ns_send_appdefined (-1);
4292 /* ==========================================================================
4294     EmacsApp aux handlers for managing event loop
4296    ========================================================================== */
4299 - (void)timeout_handler: (NSTimer *)timedEntry
4300 /* --------------------------------------------------------------------------
4301      The timeout specified to ns_select has passed.
4302    -------------------------------------------------------------------------- */
4304   /*NSTRACE (timeout_handler); */
4305   ns_send_appdefined (-2);
4308 extern void update_window_cursor (struct window *w, int on);
4310 - (void)fd_handler: (NSTimer *) fdEntry
4311 /* --------------------------------------------------------------------------
4312      Check data waiting on file descriptors and terminate if so
4313    -------------------------------------------------------------------------- */
4315   int result;
4316   /* NSTRACE (fd_handler); */
4318   if (select_nfds == 0)
4319     return;
4321   memcpy (&t_readfds, &select_readfds, sizeof (fd_set));
4323   select_timeout.tv_sec = select_timeout.tv_usec = 0;
4324   result = select (select_nfds, &t_readfds, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
4325                   &select_timeout);
4326   if (result)
4327     {
4328       memcpy (&select_readfds, &t_readfds, sizeof (fd_set));
4329       ns_send_appdefined (result);
4330     }
4335 /* ==========================================================================
4337     Service provision
4339    ========================================================================== */
4341 /* called from system: queue for next pass through event loop */
4342 - (void)requestService: (NSPasteboard *)pboard
4343               userData: (NSString *)userData
4344                  error: (NSString **)error
4346   [ns_pending_service_names addObject: userData];
4347   [ns_pending_service_args addObject: [NSString stringWithUTF8String:
4348       SDATA (ns_string_from_pasteboard (pboard))]];
4352 /* called from ns_read_socket to clear queue */
4353 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
4355   struct frame *emacsframe = SELECTED_FRAME ();
4356   NSEvent *theEvent = [NSApp currentEvent];
4358   if (!emacs_event)
4359     return NO;
4361   emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4362   emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
4363   ns_input_spi_name = build_string ([name UTF8String]);
4364   ns_input_spi_arg = build_string ([arg UTF8String]);
4365   emacs_event->modifiers = EV_MODIFIERS (theEvent);
4366   EV_TRAILER (theEvent);
4368   return YES;
4372 @end  /* EmacsApp */
4376 /* ==========================================================================
4378     EmacsView implementation
4380    ========================================================================== */
4383 @implementation EmacsView
4385 /* needed to inform when window closed from LISP */
4386 - (void) setWindowClosing: (BOOL)closing
4388   windowClosing = closing;
4392 - (void)dealloc
4394   NSTRACE (EmacsView_dealloc);
4395   [toolbar release];
4396   [super dealloc];
4400 /* called on font panel selection */
4401 - (void)changeFont: (id)sender
4403   NSEvent *e =[[self window] currentEvent];
4404   struct face *face =FRAME_DEFAULT_FACE (emacsframe);
4405   id newFont;
4406   float size;
4408   NSTRACE (changeFont);
4409   if (!emacs_event)
4410     return;
4412   if (newFont = [sender convertFont:
4413                            ((struct nsfont_info *)face->font)->nsfont])
4414     {
4415       SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
4417       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4418       emacs_event->modifiers = 0;
4419       emacs_event->code = KEY_NS_CHANGE_FONT;
4421       size = [newFont pointSize];
4422       ns_input_fontsize = make_number (lrint (size));
4423       ns_input_font = build_string ([[newFont familyName] UTF8String]);
4424       EV_TRAILER (e);
4425     }
4429 - (BOOL)acceptsFirstResponder
4431   NSTRACE (acceptsFirstResponder);
4432   return YES;
4436 - (void)resetCursorRects
4438   NSRect visible = [self visibleRect];
4439   NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
4440   NSTRACE (resetCursorRects);
4442   if (currentCursor == nil)
4443     currentCursor = [NSCursor arrowCursor];
4445   if (!NSIsEmptyRect (visible))
4446     [self addCursorRect: visible cursor: currentCursor];
4447   [currentCursor setOnMouseEntered: YES];
4452 /*****************************************************************************/
4453 /* Keyboard handling. */
4454 #define NS_KEYLOG 0
4456 - (void)keyDown: (NSEvent *)theEvent
4458   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4459   int code;
4460   unsigned fnKeysym = 0;
4461   int flags;
4462   static NSMutableArray *nsEvArray;
4463   static BOOL firstTime = YES;
4465   NSTRACE (keyDown);
4467   /* Rhapsody and OS X give up and down events for the arrow keys */
4468   if (ns_fake_keydown == YES)
4469     ns_fake_keydown = NO;
4470   else if ([theEvent type] != NSKeyDown)
4471     return;
4473   if (!emacs_event)
4474     return;
4476  if (![[self window] isKeyWindow])
4477    {
4478      /* XXX: There is an occasional condition in which, when Emacs display
4479          updates a different frame from the current one, and temporarily
4480          selects it, then processes some interrupt-driven input
4481          (dispnew.c:3878), OS will send the event to the correct NSWindow, but
4482          for some reason that window has its first responder set to the NSView
4483          most recently updated (I guess), which is not the correct one. */
4484      if ([[theEvent window] isKindOfClass: [EmacsWindow class]])
4485          [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
4486      return;
4487    }
4489   if (nsEvArray == nil)
4490     nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
4492   [NSCursor setHiddenUntilMouseMoves: YES];
4494   if (dpyinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
4495     {
4496       clear_mouse_face (dpyinfo);
4497       dpyinfo->mouse_face_hidden = 1;
4498     }
4500   if (!processingCompose)
4501     {
4502       code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
4503         0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
4504       /* (Carbon way: [theEvent keyCode]) */
4506       /* is it a "function key"? */
4507       fnKeysym = ns_convert_key (code);
4508       if (fnKeysym)
4509         {
4510           /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
4511              because Emacs treats Delete and KP-Delete same (in simple.el). */
4512           if (fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
4513             code = 0xFF08; /* backspace */
4514           else
4515             code = fnKeysym;
4516         }
4518       /* are there modifiers? */
4519       emacs_event->modifiers = 0;
4520       flags = [theEvent modifierFlags];
4522       if (flags & NSHelpKeyMask)
4523           emacs_event->modifiers |= hyper_modifier;
4525       if (flags & NSShiftKeyMask)
4526         emacs_event->modifiers |= shift_modifier;
4528       if (flags & NSCommandKeyMask)
4529         {
4530           emacs_event->modifiers |= parse_solitary_modifier (ns_command_modifier);
4531           /* if super (default), take input manager's word so things like
4532              dvorak / qwerty layout work */
4533           if (EQ (ns_command_modifier, Qsuper)
4534               && !fnKeysym
4535               && [[theEvent characters] length] != 0)
4536             {
4537               /* XXX: the code we get will be unshifted, so if we have
4538                  a shift modifier, must convert ourselves */
4539               if (!(flags & NSShiftKeyMask))
4540                 code = [[theEvent characters] characterAtIndex: 0];
4541 #if 0
4542               /* this is ugly and also requires linking w/Carbon framework
4543                  (for LMGetKbdType) so for now leave this rare (?) case
4544                  undealt with.. in future look into CGEvent methods */
4545               else
4546                 {
4547                   long smv = GetScriptManagerVariable (smKeyScript);
4548                   Handle uchrHandle = GetResource
4549                     ('uchr', GetScriptVariable (smv, smScriptKeys));
4550                   UInt32 dummy = 0;
4551                   UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
4552                                  [[theEvent characters] characterAtIndex: 0],
4553                                  kUCKeyActionDisplay,
4554                                  (flags & ~NSCommandKeyMask) >> 8,
4555                                  LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
4556                                  &dummy, 1, &dummy, &code);
4557                   code &= 0xFF;
4558                 }
4559 #endif
4560             }
4561         }
4563       if (flags & NSControlKeyMask)
4564           emacs_event->modifiers |=
4565             parse_solitary_modifier (ns_control_modifier);
4567       if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
4568           emacs_event->modifiers |=
4569             parse_solitary_modifier (ns_function_modifier);
4571       if (flags & NSAlternateKeyMask) /* default = meta */
4572         {
4573           if ((NILP (ns_alternate_modifier) || EQ (ns_alternate_modifier, Qnone))
4574               && !fnKeysym)
4575             {   /* accept pre-interp alt comb */
4576               if ([[theEvent characters] length] > 0)
4577                 code = [[theEvent characters] characterAtIndex: 0];
4578               /*HACK: clear lone shift modifier to stop next if from firing */
4579               if (emacs_event->modifiers == shift_modifier)
4580                 emacs_event->modifiers = 0;
4581             }
4582           else
4583               emacs_event->modifiers |=
4584                 parse_solitary_modifier (ns_alternate_modifier);
4585         }
4587   if (NS_KEYLOG)
4588     fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
4589              code, fnKeysym, flags, emacs_event->modifiers);
4591       /* if it was a function key or had modifiers, pass it directly to emacs */
4592       if (fnKeysym || (emacs_event->modifiers
4593                        && [[theEvent charactersIgnoringModifiers] length] > 0))
4594 /*[[theEvent characters] length] */
4595         {
4596           emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4597           if (code < 0x20)
4598             code |= (1<<28)|(3<<16);
4599           else if (code == 0x7f)
4600             code |= (1<<28)|(3<<16);
4601           else if (!fnKeysym)
4602             emacs_event->kind = code > 0xFF
4603               ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4605           emacs_event->code = code;
4606           EV_TRAILER (theEvent);
4607           return;
4608         }
4609     }
4611   /* if we get here we should send the key for input manager processing */
4612   if (firstTime && [[NSInputManager currentInputManager]
4613                      wantsToDelayTextChangeNotifications] == NO)
4614     fprintf (stderr,
4615           "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
4616   firstTime = NO;
4618   if (NS_KEYLOG && !processingCompose)
4619     fprintf (stderr, "keyDown: Begin compose sequence.\n");
4621   processingCompose = YES;
4622   [nsEvArray addObject: theEvent];
4623   [self interpretKeyEvents: nsEvArray];
4624   [nsEvArray removeObject: theEvent];
4628 #ifdef NS_IMPL_COCOA
4629 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
4630    decided not to send key-down for.
4631    See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
4632    If it matches one of these, send it on to keyDown. */
4633 -(void)keyUp: (NSEvent *)theEvent
4635   int flags = [theEvent modifierFlags];
4636   int code = [theEvent keyCode];
4637   if (code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
4638     {
4639       if (NS_KEYLOG)
4640         fprintf (stderr, "keyUp: passed test");
4641       ns_fake_keydown = YES;
4642       [self keyDown: theEvent];
4643     }
4645 #endif
4648 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
4651 /* <NSTextInput>: called when done composing;
4652    NOTE: also called when we delete over working text, followed immed.
4653          by doCommandBySelector: deleteBackward: */
4654 - (void)insertText: (id)aString
4656   int code;
4657   int len = [(NSString *)aString length];
4658   int i;
4660   if (NS_KEYLOG)
4661     NSLog (@"insertText '%@'\tlen = %d", aString, len);
4662   processingCompose = NO;
4664   if (!emacs_event)
4665     return;
4667   /* first, clear any working text */
4668   if (workingText != nil)
4669     [self deleteWorkingText];
4671   /* now insert the string as keystrokes */
4672   for (i =0; i<len; i++)
4673     {
4674       code = [aString characterAtIndex: i];
4675       /* TODO: still need this? */
4676       if (code == 0x2DC)
4677         code = '~'; /* 0x7E */
4678       emacs_event->modifiers = 0;
4679       emacs_event->kind
4680         = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4681       emacs_event->code = code;
4682       EV_TRAILER ((id)nil);
4683     }
4687 /* <NSTextInput>: inserts display of composing characters */
4688 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
4690   NSString *str = [aString respondsToSelector: @selector (string)] ?
4691     [aString string] : aString;
4692   if (NS_KEYLOG)
4693     NSLog (@"setMarkedText '%@' len =%d range %d from %d", str, [str length],
4694            selRange.length, selRange.location);
4696   if (workingText != nil)
4697     [self deleteWorkingText];
4698   if ([str length] == 0)
4699     return;
4701   if (!emacs_event)
4702     return;
4704   processingCompose = YES;
4705   workingText = [str copy];
4706   ns_working_text = build_string ([workingText UTF8String]);
4708   emacs_event->kind = NS_TEXT_EVENT;
4709   emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
4710   EV_TRAILER ((id)nil);
4714 /* delete display of composing characters [not in <NSTextInput>] */
4715 - (void)deleteWorkingText
4717   if (workingText == nil)
4718     return;
4719   if (NS_KEYLOG)
4720     NSLog(@"deleteWorkingText len =%d\n", [workingText length]);
4721   [workingText release];
4722   workingText = nil;
4723   processingCompose = NO;
4725   if (!emacs_event)
4726     return;
4728   emacs_event->kind = NS_TEXT_EVENT;
4729   emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
4730   EV_TRAILER ((id)nil);
4734 - (BOOL)hasMarkedText
4736   return workingText != nil;
4740 - (NSRange)markedRange
4742   NSRange rng = workingText != nil
4743     ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
4744   if (NS_KEYLOG)
4745     NSLog (@"markedRange request");
4746   return rng;
4750 - (void)unmarkText
4752   if (NS_KEYLOG)
4753     NSLog (@"unmark (accept) text");
4754   [self deleteWorkingText];
4755   processingCompose = NO;
4759 /* used to position char selection windows, etc. */
4760 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
4762   NSRect rect;
4763   NSPoint pt;
4764   struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
4765   if (NS_KEYLOG)
4766     NSLog (@"firstRectForCharRange request");
4768   rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
4769   rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
4770   pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
4771   pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
4772                                        +FRAME_LINE_HEIGHT (emacsframe));
4774   pt = [self convertPoint: pt toView: nil];
4775   pt = [[self window] convertBaseToScreen: pt];
4776   rect.origin = pt;
4777   return rect;
4781 - (NSInteger)conversationIdentifier
4783   return (NSInteger)self;
4787 - (void)doCommandBySelector: (SEL)aSelector
4789   if (NS_KEYLOG)
4790     NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
4792   if (aSelector == @selector (deleteBackward:))
4793     {
4794       /* happens when user backspaces over an ongoing composition:
4795          throw a 'delete' into the event queue */
4796       if (!emacs_event)
4797         return;
4798       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4799       emacs_event->code = 0xFF08;
4800       EV_TRAILER ((id)nil);
4801     }
4804 - (NSArray *)validAttributesForMarkedText
4806   static NSArray *arr = nil;
4807   if (arr == nil) arr = [NSArray new];
4808  /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
4809   return arr;
4812 - (NSRange)selectedRange
4814   if (NS_KEYLOG)
4815     NSLog (@"selectedRange request");
4816   return NSMakeRange (NSNotFound, 0);
4819 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
4821   if (NS_KEYLOG)
4822     NSLog (@"characterIndexForPoint request");
4823   return 0;
4826 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
4828   static NSAttributedString *str = nil;
4829   if (str == nil) str = [NSAttributedString new];
4830   if (NS_KEYLOG)
4831     NSLog (@"attributedSubstringFromRange request");
4832   return str;
4835 /* End <NSTextInput> impl. */
4836 /*****************************************************************************/
4839 /* This is what happens when the user presses a mouse button.  */
4840 - (void)mouseDown: (NSEvent *)theEvent
4842   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
4843   Lisp_Object window;
4845   NSTRACE (mouseDown);
4847   [self deleteWorkingText];
4849   if (!emacs_event)
4850     return;
4852   last_mouse_frame = emacsframe;
4853   /* appears to be needed to prevent spurious movement events generated on
4854      button clicks */
4855   last_mouse_frame->mouse_moved = 0;
4857   if ([theEvent type] == NSScrollWheel)
4858     {
4859       float delta = [theEvent deltaY];
4860       /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
4861       if (delta == 0)
4862         return;
4863       emacs_event->kind = WHEEL_EVENT;
4864       emacs_event->code = 0;
4865       emacs_event->modifiers = EV_MODIFIERS (theEvent) |
4866         ((delta > 0) ? up_modifier : down_modifier);
4867     }
4868   else
4869     {
4870       emacs_event->kind = MOUSE_CLICK_EVENT;
4871       emacs_event->code = EV_BUTTON (theEvent);
4872       emacs_event->modifiers = EV_MODIFIERS (theEvent)
4873                              | EV_UDMODIFIERS (theEvent);
4874     }
4875   XSETINT (emacs_event->x, lrint (p.x));
4876   XSETINT (emacs_event->y, lrint (p.y));
4877   EV_TRAILER (theEvent);
4881 - (void)rightMouseDown: (NSEvent *)theEvent
4883   NSTRACE (rightMouseDown);
4884   [self mouseDown: theEvent];
4888 - (void)otherMouseDown: (NSEvent *)theEvent
4890   NSTRACE (otherMouseDown);
4891   [self mouseDown: theEvent];
4895 - (void)mouseUp: (NSEvent *)theEvent
4897   NSTRACE (mouseUp);
4898   [self mouseDown: theEvent];
4902 - (void)rightMouseUp: (NSEvent *)theEvent
4904   NSTRACE (rightMouseUp);
4905   [self mouseDown: theEvent];
4909 - (void)otherMouseUp: (NSEvent *)theEvent
4911   NSTRACE (otherMouseUp);
4912   [self mouseDown: theEvent];
4916 - (void) scrollWheel: (NSEvent *)theEvent
4918   NSTRACE (scrollWheel);
4919   [self mouseDown: theEvent];
4923 /* Tell emacs the mouse has moved. */
4924 - (void)mouseMoved: (NSEvent *)e
4926   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4927   Lisp_Object frame;
4929 //  NSTRACE (mouseMoved);
4931   last_mouse_movement_time = EV_TIMESTAMP (e);
4932   last_mouse_motion_position
4933     = [self convertPoint: [e locationInWindow] fromView: nil];
4935   /* update any mouse face */
4936   if (dpyinfo->mouse_face_hidden)
4937     {
4938       dpyinfo->mouse_face_hidden = 0;
4939       clear_mouse_face (dpyinfo);
4940     }
4942   /* tooltip handling */
4943   previous_help_echo_string = help_echo_string;
4944   help_echo_string = Qnil;
4946   if (!note_mouse_movement (emacsframe, last_mouse_motion_position.x,
4947                             last_mouse_motion_position.y))
4948     help_echo_string = previous_help_echo_string;
4950   XSETFRAME (frame, emacsframe);
4951   if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
4952     {
4953       /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
4954          (note_mouse_highlight), which is called through the
4955          note_mouse_movement () call above */
4956       gen_help_event (help_echo_string, frame, help_echo_window,
4957                       help_echo_object, help_echo_pos);
4958     }
4959   else
4960     {
4961       help_echo_string = Qnil;
4962       gen_help_event (Qnil, frame, Qnil, Qnil, 0);
4963     }
4965   if (emacsframe->mouse_moved && send_appdefined)
4966     ns_send_appdefined (-1);
4970 - (void)mouseDragged: (NSEvent *)e
4972   NSTRACE (mouseDragged);
4973   [self mouseMoved: e];
4977 - (void)rightMouseDragged: (NSEvent *)e
4979   NSTRACE (rightMouseDragged);
4980   [self mouseMoved: e];
4984 - (void)otherMouseDragged: (NSEvent *)e
4986   NSTRACE (otherMouseDragged);
4987   [self mouseMoved: e];
4991 - (BOOL)windowShouldClose: (id)sender
4993   NSEvent *e =[[self window] currentEvent];
4995   NSTRACE (windowShouldClose);
4996   windowClosing = YES;
4997   if (!emacs_event)
4998     return NO;
4999   emacs_event->kind = DELETE_WINDOW_EVENT;
5000   emacs_event->modifiers = 0;
5001   emacs_event->code = 0;
5002   EV_TRAILER (e);
5003   /* Don't close this window, let this be done from lisp code.  */
5004   return NO;
5008 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
5009 /* normalize frame to gridded text size */
5011   NSTRACE (windowWillResize);
5012 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
5014   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe,
5015 #ifdef NS_IMPL_GNUSTEP
5016                                         frameSize.width + 3);
5017 #else
5018                                         frameSize.width);
5019 #endif
5020   if (cols < MINWIDTH)
5021     cols = MINWIDTH;
5022   frameSize.width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (emacsframe, cols);
5024   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, frameSize.height
5025 #ifdef NS_IMPL_GNUSTEP
5026       - FRAME_NS_TITLEBAR_HEIGHT (emacsframe) + 3
5027         - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
5028 #else
5029       - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5030         - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
5031 #endif
5032   if (rows < MINHEIGHT)
5033     rows = MINHEIGHT;
5034   frameSize.height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows)
5035                        + FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5036                        + FRAME_NS_TOOLBAR_HEIGHT (emacsframe);
5037 #ifdef NS_IMPL_COCOA
5038   {
5039     /* this sets window title to have size in it; the wm does this under GS */
5040     NSRect r = [[self window] frame];
5041     if (r.size.height == frameSize.height && r.size.width == frameSize.width)
5042       {
5043         if (old_title != 0)
5044           {
5045             xfree (old_title);
5046             old_title = 0;
5047           }
5048       }
5049     else
5050       {
5051         char *size_title;
5052         NSWindow *window = [self window];
5053         if (old_title == 0)
5054           {
5055             const char *t = [[[self window] title] UTF8String];
5056             char *pos = strstr (t, "  â€”  ");
5057             if (pos)
5058               *pos = '\0';
5059             old_title = (char *) xmalloc (strlen (t) + 1);
5060             strcpy (old_title, t);
5061           }
5062         size_title = xmalloc (strlen (old_title) + 40);
5063         sprintf (size_title, "%s  â€”  (%d x %d)", old_title, cols, rows);
5064         [window setTitle: [NSString stringWithUTF8String: size_title]];
5065         [window display];
5066         xfree (size_title);
5067       }
5068   }
5069 #endif /* NS_IMPL_COCOA */
5070 /*fprintf (stderr,"    ...size became %.0f x %.0f  (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
5072   return frameSize;
5076 - (void)windowDidResize: (NSNotification *)notification
5078   NSWindow *theWindow = [notification object];
5080 #ifdef NS_IMPL_GNUSTEP
5081    /* in GNUstep, at least currently, it's possible to get a didResize
5082       without getting a willResize.. therefore we need to act as if we got
5083       the willResize now */
5084   NSSize sz = [theWindow frame].size;
5085   sz = [self windowWillResize: theWindow toSize: sz];
5086 #endif /* NS_IMPL_GNUSTEP */
5088   NSTRACE (windowDidResize);
5089 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
5091 #ifdef NS_IMPL_COCOA
5092   if (old_title != 0)
5093     {
5094       xfree (old_title);
5095       old_title = 0;
5096     }
5097 #endif /* NS_IMPL_COCOA */
5099   if (cols > 0 && rows > 0)
5100     x_set_window_size (emacsframe, 0, cols, rows);
5102   ns_send_appdefined (-1);
5106 - (void)windowDidBecomeKey: (NSNotification *)notification
5107 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5109   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5110   struct frame *old_focus = dpyinfo->x_focus_frame;
5112   NSTRACE (windowDidBecomeKey);
5114   if (emacsframe != old_focus)
5115     dpyinfo->x_focus_frame = emacsframe;
5117   ns_frame_rehighlight (emacsframe);
5119   if (emacs_event)
5120     {
5121       emacs_event->kind = FOCUS_IN_EVENT;
5122       EV_TRAILER ((id)nil);
5123     }
5127 - (void)windowDidResignKey: (NSNotification *)notification
5128 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5130   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5131   NSTRACE (windowDidResignKey);
5133   if (dpyinfo->x_focus_frame == emacsframe)
5134     dpyinfo->x_focus_frame = 0;
5136   ns_frame_rehighlight (emacsframe);
5138   /* FIXME: for some reason needed on second and subsequent clicks away
5139             from sole-frame Emacs to get hollow box to show */
5140   if (!windowClosing && [[self window] isVisible] == YES)
5141     {
5142       x_update_cursor (emacsframe, 1);
5143       x_set_frame_alpha (emacsframe);
5144     }
5146   if (emacs_event)
5147     {
5148       [self deleteWorkingText];
5149       emacs_event->kind = FOCUS_IN_EVENT;
5150       EV_TRAILER ((id)nil);
5151     }
5155 - (void)windowWillMiniaturize: sender
5157   NSTRACE (windowWillMiniaturize);
5161 - (BOOL)isFlipped
5163   return YES;
5167 - (BOOL)isOpaque
5169   return NO;
5173 - initFrameFromEmacs: (struct frame *)f
5175   NSRect r, wr;
5176   Lisp_Object tem;
5177   NSWindow *win;
5178   NSButton *toggleButton;
5179   int vbextra = NS_SCROLL_BAR_WIDTH (f);
5180   NSSize sz;
5181   NSColor *col;
5182   NSString *name;
5184   NSTRACE (initFrameFromEmacs);
5186   windowClosing = NO;
5187   processingCompose = NO;
5188   scrollbarsNeedingUpdate = 0;
5190 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
5192   r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
5193                  FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
5194   [self initWithFrame: r];
5196   FRAME_NS_VIEW (f) = self;
5197   emacsframe = f;
5198   old_title = 0;
5200   win = [[EmacsWindow alloc]
5201             initWithContentRect: r
5202                       styleMask: (NSResizableWindowMask |
5203                                   NSMiniaturizableWindowMask |
5204                                   NSClosableWindowMask)
5205                         backing: NSBackingStoreBuffered
5206                           defer: YES];
5208   wr = [win frame];
5209   f->border_width = wr.size.width - r.size.width;
5210   FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
5212   [win setAcceptsMouseMovedEvents: YES];
5213   [win setDelegate: self];
5214   [win useOptimizedDrawing: YES];
5216   sz.width = FRAME_COLUMN_WIDTH (f);
5217   sz.height = FRAME_LINE_HEIGHT (f);
5218   [win setResizeIncrements: sz];
5220   [[win contentView] addSubview: self];
5222   if (ns_drag_types)
5223     [self registerForDraggedTypes: ns_drag_types];
5225   tem = f->name;
5226   name = [NSString stringWithUTF8String:
5227                    NILP (tem) ? (unsigned char *)"Emacs" : SDATA (tem)];
5228   [win setTitle: name];
5230   /* toolbar support */
5231   toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
5232                          [NSString stringWithFormat: @"Emacs Frame %d",
5233                                    ns_window_num]];
5234   [win setToolbar: toolbar];
5235   [toolbar setVisible: NO];
5236 #ifdef NS_IMPL_COCOA
5237   toggleButton = [win standardWindowButton: NSWindowToolbarButton];
5238   [toggleButton setTarget: self];
5239   [toggleButton setAction: @selector (toggleToolbar: )];
5240 #endif
5241   FRAME_NS_TOOLBAR_HEIGHT (f) = 0;
5243   tem = f->icon_name;
5244   if (!NILP (tem))
5245     [win setMiniwindowTitle:
5246            [NSString stringWithUTF8String: SDATA (tem)]];
5248   {
5249     NSScreen *screen = [win screen];
5251     if (screen != 0)
5252       [win setFrameTopLeftPoint: NSMakePoint
5253            (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
5254             IN_BOUND (-SCREENMAX,
5255                      [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
5256   }
5258   [win makeFirstResponder: self];
5260   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5261                                   (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
5262   [win setBackgroundColor: col];
5263   if ([col alphaComponent] != 1.0)
5264     [win setOpaque: NO];
5266   [self allocateGState];
5268   ns_window_num++;
5269   return self;
5273 - (void)windowDidMove: sender
5275   NSWindow *win = [self window];
5276   NSRect r = [win frame];
5277   NSScreen *screen = [win screen];
5278   NSRect sr = [screen frame];
5280   NSTRACE (windowDidMove);
5282   if (!emacsframe->output_data.ns)
5283     return;
5284   if (screen != nil)
5285     {
5286       emacsframe->left_pos = r.origin.x; /* - sr.origin.x; */
5287       emacsframe->top_pos = sr.size.height -
5288         (r.origin.y + r.size.height); /* + sr.origin.y; */
5289     }
5292 #ifdef NS_IMPL_COCOA
5293 /* if we don't do this manually, the window will resize but not move */
5294 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
5296   NSTRACE (windowShouldZoom);
5297   [[self window] setFrame: newFrame display: NO];
5298   return YES;
5300 #endif
5303 /* Override to do something slightly nonstandard, but nice.  First click on
5304    zoom button will zoom vertically.  Second will zoom completely.  Third
5305    returns to original. */
5306 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
5307                         defaultFrame:(NSRect)defaultFrame
5309   NSRect result = [sender frame];
5310   NSTRACE (windowWillUseStandardFrame);
5312   if (result.size.height == defaultFrame.size.height) {
5313     result = defaultFrame;
5314   } else {
5315     result.size.height = defaultFrame.size.height;
5316     result.origin.y = defaultFrame.origin.y;
5317   }
5319   /* A windowWillResize does not get generated at least on Tiger. */
5320   [self windowWillResize: sender toSize: result.size];
5321   return result;
5325 - (void)windowDidDeminiaturize: sender
5327   NSTRACE (windowDidDeminiaturize);
5328   if (!emacsframe->output_data.ns)
5329     return;
5330   emacsframe->async_iconified = 0;
5331   emacsframe->async_visible   = 1;
5332   windows_or_buffers_changed++;
5334   if (emacs_event)
5335     {
5336       emacs_event->kind = ICONIFY_EVENT;
5337       EV_TRAILER ((id)nil);
5338     }
5342 - (void)windowDidExpose: sender
5344   NSTRACE (windowDidExpose);
5345   if (!emacsframe->output_data.ns)
5346     return;
5347   emacsframe->async_visible = 1;
5348   SET_FRAME_GARBAGED (emacsframe);
5350   if (send_appdefined)
5351     ns_send_appdefined (-1);
5355 - (void)windowDidMiniaturize: sender
5357   NSTRACE (windowDidMiniaturize);
5358   if (!emacsframe->output_data.ns)
5359     return;
5361   emacsframe->async_iconified = 1;
5362   emacsframe->async_visible = 0;
5364   if (emacs_event)
5365     {
5366       emacs_event->kind = ICONIFY_EVENT;
5367       EV_TRAILER ((id)nil);
5368     }
5372 - (void)mouseEntered: (NSEvent *)theEvent
5374   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5375   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5376   NSTRACE (mouseEntered);
5378   last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5382 - (void)mouseExited: (NSEvent *)theEvent
5384   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5385   NSRect r;
5386   struct ns_display_info *dpyinfo
5387     = emacsframe ? FRAME_NS_DISPLAY_INFO (emacsframe) : NULL;
5389   NSTRACE (mouseExited);
5391   if (dpyinfo || !emacsframe)
5392     return;
5394   last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5396   if (emacsframe == dpyinfo->mouse_face_mouse_frame)
5397     {
5398       clear_mouse_face (dpyinfo);
5399       dpyinfo->mouse_face_mouse_frame = 0;
5400     }
5404 - menuDown: sender
5406   NSTRACE (menuDown);
5407   if (context_menu_value == -1)
5408     context_menu_value = [sender tag];
5409   else
5410     find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
5411                                   emacsframe->menu_bar_vector,
5412                                   (void *)[sender tag]);
5413   ns_send_appdefined (-1);
5414   return self;
5418 - (EmacsToolbar *)toolbar
5420   return toolbar;
5424 /* this gets called on toolbar button click */
5425 - toolbarClicked: (id)item
5427   NSEvent *theEvent;
5428   int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
5430   NSTRACE (toolbarClicked);
5432   if (!emacs_event)
5433     return self;
5435   /* send first event (for some reason two needed) */
5436   theEvent = [[self window] currentEvent];
5437   emacs_event->kind = TOOL_BAR_EVENT;
5438   XSETFRAME (emacs_event->arg, emacsframe);
5439   EV_TRAILER (theEvent);
5441   emacs_event->kind = TOOL_BAR_EVENT;
5442 /*   XSETINT (emacs_event->code, 0); */
5443   emacs_event->arg = AREF (emacsframe->tool_bar_items,
5444                           idx + TOOL_BAR_ITEM_KEY);
5445   emacs_event->modifiers = EV_MODIFIERS (theEvent);
5446   EV_TRAILER (theEvent);
5447   return self;
5451 - toggleToolbar: (id)sender
5453   if (!emacs_event)
5454     return self;
5456   emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5457   emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
5458   EV_TRAILER ((id)nil);
5459   return self;
5463 - (void)drawRect: (NSRect)rect
5465   int x = NSMinX (rect), y = NSMinY (rect);
5466   int width = NSWidth (rect), height = NSHeight (rect);
5468   NSTRACE (drawRect);
5470   if (!emacsframe || !emacsframe->output_data.ns || ns_in_resize)
5471     return;
5473   ns_clear_frame_area (emacsframe, x, y, width, height);
5474   expose_frame (emacsframe, x, y, width, height);
5475   emacsframe->async_visible = 1;
5476   emacsframe->async_iconified = 0;
5480 /* NSDraggingDestination protocol methods.  Actually this is not really a
5481    protocol, but a category of Object.  O well...  */
5483 -(unsigned int) draggingEntered: (id <NSDraggingInfo>) sender
5485   NSTRACE (draggingEntered);
5486   return NSDragOperationGeneric;
5490 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
5492   return YES;
5496 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
5498   id pb;
5499   int x, y;
5500   NSString *type;
5501   NSEvent *theEvent = [[self window] currentEvent];
5502   NSPoint position;
5504   NSTRACE (performDragOperation);
5506   if (!emacs_event)
5507     return;
5509   position = [self convertPoint: [sender draggingLocation] fromView: nil];
5510   x = lrint (position.x);  y = lrint (position.y);
5512   pb = [sender draggingPasteboard];
5513   type = [pb availableTypeFromArray: ns_drag_types];
5514   if (type == 0)
5515     {
5516       return NO;
5517     }
5518   else if ([type isEqualToString: NSFilenamesPboardType])
5519     {
5520       NSArray *files;
5521       NSEnumerator *fenum;
5522       NSString *file;
5524       if (!(files = [pb propertyListForType: type]))
5525         return NO;
5527       fenum = [files objectEnumerator];
5528       while ( (file = [fenum nextObject]) )
5529         {
5530           emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5531           emacs_event->code = KEY_NS_DRAG_FILE;
5532           XSETINT (emacs_event->x, x);
5533           XSETINT (emacs_event->y, y);
5534           ns_input_file = append2 (ns_input_file,
5535                                    build_string ([file UTF8String]));
5536           emacs_event->modifiers = EV_MODIFIERS (theEvent);
5537           EV_TRAILER (theEvent);
5538         }
5539       return YES;
5540     }
5541   else if ([type isEqualToString: NSURLPboardType])
5542     {
5543       NSString *file;
5544       NSURL *fileURL;
5546       if (!(fileURL = [NSURL URLFromPasteboard: pb]) ||
5547           [fileURL isFileURL] == NO)
5548         return NO;
5550       file = [fileURL path];
5551       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5552       emacs_event->code = KEY_NS_DRAG_FILE;
5553       XSETINT (emacs_event->x, x);
5554       XSETINT (emacs_event->y, y);
5555       ns_input_file = append2 (ns_input_file, build_string ([file UTF8String]));
5556       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5557       EV_TRAILER (theEvent);
5558       return YES;
5559     }
5560   else if ([type isEqualToString: NSStringPboardType]
5561            || [type isEqualToString: NSTabularTextPboardType])
5562     {
5563       NSString *data;
5565       if (! (data = [pb stringForType: type]))
5566         return NO;
5568       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5569       emacs_event->code = KEY_NS_DRAG_TEXT;
5570       XSETINT (emacs_event->x, x);
5571       XSETINT (emacs_event->y, y);
5572       ns_input_text = build_string ([data UTF8String]);
5573       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5574       EV_TRAILER (theEvent);
5575       return YES;
5576     }
5577   else if ([type isEqualToString: NSColorPboardType])
5578     {
5579       NSColor *c = [NSColor colorFromPasteboard: pb];
5580       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5581       emacs_event->code = KEY_NS_DRAG_COLOR;
5582       XSETINT (emacs_event->x, x);
5583       XSETINT (emacs_event->y, y);
5584       ns_input_color = ns_color_to_lisp (c);
5585       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5586       EV_TRAILER (theEvent);
5587       return YES;
5588     }
5589   else if ([type isEqualToString: NSFontPboardType])
5590     {
5591       /* impl based on GNUstep NSTextView.m */
5592       NSData *data = [pb dataForType: NSFontPboardType];
5593       NSDictionary *dict = [NSUnarchiver unarchiveObjectWithData: data];
5594       NSFont *font = [dict objectForKey: NSFontAttributeName];
5595       char fontSize[10];
5597       if (font == nil)
5598         return NO;
5600       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5601       emacs_event->code = KEY_NS_CHANGE_FONT;
5602       XSETINT (emacs_event->x, x);
5603       XSETINT (emacs_event->y, y);
5604       ns_input_font = build_string ([[font fontName] UTF8String]);
5605       snprintf (fontSize, 10, "%f", [font pointSize]);
5606       ns_input_fontsize = build_string (fontSize);
5607       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5608       EV_TRAILER (theEvent);
5609       return YES;
5610     }
5611   else
5612     {
5613       error ("Invalid data type in dragging pasteboard.");
5614       return NO;
5615     }
5619 - validRequestorForSendType: (NSString *)typeSent
5620                  returnType: (NSString *)typeReturned
5622   NSTRACE (validRequestorForSendType);
5623   if ([ns_send_types indexOfObjectIdenticalTo: typeSent] != NSNotFound &&
5624       [ns_return_types indexOfObjectIdenticalTo: typeSent] != NSNotFound)
5625     return self;
5627   return [super validRequestorForSendType: typeSent
5628                                returnType: typeReturned];
5632 /* The next two methods are part of NSServicesRequests informal protocol,
5633    supposedly called when a services menu item is chosen from this app.
5634    But this should not happen because we override the services menu with our
5635    own entries which call ns-perform-service.
5636    Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
5637    So let's at least stub them out until further investigation can be done. */
5639 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
5641   /* we could call ns_string_from_pasteboard(pboard) here but then it should
5642      be written into the buffer in place of the existing selection..
5643      ordinary service calls go through functions defined in ns-win.el */
5644   return NO;
5647 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
5649   /* supposed to write for as many of types as we are able */
5650   return NO;
5654 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
5655    (gives a miniaturized version of the window); currently we use the latter for
5656    frames whose active buffer doesn't correspond to any file
5657    (e.g., '*scratch*') */
5658 - setMiniwindowImage: (BOOL) setMini
5660   id image = [[self window] miniwindowImage];
5661   NSTRACE (setMiniwindowImage);
5663   /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
5664      about "AppleDockIconEnabled" notwithstanding, however the set message
5665      below has its effect nonetheless. */
5666   if (image != emacsframe->output_data.ns->miniimage)
5667     {
5668       if (image && [image isKindOfClass: [EmacsImage class]])
5669         [image release];
5670       [[self window] setMiniwindowImage:
5671                        setMini ? emacsframe->output_data.ns->miniimage : nil];
5672     }
5674   return self;
5678 - (void) setRows: (int) r andColumns: (int) c
5680   rows = r;
5681   cols = c;
5684 @end  /* EmacsView */
5688 /* ==========================================================================
5690     EmacsWindow implementation
5692    ========================================================================== */
5694 @implementation EmacsWindow
5696 /* called only on resize clicks by special case in EmacsApp-sendEvent */
5697 - (void)mouseDown: (NSEvent *)theEvent
5699   if (ns_in_resize)
5700     {
5701       NSSize size = [[theEvent window] frame].size;
5702       grabOffset = [theEvent locationInWindow];
5703       grabOffset.x = size.width - grabOffset.x;
5704     }
5705   else
5706     [super mouseDown: theEvent];
5710 /* stop resizing */
5711 - (void)mouseUp: (NSEvent *)theEvent
5713   if (ns_in_resize)
5714     {
5715       struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
5716       ns_in_resize = NO;
5717       ns_set_name_as_filename (f);
5718       [self display];
5719       ns_send_appdefined (-1);
5720     }
5721   else
5722     [super mouseUp: theEvent];
5726 /* send resize events */
5727 - (void)mouseDragged: (NSEvent *)theEvent
5729   if (ns_in_resize)
5730     {
5731       NSPoint p = [theEvent locationInWindow];
5732       NSSize size, vettedSize, origSize = [self frame].size;
5734       size.width = p.x + grabOffset.x;
5735       size.height = origSize.height - p.y + grabOffset.y;
5737       if (size.width == origSize.width && size.height == origSize.height)
5738         return;
5740       vettedSize = [[self delegate] windowWillResize: self toSize: size];
5741       if (vettedSize.width != size.width || vettedSize.height != size.height)
5742         {
5743           [[NSNotificationCenter defaultCenter]
5744             postNotificationName: NSWindowDidResizeNotification
5745                           object: self];
5746         }
5747     }
5748   else
5749     [super mouseDragged: theEvent];
5752 @end /* EmacsWindow */
5755 /* ==========================================================================
5757     EmacsScroller implementation
5759    ========================================================================== */
5762 @implementation EmacsScroller
5764 /* for repeat button push */
5765 #define SCROLL_BAR_FIRST_DELAY 0.5
5766 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
5768 + (float) scrollerWidth
5770   /* TODO: if we want to allow variable widths, this is the place to do it,
5771            however neither GNUstep nor Cocoa support it very well */
5772   return [NSScroller scrollerWidth];
5776 - initFrame: (NSRect )r window: (Lisp_Object)nwin
5778   NSTRACE (EmacsScroller_initFrame);
5780   r.size.width = [EmacsScroller scrollerWidth];
5781   [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
5782   [self setContinuous: YES];
5783   [self setEnabled: YES];
5785   /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
5786      locked against the right, top and bottom edges. */
5787   [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
5789   win = nwin;
5790   condemned = NO;
5791   pixel_height = NSHeight (r);
5792   min_portion = 20 / pixel_height;
5794   frame = XFRAME (XWINDOW (win)->frame);
5795   if (FRAME_LIVE_P (frame))
5796     {
5797       int i;
5798       EmacsView *view = FRAME_NS_VIEW (frame);
5799       NSView *sview = [[view window] contentView];
5800       NSArray *subs = [sview subviews];
5802       /* disable optimization stopping redraw of other scrollbars */
5803       view->scrollbarsNeedingUpdate = 0;
5804       for (i =[subs count]-1; i >= 0; i--)
5805         if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
5806           view->scrollbarsNeedingUpdate++;
5807       [sview addSubview: self];
5808     }
5810 /*  [self setFrame: r]; */
5812   return self;
5816 - (void)setFrame: (NSRect)newRect
5818   NSTRACE (EmacsScroller_setFrame);
5819 /*  BLOCK_INPUT; */
5820   pixel_height = NSHeight (newRect);
5821   min_portion = 20 / pixel_height;
5822   [super setFrame: newRect];
5823   [self display];
5824 /*  UNBLOCK_INPUT; */
5828 - (void)dealloc
5830   NSTRACE (EmacsScroller_dealloc);
5831   if (!NILP (win))
5832     XWINDOW (win)->vertical_scroll_bar = Qnil;
5833   [super dealloc];
5837 - condemn
5839   NSTRACE (condemn);
5840   condemned =YES;
5841   return self;
5845 - reprieve
5847   NSTRACE (reprieve);
5848   condemned =NO;
5849   return self;
5853 - judge
5855   NSTRACE (judge);
5856   if (condemned)
5857     {
5858       BLOCK_INPUT;
5859       /* ensure other scrollbar updates after deletion */
5860       EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
5861       if (view != nil)
5862         view->scrollbarsNeedingUpdate++;
5863       [self removeFromSuperview];
5864       [self release];
5865       UNBLOCK_INPUT;
5866     }
5867   return self;
5871 - (void)resetCursorRects
5873   NSRect visible = [self visibleRect];
5874   NSTRACE (resetCursorRects);
5876   if (!NSIsEmptyRect (visible))
5877     [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
5878   [[NSCursor arrowCursor] setOnMouseEntered: YES];
5882 - (int) checkSamePosition: (int) position portion: (int) portion
5883                     whole: (int) whole
5885   return em_position ==position && em_portion ==portion && em_whole ==whole
5886     && portion != whole; /* needed for resize empty buf */
5890 - setPosition: (int)position portion: (int)portion whole: (int)whole
5892   NSTRACE (setPosition);
5894   em_position = position;
5895   em_portion = portion;
5896   em_whole = whole;
5898   if (portion >= whole)
5899     [self setFloatValue: 0.0 knobProportion: 1.0];
5900   else
5901     {
5902       float pos, por;
5903       portion = max ((float)whole*min_portion/pixel_height, portion);
5904       pos = (float)position / (whole - portion);
5905       por = (float)portion/whole;
5906       [self setFloatValue: pos knobProportion: por];
5907     }
5908 #ifdef NS_IMPL_GNUSTEP
5909   [self display];
5910 #endif
5911   return self;
5914 /* FIXME: unused at moment (see ns_mouse_position) at the moment because
5915      drag events will go directly to the EmacsScroller.  Leaving in for now. */
5916 -(void)getMouseMotionPart: (int *)part window: (Lisp_Object *)window
5917                         x: (Lisp_Object *)x y: ( Lisp_Object *)y
5919   *part = last_hit_part;
5920   *window = win;
5921   XSETINT (*y, pixel_height);
5922   if ([self floatValue] > 0.999)
5923     XSETINT (*x, pixel_height);
5924   else
5925     XSETINT (*x, pixel_height * [self floatValue]);
5929 /* set up emacs_event */
5930 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
5932   if (!emacs_event)
5933     return;
5935   emacs_event->part = last_hit_part;
5936   emacs_event->code = 0;
5937   emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
5938   emacs_event->frame_or_window = win;
5939   emacs_event->timestamp = EV_TIMESTAMP (e);
5940   emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
5941   emacs_event->arg = Qnil;
5942   XSETINT (emacs_event->x, loc * pixel_height);
5943   XSETINT (emacs_event->y, pixel_height-20);
5945   n_emacs_events_pending++;
5946   kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
5947   EVENT_INIT (*emacs_event);
5948   ns_send_appdefined (-1);
5952 /* called manually thru timer to implement repeated button action w/hold-down */
5953 - repeatScroll: (NSTimer *)scrollEntry
5955   NSEvent *e = [[self window] currentEvent];
5956   NSPoint p =  [[self window] mouseLocationOutsideOfEventStream];
5957   BOOL inKnob = [self testPart: p] == NSScrollerKnob;
5959   /* clear timer if need be */
5960   if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
5961     {
5962         [scroll_repeat_entry invalidate];
5963         [scroll_repeat_entry release];
5964         scroll_repeat_entry = nil;
5966         if (inKnob)
5967           return self;
5969         scroll_repeat_entry
5970           = [[NSTimer scheduledTimerWithTimeInterval:
5971                         SCROLL_BAR_CONTINUOUS_DELAY
5972                                             target: self
5973                                           selector: @selector (repeatScroll:)
5974                                           userInfo: 0
5975                                            repeats: YES]
5976               retain];
5977     }
5979   [self sendScrollEventAtLoc: 0 fromEvent: e];
5980   return self;
5984 /* Asynchronous mouse tracking for scroller.  This allows us to dispatch
5985    mouseDragged events without going into a modal loop. */
5986 - (void)mouseDown: (NSEvent *)e
5988   NSRect sr, kr;
5989   /* hitPart is only updated AFTER event is passed on */
5990   NSScrollerPart part = [self testPart: [e locationInWindow]];
5991   double inc = 0.0, loc, kloc, pos;
5992   int edge = 0;
5994   NSTRACE (EmacsScroller_mouseDown);
5996   switch (part)
5997     {
5998     case NSScrollerDecrementPage:
5999         last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
6000     case NSScrollerIncrementPage:
6001         last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
6002     case NSScrollerDecrementLine:
6003       last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
6004     case NSScrollerIncrementLine:
6005       last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
6006     case NSScrollerKnob:
6007       last_hit_part = scroll_bar_handle; break;
6008     case NSScrollerKnobSlot:  /* GNUstep-only */
6009       last_hit_part = scroll_bar_move_ratio; break;
6010     default:  /* NSScrollerNoPart? */
6011       fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %d\n", part);
6012       return;
6013     }
6015   if (inc != 0.0)
6016     {
6017       pos = 0;      /* ignored */
6019       /* set a timer to repeat, as we can't let superclass do this modally */
6020       scroll_repeat_entry
6021         = [[NSTimer scheduledTimerWithTimeInterval: 0.5
6022                                             target: self
6023                                           selector: @selector (repeatScroll:)
6024                                           userInfo: 0
6025                                            repeats: YES]
6026             retain];
6027     }
6028   else
6029     {
6030       /* handle, or on GNUstep possibly slot */
6031       NSEvent *fake_event;
6033       /* compute float loc in slot and mouse offset on knob */
6034       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6035                       toView: nil];
6036       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6037       if (loc <= 0.0)
6038         {
6039           loc = 0.0;
6040           edge = -1;
6041         }
6042       else if (loc >= NSHeight (sr))
6043         {
6044           loc = NSHeight (sr);
6045           edge = 1;
6046         }
6048       if (edge)
6049         kloc = 0.5 * edge;
6050       else
6051         {
6052           kr = [self convertRect: [self rectForPart: NSScrollerKnob]
6053                           toView: nil];
6054           kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
6055         }
6056       last_mouse_offset = kloc;
6058       /* if knob, tell emacs a location offset by knob pos
6059          (to indicate top of handle) */
6060       if (part == NSScrollerKnob)
6061           pos = (loc - last_mouse_offset) / NSHeight (sr);
6062       else
6063         /* else this is a slot click on GNUstep: go straight there */
6064         pos = loc / NSHeight (sr);
6066       /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
6067       fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
6068                                       location: [e locationInWindow]
6069                                  modifierFlags: [e modifierFlags]
6070                                      timestamp: [e timestamp]
6071                                   windowNumber: [e windowNumber]
6072                                        context: [e context]
6073                                    eventNumber: [e eventNumber]
6074                                     clickCount: [e clickCount]
6075                                       pressure: [e pressure]];
6076       [super mouseUp: fake_event];
6077     }
6079   if (part != NSScrollerKnob)
6080     [self sendScrollEventAtLoc: pos fromEvent: e];
6084 /* Called as we manually track scroller drags, rather than superclass. */
6085 - (void)mouseDragged: (NSEvent *)e
6087     NSRect sr;
6088     double loc, pos;
6089     int edge = 0;
6091     NSTRACE (EmacsScroller_mouseDragged);
6093       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6094                       toView: nil];
6095       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6097       if (loc <= 0.0)
6098         {
6099           loc = 0.0;
6100           edge = -1;
6101         }
6102       else if (loc >= NSHeight (sr) + last_mouse_offset)
6103         {
6104           loc = NSHeight (sr) + last_mouse_offset;
6105           edge = 1;
6106         }
6108       pos = /*(edge ? loc :*/ (loc - last_mouse_offset) / NSHeight (sr);
6109       [self sendScrollEventAtLoc: pos fromEvent: e];
6113 - (void)mouseUp: (NSEvent *)e
6115   if (scroll_repeat_entry)
6116     {
6117       [scroll_repeat_entry invalidate];
6118       [scroll_repeat_entry release];
6119       scroll_repeat_entry = nil;
6120     }
6121   last_hit_part = 0;
6125 /* treat scrollwheel events in the bar as though they were in the main window */
6126 - (void) scrollWheel: (NSEvent *)theEvent
6128   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
6129   [view mouseDown: theEvent];
6132 @end  /* EmacsScroller */
6136 /* ==========================================================================
6138     EmacsPrefsController implementation
6140    ========================================================================== */
6143 @implementation EmacsPrefsController
6145 /* in Tiger+, can just do [popup selectItemWithTag: tag]; */
6146 static void selectItemWithTag (NSPopUpButton *popup, int tag)
6148   NSEnumerator *items = [[popup itemArray] objectEnumerator];
6149   NSMenuItem *item;
6150   while (item = [items nextObject])
6151     {
6152       if ([item tag] == tag)
6153         {
6154           [popup selectItem: item];
6155           return;
6156         }
6157     }
6160 - init
6162   [NSBundle loadNibNamed: @"preferences" owner: self];
6163   return self;
6167 - (void) showForFrame: (struct frame *)f
6169   frame = f;
6170   [self setPanelFromValues];
6171   [prefsWindow makeKeyAndOrderFront: self];
6172   [prefsWindow display];
6176 /* If you change this, change setPanelFromDefaultValues too. */
6177 - (void) setPanelFromValues
6179   int cursorType
6180     = ns_lisp_to_cursor_type (get_frame_param (frame, Qcursor_type));
6181   prevExpandSpace = XFLOATINT (ns_expand_space);
6183 #ifdef NS_IMPL_COCOA
6184   prevUseHighlightColor = ns_use_system_highlight_color;
6185 #endif
6187   [expandSpaceSlider setFloatValue: prevExpandSpace];
6188   [cursorTypeMatrix selectCellWithTag: (cursorType == FILLED_BOX_CURSOR ? 1 :
6189                                         (cursorType == BAR_CURSOR ? 2 :
6190                                          (cursorType == HBAR_CURSOR ? 3 : 4)))];
6191   selectItemWithTag (alternateModMenu,
6192                      parse_solitary_modifier (ns_alternate_modifier));
6193   selectItemWithTag (commandModMenu,
6194                      parse_solitary_modifier (ns_command_modifier));
6195 #ifdef NS_IMPL_COCOA
6196   selectItemWithTag (controlModMenu,
6197                      parse_solitary_modifier (ns_control_modifier));
6198   selectItemWithTag (functionModMenu,
6199                      parse_solitary_modifier (ns_function_modifier));
6200   [smoothFontsCheck setState: (NILP (ns_antialias_text) ? NO : YES)];
6201   [useQuickdrawCheck setState: (NILP (ns_use_qd_smoothing) ? NO : YES)];
6202   [useSysHiliteCheck setState: (NILP (prevUseHighlightColor) ? NO : YES)];
6203   [confirmQuitCheck setState: (NILP (ns_confirm_quit) ? NO : YES)];
6204 #endif
6208 /* This and ns_set_default_prefs should be changed together. */
6209 - (void) setPanelFromDefaultValues
6211   [expandSpaceSlider setFloatValue: 0.0];
6212   [cursorTypeMatrix selectCellWithTag: 1]; /* filled box */
6213   selectItemWithTag (alternateModMenu, meta_modifier);
6214   selectItemWithTag (commandModMenu, super_modifier);
6215 #ifdef NS_IMPL_COCOA
6216   selectItemWithTag (controlModMenu, ctrl_modifier);
6217   selectItemWithTag (functionModMenu, 0); /* none */
6218   [smoothFontsCheck setState: YES];
6219   [useQuickdrawCheck setState: NO];
6220   [useSysHiliteCheck setState: YES];
6221 #endif
6225 - (void) setValuesFromPanel
6227   int altTag = [[alternateModMenu selectedItem] tag];
6228   int cmdTag = [[commandModMenu selectedItem] tag];
6229 #ifdef NS_IMPL_COCOA
6230   int ctrlTag = [[controlModMenu selectedItem] tag];
6231   int fnTag = [[functionModMenu selectedItem] tag];
6232 #endif
6233   float expandSpace = [expandSpaceSlider floatValue];
6234   int cursorTag = [[cursorTypeMatrix selectedCell] tag];
6235   Lisp_Object cursor_type = ns_cursor_type_to_lisp
6236        ( cursorTag == 1 ? FILLED_BOX_CURSOR
6237        : cursorTag == 2 ? BAR_CURSOR
6238        : cursorTag == 3 ? HBAR_CURSOR : HOLLOW_BOX_CURSOR);
6240   if (expandSpace != prevExpandSpace)
6241     {
6242       ns_expand_space = make_float (expandSpace);
6243       /* TODO: more needed: store needed metrics in nsfont_info, update
6244          frame default font max_bounds and fontp, recompute faces */
6245 /*         FRAME_LINE_HEIGHT (frame) *= (expandSpace / prevExpandSpace);
6246            x_set_window_size (frame, 0, frame->text_cols, frame->text_lines); */
6247       prevExpandSpace = expandSpace;
6248     }
6250   store_frame_param (frame, Qcursor_type, cursor_type);
6251   x_set_cursor_type (frame, cursor_type, Qnil);  /* FIXME: do only if changed */
6253   ns_alternate_modifier = ns_mod_to_lisp (altTag);
6254   ns_command_modifier = ns_mod_to_lisp (cmdTag);
6255 #ifdef NS_IMPL_COCOA
6256   ns_control_modifier = ns_mod_to_lisp (ctrlTag);
6257   ns_function_modifier = ns_mod_to_lisp (fnTag);
6258   ns_antialias_text = [smoothFontsCheck state] ? Qt : Qnil;
6259   ns_use_qd_smoothing = [useQuickdrawCheck state] ? Qt : Qnil;
6260   ns_use_system_highlight_color = [useSysHiliteCheck state] ? Qt : Qnil;
6261   ns_confirm_quit = [confirmQuitCheck state] ? Qt : Qnil;
6262   if (! EQ (ns_use_system_highlight_color, prevUseHighlightColor))
6263     {
6264       prevUseHighlightColor = ns_use_system_highlight_color;
6265       if (EQ (ns_use_system_highlight_color, Qt))
6266         {
6267           ns_selection_color = [[NSUserDefaults standardUserDefaults]
6268                                  stringForKey: @"AppleHighlightColor"];
6269           if (ns_selection_color == nil)
6270             ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
6271         }
6272       else
6273         ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
6274     }
6275 #endif /* NS_IMPL_COCOA */
6276   Fcall_interactively (intern ("ns-save-preferences"), Qnil, Qnil);
6280 /* buttons */
6281 - (IBAction)cancel: (id)sender
6283   [prefsWindow close];
6287 - (IBAction)ok: (id)sender
6289   [self setValuesFromPanel];
6290   [prefsWindow close];
6294 - (IBAction)resetToDefaults: (id)sender
6296   [self setPanelFromDefaultValues];
6300 - (IBAction)runHelp: (id)sender
6302   struct frame *emacsframe = frame;
6303   if (!emacs_event)
6304     return;
6305   ns_raise_frame(frame);
6306   emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
6307   emacs_event->code = KEY_NS_INFO_PREFS;
6308   EV_TRAILER ((id)nil);
6312 - (IBAction)setColors: (id)sender
6314   Lisp_Object lispFrame;
6315   XSETFRAME (lispFrame, frame);
6316   ns_raise_frame(frame);
6317   Fns_popup_color_panel (lispFrame);
6321 - (IBAction)setDefaultFont: (id)sender
6323   Lisp_Object lispFrame;
6324   XSETFRAME (lispFrame, frame);
6325   ns_raise_frame(frame);
6326   Fns_popup_font_panel (lispFrame);
6329 @end  /* EmacsPrefsController */
6334 /* ==========================================================================
6336    Font-related functions; these used to be in nsfaces.m
6338    ========================================================================== */
6341 Lisp_Object
6342 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
6344   struct font *font = XFONT_OBJECT (font_object);
6346   if (fontset < 0)
6347     fontset = fontset_from_font (font_object);
6348   FRAME_FONTSET (f) = fontset;
6350   if (FRAME_FONT (f) == font)
6351     /* This font is already set in frame F.  There's nothing more to
6352        do.  */
6353     return font_object;
6355   FRAME_FONT (f) = font;
6357   FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
6358   FRAME_COLUMN_WIDTH (f) = font->average_width;
6359   FRAME_SPACE_WIDTH (f) = font->space_width;
6360   FRAME_LINE_HEIGHT (f) = font->height;
6362   compute_fringe_widths (f, 1);
6364   /* Compute the scroll bar width in character columns.  */
6365   if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
6366     {
6367       int wid = FRAME_COLUMN_WIDTH (f);
6368       FRAME_CONFIG_SCROLL_BAR_COLS (f)
6369         = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
6370     }
6371   else
6372     {
6373       int wid = FRAME_COLUMN_WIDTH (f);
6374       FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
6375     }
6377   /* Now make the frame display the given font.  */
6378   if (FRAME_NS_WINDOW (f) != 0)
6379         x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
6381   return font_object;
6385 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
6386 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
6387          in 1.43. */
6389 const char *
6390 ns_xlfd_to_fontname (const char *xlfd)
6391 /* --------------------------------------------------------------------------
6392     Convert an X font name (XLFD) to an NS font name.
6393     Only family is used.
6394     The string returned is temporarily allocated.
6395    -------------------------------------------------------------------------- */
6397   char *name = xmalloc (180);
6398   int i, len;
6399   const char *ret;
6401   if (!strncmp (xlfd, "--", 2))
6402     sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
6403   else
6404     sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
6406   /* stopgap for malformed XLFD input */
6407   if (strlen (name) == 0)
6408     strcpy (name, "Monaco");
6410   /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
6411      also uppercase after '-' or ' ' */
6412   name[0] = toupper (name[0]);
6413   for (len =strlen (name), i =0; i<len; i++)
6414     {
6415       if (name[i] == '$')
6416         {
6417           name[i] = '-';
6418           if (i+1<len)
6419             name[i+1] = toupper (name[i+1]);
6420         }
6421       else if (name[i] == '_')
6422         {
6423           name[i] = ' ';
6424           if (i+1<len)
6425             name[i+1] = toupper (name[i+1]);
6426         }
6427     }
6428 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name);  */
6429   ret = [[NSString stringWithUTF8String: name] UTF8String];
6430   xfree (name);
6431   return ret;
6435 void
6436 syms_of_nsterm ()
6438   NSTRACE (syms_of_nsterm);
6439   DEFVAR_LISP ("ns-input-file", &ns_input_file,
6440               "The file specified in the last NS event.");
6441   ns_input_file =Qnil;
6443   DEFVAR_LISP ("ns-input-text", &ns_input_text,
6444               "The data received in the last NS text drag event.");
6445   ns_input_text =Qnil;
6447   DEFVAR_LISP ("ns-working-text", &ns_working_text,
6448               "String for visualizing working composition sequence.");
6449   ns_working_text =Qnil;
6451   DEFVAR_LISP ("ns-input-font", &ns_input_font,
6452               "The font specified in the last NS event.");
6453   ns_input_font =Qnil;
6455   DEFVAR_LISP ("ns-input-fontsize", &ns_input_fontsize,
6456               "The fontsize specified in the last NS event.");
6457   ns_input_fontsize =Qnil;
6459   DEFVAR_LISP ("ns-input-line", &ns_input_line,
6460                "The line specified in the last NS event.");
6461   ns_input_line =Qnil;
6463   DEFVAR_LISP ("ns-input-color", &ns_input_color,
6464                "The color specified in the last NS event.");
6465   ns_input_color =Qnil;
6467   DEFVAR_LISP ("ns-input-spi-name", &ns_input_spi_name,
6468                "The service name specified in the last NS event.");
6469   ns_input_spi_name =Qnil;
6471   DEFVAR_LISP ("ns-input-spi-arg", &ns_input_spi_arg,
6472                "The service argument specified in the last NS event.");
6473   ns_input_spi_arg =Qnil;
6475   DEFVAR_LISP ("ns-alternate-modifier", &ns_alternate_modifier,
6476                "This variable describes the behavior of the alternate or option key.\n\
6477 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6478 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6479 at all, allowing it to be used at a lower level for accented character entry.");
6481   DEFVAR_LISP ("ns-command-modifier", &ns_command_modifier,
6482                "This variable describes the behavior of the command key.\n\
6483 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6485   DEFVAR_LISP ("ns-control-modifier", &ns_control_modifier,
6486                "This variable describes the behavior of the control key.\n\
6487 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6489   DEFVAR_LISP ("ns-function-modifier", &ns_function_modifier,
6490                "This variable describes the behavior of the function key (on laptops).\n\
6491 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6492 Set to none means that the function key is not interpreted by Emacs at all,\n\
6493 allowing it to be used at a lower level for accented character entry.");
6495   DEFVAR_LISP ("ns-expand-space", &ns_expand_space,
6496                "Amount by which spacing between lines is expanded (positive)\n\
6497 or shrunk (negative).  Zero (the default) means standard line height.\n\
6498 (This variable should only be read, never set.)");
6500   DEFVAR_LISP ("ns-antialias-text", &ns_antialias_text,
6501                "Non-nil (the default) means to render text antialiased. Only has an effect on OS X Panther and above.");
6503   DEFVAR_LISP ("ns-use-qd-smoothing", &ns_use_qd_smoothing,
6504                "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).");
6506   DEFVAR_LISP ("ns-use-system-highlight-color",
6507                &ns_use_system_highlight_color,
6508                "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'.");
6510   DEFVAR_LISP ("ns-confirm-quit", &ns_confirm_quit,
6511                "Whether to confirm application quit using dialog.");
6513   staticpro (&ns_display_name_list);
6514   ns_display_name_list = Qnil;
6516   staticpro (&last_mouse_motion_frame);
6517   last_mouse_motion_frame = Qnil;
6519   /* from 23+ we need to tell emacs what modifiers there are.. */
6520   Qmodifier_value = intern ("modifier-value");
6521   Qalt = intern ("alt");
6522   Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
6523   Qhyper = intern ("hyper");
6524   Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
6525   Qmeta = intern ("meta");
6526   Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
6527   Qsuper = intern ("super");
6528   Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
6529   Qcontrol = intern ("control");
6530   Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
6532   /* TODO: move to common code */
6533   DEFVAR_LISP ("x-toolkit-scroll-bars", &Vx_toolkit_scroll_bars,
6534                doc: /* If not nil, Emacs uses toolkit scroll bars.  */);
6535 #ifdef USE_TOOLKIT_SCROLL_BARS
6536   Vx_toolkit_scroll_bars = Qt;
6537 #else
6538   Vx_toolkit_scroll_bars = Qnil;
6539 #endif
6541   /* these are unsupported but we need the declarations to avoid whining
6542      messages from cus-start.el */
6543   DEFVAR_BOOL ("x-use-underline-position-properties",
6544                &x_use_underline_position_properties,
6545      doc: /* NOT SUPPORTED UNDER NS.
6546 *Non-nil means make use of UNDERLINE_POSITION font properties.
6547 A value of nil means ignore them.  If you encounter fonts with bogus
6548 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
6549 to 4.1, set this to nil.
6551 NOTE: Not supported on Mac yet.  */);
6552   x_use_underline_position_properties = 0;
6554   DEFVAR_BOOL ("x-underline-at-descent-line",
6555                &x_underline_at_descent_line,
6556      doc: /* NOT SUPPORTED UNDER NS.
6557 *Non-nil means to draw the underline at the same place as the descent line.
6558 A value of nil means to draw the underline according to the value of the
6559 variable `x-use-underline-position-properties', which is usually at the
6560 baseline level.  The default value is nil.  */);
6561   x_underline_at_descent_line = 0;
6563   /* Tell emacs about this window system. */
6564   Fprovide (intern ("ns"), Qnil);
6568 // arch-tag: 6eaa8f7d-a69b-4e1c-b43d-ab31defbe0d2