Retrospective commit from 2009-12-26.
[emacs.git] / src / nsterm.m
blob9256c084e28ed544a70f686431b6fd9623013ed4
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>
37 #include <setjmp.h>
39 #include "lisp.h"
40 #include "blockinput.h"
41 #include "sysselect.h"
42 #include "nsterm.h"
43 #include "systime.h"
44 #include "character.h"
45 #include "fontset.h"
46 #include "composite.h"
47 #include "ccl.h"
49 #include "termhooks.h"
50 #include "termopts.h"
51 #include "termchar.h"
53 #include "window.h"
54 #include "keyboard.h"
56 #include "font.h"
58 /* call tracing */
59 #if 0
60 int term_trace_num = 0;
61 #define NSTRACE(x)        fprintf (stderr, "%s:%d: [%d] " #x "\n",         \
62                                 __FILE__, __LINE__, ++term_trace_num)
63 #else
64 #define NSTRACE(x)
65 #endif
68 /* ==========================================================================
70     Local declarations
72    ========================================================================== */
74 /* Convert a symbol indexed with an NSxxx value to a value as defined
75    in keyboard.c (lispy_function_key). I hope this is a correct way
76    of doing things... */
77 static unsigned convert_ns_to_X_keysym[] =
79   NSHomeFunctionKey,            0x50,
80   NSLeftArrowFunctionKey,       0x51,
81   NSUpArrowFunctionKey,         0x52,
82   NSRightArrowFunctionKey,      0x53,
83   NSDownArrowFunctionKey,       0x54,
84   NSPageUpFunctionKey,          0x55,
85   NSPageDownFunctionKey,        0x56,
86   NSEndFunctionKey,             0x57,
87   NSBeginFunctionKey,           0x58,
88   NSSelectFunctionKey,          0x60,
89   NSPrintFunctionKey,           0x61,
90   NSExecuteFunctionKey,         0x62,
91   NSInsertFunctionKey,          0x63,
92   NSUndoFunctionKey,            0x65,
93   NSRedoFunctionKey,            0x66,
94   NSMenuFunctionKey,            0x67,
95   NSFindFunctionKey,            0x68,
96   NSHelpFunctionKey,            0x6A,
97   NSBreakFunctionKey,           0x6B,
99   NSF1FunctionKey,              0xBE,
100   NSF2FunctionKey,              0xBF,
101   NSF3FunctionKey,              0xC0,
102   NSF4FunctionKey,              0xC1,
103   NSF5FunctionKey,              0xC2,
104   NSF6FunctionKey,              0xC3,
105   NSF7FunctionKey,              0xC4,
106   NSF8FunctionKey,              0xC5,
107   NSF9FunctionKey,              0xC6,
108   NSF10FunctionKey,             0xC7,
109   NSF11FunctionKey,             0xC8,
110   NSF12FunctionKey,             0xC9,
111   NSF13FunctionKey,             0xCA,
112   NSF14FunctionKey,             0xCB,
113   NSF15FunctionKey,             0xCC,
114   NSF16FunctionKey,             0xCD,
115   NSF17FunctionKey,             0xCE,
116   NSF18FunctionKey,             0xCF,
117   NSF19FunctionKey,             0xD0,
118   NSF20FunctionKey,             0xD1,
119   NSF21FunctionKey,             0xD2,
120   NSF22FunctionKey,             0xD3,
121   NSF23FunctionKey,             0xD4,
122   NSF24FunctionKey,             0xD5,
124   NSBackspaceCharacter,         0x08,  /* 8: Not on some KBs. */
125   NSDeleteCharacter,            0xFF,  /* 127: Big 'delete' key upper right. */
126   NSDeleteFunctionKey,          0x9F,  /* 63272: Del forw key off main array. */
128   NSTabCharacter,               0x09,
129   0x19,                         0x09,  /* left tab->regular since pass shift */
130   NSCarriageReturnCharacter,    0x0D,
131   NSNewlineCharacter,           0x0D,
132   NSEnterCharacter,             0x8D,
134   0x1B,                         0x1B   /* escape */
138 /* Lisp communications */
139 Lisp_Object ns_input_file, ns_input_font, ns_input_fontsize, ns_input_line;
140 Lisp_Object ns_input_color, ns_input_text, ns_working_text;
141 Lisp_Object ns_input_spi_name, ns_input_spi_arg;
142 Lisp_Object Vx_toolkit_scroll_bars;
143 static Lisp_Object Qmodifier_value;
144 /* TODO: unsure why these defined in term files, anyway we need in keymap.c */
145 Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper;
146 extern Lisp_Object Qcursor_color, Qcursor_type, Qns;
148 /* Specifies which emacs modifier should be generated when NS receives
149    the Alternate modifer.  May be Qnone or any of the modifier lisp symbols. */
150 Lisp_Object ns_alternate_modifier;
152 /* Specifies which emacs modifier should be generated when NS receives
153    the Command modifer.  May be any of the modifier lisp symbols. */
154 Lisp_Object ns_command_modifier;
156 /* Specifies which emacs modifier should be generated when NS receives
157    the Control modifer.  May be any of the modifier lisp symbols. */
158 Lisp_Object ns_control_modifier;
160 /* Specifies which emacs modifier should be generated when NS receives
161    the Function modifer (laptops).  May be any of the modifier lisp symbols. */
162 Lisp_Object ns_function_modifier;
164 /* Control via default 'GSFontAntiAlias' on OS X and GNUstep. */
165 Lisp_Object ns_antialias_text;
167 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
168    the maximum font size to NOT antialias.  On GNUstep there is currently
169    no way to control this behavior. */
170 float ns_antialias_threshold;
172 /* Used to pick up AppleHighlightColor on OS X */
173 NSString *ns_selection_color;
175 /* Confirm on exit. */
176 Lisp_Object ns_confirm_quit;
178 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
179 NSString *ns_app_name = @"Emacs";  /* default changed later */
181 /* Display variables */
182 struct ns_display_info *x_display_list; /* Chain of existing displays */
183 Lisp_Object ns_display_name_list;
184 long context_menu_value = 0;
186 /* display update */
187 NSPoint last_mouse_motion_position;
188 static NSRect last_mouse_glyph;
189 static unsigned long last_mouse_movement_time = 0;
190 static Lisp_Object last_mouse_motion_frame;
191 static EmacsScroller *last_mouse_scroll_bar = nil;
192 static struct frame *ns_updating_frame;
193 static NSView *focus_view = NULL;
194 static int ns_window_num =0;
195 static NSRect uRect;
196 static BOOL gsaved = NO;
197 BOOL ns_in_resize = NO;
198 static BOOL ns_fake_keydown = NO;
199 int ns_tmp_flags; /* FIXME */
200 struct nsfont_info *ns_tmp_font; /* FIXME */
201 /*static int debug_lock = 0; */
203 /* event loop */
204 static BOOL send_appdefined = YES;
205 static NSEvent *last_appdefined_event = 0;
206 static NSTimer *timed_entry = 0;
207 static NSTimer *fd_entry = nil;
208 static NSTimer *scroll_repeat_entry = nil;
209 static fd_set select_readfds, t_readfds;
210 static struct timeval select_timeout;
211 static int select_nfds;
212 static NSAutoreleasePool *outerpool;
213 static struct input_event *emacs_event = NULL;
214 static struct input_event *q_event_ptr = NULL;
215 static int n_emacs_events_pending = 0;
216 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
217   *ns_pending_service_args;
218 static BOOL inNsSelect = 0;
220 /* Convert modifiers in a NeXTSTEP event to emacs style modifiers.  */
221 #define NS_FUNCTION_KEY_MASK 0x800000
222 #define EV_MODIFIERS(e)                               \
223     ((([e modifierFlags] & NSHelpKeyMask) ?           \
224            hyper_modifier : 0)                        \
225      | (([e modifierFlags] & NSAlternateKeyMask) ?    \
226            parse_solitary_modifier (ns_alternate_modifier) : 0)   \
227      | (([e modifierFlags] & NSShiftKeyMask) ?        \
228            shift_modifier : 0)                        \
229      | (([e modifierFlags] & NSControlKeyMask) ?      \
230            parse_solitary_modifier (ns_control_modifier) : 0)     \
231      | (([e modifierFlags] & NS_FUNCTION_KEY_MASK) ?  \
232            parse_solitary_modifier (ns_function_modifier) : 0)    \
233      | (([e modifierFlags] & NSCommandKeyMask) ?      \
234            parse_solitary_modifier (ns_command_modifier):0))
236 #define EV_UDMODIFIERS(e)                                      \
237     ((([e type] == NSLeftMouseDown) ? down_modifier : 0)       \
238      | (([e type] == NSRightMouseDown) ? down_modifier : 0)    \
239      | (([e type] == NSOtherMouseDown) ? down_modifier : 0)    \
240      | (([e type] == NSLeftMouseDragged) ? down_modifier : 0)  \
241      | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
242      | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
243      | (([e type] == NSLeftMouseUp)   ? up_modifier   : 0)     \
244      | (([e type] == NSRightMouseUp)   ? up_modifier   : 0)    \
245      | (([e type] == NSOtherMouseUp)   ? up_modifier   : 0))
247 #define EV_BUTTON(e)                                                         \
248     ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 :    \
249       (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
250      [e buttonNumber] - 1)
252 /* Convert the time field to a timestamp in milliseconds. */
253 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
255 /* This is a piece of code which is common to all the event handling
256    methods.  Maybe it should even be a function.  */
257 #define EV_TRAILER(e)                                         \
258   {                                                           \
259   XSETFRAME (emacs_event->frame_or_window, emacsframe);       \
260   if (e) emacs_event->timestamp = EV_TIMESTAMP (e);           \
261   n_emacs_events_pending++;                                   \
262   kbd_buffer_store_event_hold (emacs_event, q_event_ptr);     \
263   EVENT_INIT (*emacs_event);                                  \
264   ns_send_appdefined (-1);                                    \
265   }
267 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
269 /* TODO: get rid of need for these forward declarations */
270 static void ns_condemn_scroll_bars (struct frame *f);
271 static void ns_judge_scroll_bars (struct frame *f);
272 void x_set_frame_alpha (struct frame *f);
274 /* unused variables needed for compatibility reasons */
275 int x_use_underline_position_properties, x_underline_at_descent_line;
276 /* FIXME: figure out what to do with underline_minimum_offset. */
279 /* ==========================================================================
281     Utilities
283    ========================================================================== */
286 static Lisp_Object
287 append2 (Lisp_Object list, Lisp_Object item)
288 /* --------------------------------------------------------------------------
289    Utility to append to a list
290    -------------------------------------------------------------------------- */
292   Lisp_Object array[2];
293   array[0] = list;
294   array[1] = Fcons (item, Qnil);
295   return Fnconc (2, &array[0]);
299 void
300 ns_init_paths ()
301 /* --------------------------------------------------------------------------
302    Used to allow emacs to find its resources under Emacs.app
303    Called from emacs.c at startup.
304    -------------------------------------------------------------------------- */
306   NSBundle *bundle = [NSBundle mainBundle];
307   NSString *binDir = [bundle bundlePath], *resourceDir = [bundle resourcePath];
308   NSString *resourcePath, *resourcePaths;
309   NSRange range;
310   BOOL onWindows = NO; /* how do I determine this? */
311   NSString *pathSeparator = onWindows ? @";" : @":";
312   NSFileManager *fileManager = [NSFileManager defaultManager];
313   BOOL isDir;
314 /*NSLog (@"ns_init_paths: '%@'\n%@\n", [[NSBundle mainBundle] bundlePath], [[NSBundle mainBundle] resourcePath]); */
316   /* get bindir from base */
317   range = [resourceDir rangeOfString: @"Contents"];
318   if (range.location != NSNotFound)
319     {
320       binDir = [binDir stringByAppendingPathComponent: @"Contents"];
321 #ifdef NS_IMPL_COCOA
322       binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
323 #endif
324     }
326   /* the following based on Andrew Choi's init_mac_osx_environment () */
327   if (!getenv ("EMACSLOADPATH"))
328     {
329       NSArray *paths = [resourceDir stringsByAppendingPaths:
330                                   [NSArray arrayWithObjects:
331                                          @"site-lisp", @"lisp", @"leim", nil]];
332       NSEnumerator *pathEnum = [paths objectEnumerator];
333       resourcePaths = @"";
334       while (resourcePath = [pathEnum nextObject])
335         {
336           if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
337             if (isDir)
338               {
339                 if ([resourcePaths length] > 0)
340                   resourcePaths
341                     = [resourcePaths stringByAppendingString: pathSeparator];
342                 resourcePaths
343                   = [resourcePaths stringByAppendingString: resourcePath];
344               }
345         }
346       if ([resourcePaths length] > 0)
347         setenv ("EMACSLOADPATH", [resourcePaths UTF8String], 1);
348 /*NSLog (@"loadPath: '%@'\n", resourcePaths); */
349     }
351   if (!getenv ("EMACSPATH"))
352     {
353       NSArray *paths = [binDir stringsByAppendingPaths:
354                                   [NSArray arrayWithObjects: @"bin",
355                                                              @"lib-exec", nil]];
356       NSEnumerator *pathEnum = [paths objectEnumerator];
357       resourcePaths = @"";
358       while (resourcePath = [pathEnum nextObject])
359         {
360           if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
361             if (isDir)
362               {
363                 if ([resourcePaths length] > 0)
364                   resourcePaths
365                     = [resourcePaths stringByAppendingString: pathSeparator];
366                 resourcePaths
367                   = [resourcePaths stringByAppendingString: resourcePath];
368               }
369         }
370       if ([resourcePaths length] > 0)
371         setenv ("EMACSPATH", [resourcePaths UTF8String], 1);
372     }
374   resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
375   if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
376     {
377       if (isDir)
378         {
379           if (!getenv ("EMACSDATA"))
380             setenv ("EMACSDATA", [resourcePath UTF8String], 1);
381           if (!getenv ("EMACSDOC"))
382             setenv ("EMACSDOC", [resourcePath UTF8String], 1);
383         }
384     }
386   if (!getenv ("INFOPATH"))
387     {
388       resourcePath = [resourceDir stringByAppendingPathComponent: @"info"];
389       if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
390         if (isDir)
391           setenv ("INFOPATH", [[resourcePath stringByAppendingString: @":"]
392                                              UTF8String], 1);
393       /* Note, extra colon needed to cause merge w/later user additions. */
394     }
398 static int
399 timeval_subtract (struct timeval *result, struct timeval x, struct timeval y)
400 /* --------------------------------------------------------------------------
401    Subtract the `struct timeval' values X and Y, storing the result in RESULT.
402    Return 1 if the difference is negative, otherwise 0.
403    -------------------------------------------------------------------------- */
405   /* Perform the carry for the later subtraction by updating y.
406      This is safer because on some systems
407      the tv_sec member is unsigned.  */
408   if (x.tv_usec < y.tv_usec)
409     {
410       int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
411       y.tv_usec -= 1000000 * nsec;
412       y.tv_sec += nsec;
413     }
414   if (x.tv_usec - y.tv_usec > 1000000)
415     {
416       int nsec = (y.tv_usec - x.tv_usec) / 1000000;
417       y.tv_usec += 1000000 * nsec;
418       y.tv_sec -= nsec;
419     }
421   /* Compute the time remaining to wait.  tv_usec is certainly positive.  */
422   result->tv_sec = x.tv_sec - y.tv_sec;
423   result->tv_usec = x.tv_usec - y.tv_usec;
425   /* Return indication of whether the result should be considered negative.  */
426   return x.tv_sec < y.tv_sec;
429 static void
430 ns_timeout (int usecs)
431 /* --------------------------------------------------------------------------
432      Blocking timer utility used by ns_ring_bell
433    -------------------------------------------------------------------------- */
435   struct timeval wakeup;
437   EMACS_GET_TIME (wakeup);
439   /* Compute time to wait until, propagating carry from usecs.  */
440   wakeup.tv_usec += usecs;
441   wakeup.tv_sec += (wakeup.tv_usec / 1000000);
442   wakeup.tv_usec %= 1000000;
444   /* Keep waiting until past the time wakeup.  */
445   while (1)
446     {
447       struct timeval timeout;
449       EMACS_GET_TIME (timeout);
451       /* In effect, timeout = wakeup - timeout.
452          Break if result would be negative.  */
453       if (timeval_subtract (&timeout, wakeup, timeout))
454         break;
456       /* Try to wait that long--but we might wake up sooner.  */
457       select (0, NULL, NULL, NULL, &timeout);
458     }
462 void
463 ns_release_object (void *obj)
464 /* --------------------------------------------------------------------------
465     Release an object (callable from C)
466    -------------------------------------------------------------------------- */
468     [(id)obj release];
472 void
473 ns_retain_object (void *obj)
474 /* --------------------------------------------------------------------------
475     Retain an object (callable from C)
476    -------------------------------------------------------------------------- */
478     [(id)obj retain];
482 void *
483 ns_alloc_autorelease_pool ()
484 /* --------------------------------------------------------------------------
485      Allocate a pool for temporary objects (callable from C)
486    -------------------------------------------------------------------------- */
488   return [[NSAutoreleasePool alloc] init];
492 void
493 ns_release_autorelease_pool (void *pool)
494 /* --------------------------------------------------------------------------
495      Free a pool and temporary objects it refers to (callable from C)
496    -------------------------------------------------------------------------- */
498   ns_release_object (pool);
503 /* ==========================================================================
505     Focus (clipping) and screen update
507    ========================================================================== */
509 static NSRect
510 ns_resize_handle_rect (NSWindow *window)
512   NSRect r = [window frame];
513   r.origin.x = r.size.width - RESIZE_HANDLE_SIZE;
514   r.origin.y = 0;
515   r.size.width = r.size.height = RESIZE_HANDLE_SIZE;
516   return r;
520 static void
521 ns_update_begin (struct frame *f)
522 /* --------------------------------------------------------------------------
523    Prepare for a grouped sequence of drawing calls
524    external (RIF) call; whole frame, called before update_window_begin
525    -------------------------------------------------------------------------- */
527   NSView *view = FRAME_NS_VIEW (f);
528   NSTRACE (ns_update_begin);
530   ns_updating_frame = f;
531   [view lockFocus];
533 #ifdef NS_IMPL_GNUSTEP
534   uRect = NSMakeRect (0, 0, 0, 0);
535 #endif
539 static void
540 ns_update_window_begin (struct window *w)
541 /* --------------------------------------------------------------------------
542    Prepare for a grouped sequence of drawing calls
543    external (RIF) call; for one window, called after update_begin
544    -------------------------------------------------------------------------- */
546   struct frame *f = XFRAME (WINDOW_FRAME (w));
547   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
548   NSTRACE (ns_update_window_begin);
550   updated_window = w;
551   set_output_cursor (&w->cursor);
553   BLOCK_INPUT;
555   if (f == dpyinfo->mouse_face_mouse_frame)
556     {
557       /* Don't do highlighting for mouse motion during the update.  */
558       dpyinfo->mouse_face_defer = 1;
560         /* If the frame needs to be redrawn,
561            simply forget about any prior mouse highlighting.  */
562       if (FRAME_GARBAGED_P (f))
563         dpyinfo->mouse_face_window = Qnil;
565       /* (further code for mouse faces ifdef'd out in other terms elided) */
566     }
568   UNBLOCK_INPUT;
572 static void
573 ns_update_window_end (struct window *w, int cursor_on_p,
574                       int mouse_face_overwritten_p)
575 /* --------------------------------------------------------------------------
576    Finished a grouped sequence of drawing calls
577    external (RIF) call; for one window called before update_end
578    -------------------------------------------------------------------------- */
580   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (XFRAME (w->frame));
582   /* note: this fn is nearly identical in all terms */
583   if (!w->pseudo_window_p)
584     {
585       BLOCK_INPUT;
587       if (cursor_on_p)
588         display_and_set_cursor (w, 1,
589                                 output_cursor.hpos, output_cursor.vpos,
590                                 output_cursor.x, output_cursor.y);
592       if (draw_window_fringes (w, 1))
593         x_draw_vertical_border (w);
595       UNBLOCK_INPUT;
596     }
598   /* If a row with mouse-face was overwritten, arrange for
599      frame_up_to_date to redisplay the mouse highlight.  */
600   if (mouse_face_overwritten_p)
601     {
602       dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
603       dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
604       dpyinfo->mouse_face_window = Qnil;
605     }
607   updated_window = NULL;
608   NSTRACE (update_window_end);
612 static void
613 ns_update_end (struct frame *f)
614 /* --------------------------------------------------------------------------
615    Finished a grouped sequence of drawing calls
616    external (RIF) call; for whole frame, called after update_window_end
617    -------------------------------------------------------------------------- */
619   NSView *view = FRAME_NS_VIEW (f);
621 /*   if (f == FRAME_NS_DISPLAY_INFO (f)->mouse_face_mouse_frame) */
622     FRAME_NS_DISPLAY_INFO (f)->mouse_face_defer = 0;
624   BLOCK_INPUT;
626 #ifdef NS_IMPL_GNUSTEP
627   /* trigger flush only in the rectangle we tracked as being drawn */
628   [view unlockFocusNeedsFlush: NO];
629 /*fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", uRect.origin.x, uRect.origin.y, uRect.size.width, uRect.size.height); */
630   [view lockFocusInRect: uRect];
631 #endif
633   [view unlockFocus];
634   [[view window] flushWindow];
636   UNBLOCK_INPUT;
637   ns_updating_frame = NULL;
638   NSTRACE (ns_update_end);
642 static void
643 ns_flush (struct frame *f)
644 /* --------------------------------------------------------------------------
645    external (RIF) call
646    NS impl is no-op since currently we flush in ns_update_end and elsewhere
647    -------------------------------------------------------------------------- */
649     NSTRACE (ns_flush);
653 static void
654 ns_focus (struct frame *f, NSRect *r, int n)
655 /* --------------------------------------------------------------------------
656    Internal: Focus on given frame.  During small local updates this is used to
657      draw, however during large updates, ns_update_begin and ns_update_end are
658      called to wrap the whole thing, in which case these calls are stubbed out.
659      Except, on GNUstep, we accumulate the rectangle being drawn into, because
660      the back end won't do this automatically, and will just end up flushing
661      the entire window.
662    -------------------------------------------------------------------------- */
664 //  NSTRACE (ns_focus);
665 #ifdef NS_IMPL_GNUSTEP
666   NSRect u;
667     if (n == 2)
668       u = NSUnionRect (r[0], r[1]);
669     else if (r)
670       u = *r;
671 #endif
672 /* static int c =0;
673    fprintf (stderr, "focus: %d", c++);
674    if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
675    fprintf (stderr, "\n"); */
677   if (f != ns_updating_frame)
678     {
679       NSView *view = FRAME_NS_VIEW (f);
680       if (view != focus_view)
681         {
682           if (focus_view != NULL)
683             {
684               [focus_view unlockFocus];
685               [[focus_view window] flushWindow];
686 /*debug_lock--; */
687             }
689           if (view)
690 #ifdef NS_IMPL_GNUSTEP
691             r ? [view lockFocusInRect: u] : [view lockFocus];
692 #else
693             [view lockFocus];
694 #endif
695           focus_view = view;
696 /*if (view) debug_lock++; */
697         }
698 #ifdef NS_IMPL_GNUSTEP
699       else
700         {
701           /* more than one rect being drawn into */
702           if (view && r)
703             {
704               [view unlockFocus]; /* add prev rect to redraw list */
705               [view lockFocusInRect: u]; /* focus for draw in new rect */
706             }
707         }
708 #endif
709     }
710 #ifdef NS_IMPL_GNUSTEP
711   else
712     {
713       /* in batch mode, but in GNUstep must still track rectangles explicitly */
714       uRect = (r ? NSUnionRect (uRect, u) : [FRAME_NS_VIEW (f) visibleRect]);
715     }
716 #endif
718   /* clipping */
719   if (r)
720     {
721       [[NSGraphicsContext currentContext] saveGraphicsState];
722       if (n == 2)
723         NSRectClipList (r, 2);
724       else
725         NSRectClip (*r);
726       gsaved = YES;
727     }
731 static void
732 ns_unfocus (struct frame *f)
733 /* --------------------------------------------------------------------------
734      Internal: Remove focus on given frame
735    -------------------------------------------------------------------------- */
737 //  NSTRACE (ns_unfocus);
739   if (gsaved)
740     {
741       [[NSGraphicsContext currentContext] restoreGraphicsState];
742       gsaved = NO;
743     }
745   if (f != ns_updating_frame)
746     {
747       if (focus_view != NULL)
748         {
749           [focus_view unlockFocus];
750           [[focus_view window] flushWindow];
751           focus_view = NULL;
752 /*debug_lock--; */
753         }
754     }
758 static void
759 ns_clip_to_row (struct window *w, struct glyph_row *row, int area, BOOL gc)
760 /* --------------------------------------------------------------------------
761      Internal (but parallels other terms): Focus drawing on given row
762    -------------------------------------------------------------------------- */
764   struct frame *f = XFRAME (WINDOW_FRAME (w));
765   NSRect clip_rect;
766   int window_x, window_y, window_width;
768   window_box (w, area, &window_x, &window_y, &window_width, 0);
770   clip_rect.origin.x = window_x - FRAME_INTERNAL_BORDER_WIDTH (f);
771   clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
772   clip_rect.origin.y = max (clip_rect.origin.y, window_y);
773   clip_rect.size.width = window_width + 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
774   clip_rect.size.height = row->visible_height;
776   /* allow a full-height row at the top when requested
777      (used to draw fringe all the way through internal border area) */
778   if (gc && clip_rect.origin.y < 5)
779     {
780       clip_rect.origin.y -= FRAME_INTERNAL_BORDER_WIDTH (f);
781       clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
782     }
784   /* likewise at bottom */
785   if (gc &&
786       FRAME_PIXEL_HEIGHT (f) - (clip_rect.origin.y + clip_rect.size.height) < 5)
787     clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
789   ns_focus (f, &clip_rect, 1);
793 static void
794 ns_ring_bell ()
795 /* --------------------------------------------------------------------------
796      "Beep" routine
797    -------------------------------------------------------------------------- */
799   NSTRACE (ns_ring_bell);
800   if (visible_bell)
801     {
802       NSAutoreleasePool *pool;
803       struct frame *frame = SELECTED_FRAME ();
804       NSView *view;
806       BLOCK_INPUT;
807       pool = [[NSAutoreleasePool alloc] init];
809       view = FRAME_NS_VIEW (frame);
810       if (view != nil)
811         {
812           NSRect r, surr;
813           NSPoint dim = NSMakePoint (128, 128);
815           r = [view bounds];
816           r.origin.x += (r.size.width - dim.x) / 2;
817           r.origin.y += (r.size.height - dim.y) / 2;
818           r.size.width = dim.x;
819           r.size.height = dim.y;
820           surr = NSInsetRect (r, -2, -2);
821           ns_focus (frame, &surr, 1);
822           [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
823           [ns_lookup_indexed_color (NS_FACE_FOREGROUND
824                                       (FRAME_DEFAULT_FACE (frame)), frame) set];
825           NSRectFill (r);
826           [[view window] flushWindow];
827           ns_timeout (150000);
828           [[view window] restoreCachedImage];
829           [[view window] flushWindow];
830           ns_unfocus (frame);
831         }
832       [pool release];
833       UNBLOCK_INPUT;
834     }
835   else
836     {
837       NSBeep ();
838     }
842 static void
843 ns_reset_terminal_modes (struct terminal *terminal)
844 /*  Externally called as hook */
846   NSTRACE (ns_reset_terminal_modes);
850 static void
851 ns_set_terminal_modes (struct terminal *terminal)
852 /*  Externally called as hook */
854   NSTRACE (ns_set_terminal_modes);
859 /* ==========================================================================
861     Frame / window manager related functions
863    ========================================================================== */
866 static void
867 ns_raise_frame (struct frame *f)
868 /* --------------------------------------------------------------------------
869      Bring window to foreground and make it active
870    -------------------------------------------------------------------------- */
872   NSView *view = FRAME_NS_VIEW (f);
873   check_ns ();
874   BLOCK_INPUT;
875   FRAME_SAMPLE_VISIBILITY (f);
876   if (FRAME_VISIBLE_P (f))
877     {
878       [[view window] makeKeyAndOrderFront: NSApp];
879     }
880   UNBLOCK_INPUT;
884 static void
885 ns_lower_frame (struct frame *f)
886 /* --------------------------------------------------------------------------
887      Send window to back
888    -------------------------------------------------------------------------- */
890   NSView *view = FRAME_NS_VIEW (f);
891   check_ns ();
892   BLOCK_INPUT;
893   [[view window] orderBack: NSApp];
894   UNBLOCK_INPUT;
898 static void
899 ns_frame_raise_lower (struct frame *f, int raise)
900 /* --------------------------------------------------------------------------
901      External (hook)
902    -------------------------------------------------------------------------- */
904   NSTRACE (ns_frame_raise_lower);
906   if (raise)
907     ns_raise_frame (f);
908   else
909     ns_lower_frame (f);
913 static void
914 ns_frame_rehighlight (struct frame *frame)
915 /* --------------------------------------------------------------------------
916      External (hook): called on things like window switching within frame
917    -------------------------------------------------------------------------- */
919   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
920   struct frame *old_highlight = dpyinfo->x_highlight_frame;
922   NSTRACE (ns_frame_rehighlight);
923   if (dpyinfo->x_focus_frame)
924     {
925       dpyinfo->x_highlight_frame
926         = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
927            ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
928            : dpyinfo->x_focus_frame);
929       if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
930         {
931           FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
932           dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
933         }
934     }
935   else
936       dpyinfo->x_highlight_frame = 0;
938   if (dpyinfo->x_highlight_frame &&
939          dpyinfo->x_highlight_frame != old_highlight)
940     {
941       if (old_highlight)
942         {
943           x_update_cursor (old_highlight, 1);
944           x_set_frame_alpha (old_highlight);
945         }
946       if (dpyinfo->x_highlight_frame)
947         {
948           x_update_cursor (dpyinfo->x_highlight_frame, 1);
949           x_set_frame_alpha (dpyinfo->x_highlight_frame);
950         }
951     }
955 void
956 x_make_frame_visible (struct frame *f)
957 /* --------------------------------------------------------------------------
958      External: Show the window (X11 semantics)
959    -------------------------------------------------------------------------- */
961   NSTRACE (x_make_frame_visible);
962   /* XXX: at some points in past this was not needed, as the only place that
963      called this (frame.c:Fraise_frame ()) also called raise_lower;
964      if this ends up the case again, comment this out again. */
965   if (!FRAME_VISIBLE_P (f))
966     {
967       f->async_visible = 1;
968       ns_raise_frame (f);
969     }
973 void
974 x_make_frame_invisible (struct frame *f)
975 /* --------------------------------------------------------------------------
976      External: Hide the window (X11 semantics)
977    -------------------------------------------------------------------------- */
979   NSView * view = FRAME_NS_VIEW (f);
980   NSTRACE (x_make_frame_invisible);
981   check_ns ();
982   [[view window] orderOut: NSApp];
983   f->async_visible = 0;
984   f->async_iconified = 0;
988 void
989 x_iconify_frame (struct frame *f)
990 /* --------------------------------------------------------------------------
991      External: Iconify window
992    -------------------------------------------------------------------------- */
994   NSView * view = FRAME_NS_VIEW (f);
995   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
996   NSTRACE (x_iconify_frame);
997   check_ns ();
999   if (dpyinfo->x_highlight_frame == f)
1000     dpyinfo->x_highlight_frame = 0;
1002   if ([[view window] windowNumber] <= 0)
1003     {
1004       /* the window is still deferred.  Make it very small, bring it
1005          on screen and order it out. */
1006       NSRect s = { { 100, 100}, {0, 0} };
1007       NSRect t;
1008       t = [[view window] frame];
1009       [[view window] setFrame: s display: NO];
1010       [[view window] orderBack: NSApp];
1011       [[view window] orderOut: NSApp];
1012       [[view window] setFrame: t display: NO];
1013     }
1014   [[view window] miniaturize: NSApp];
1018 void
1019 x_destroy_window (struct frame *f)
1020 /* --------------------------------------------------------------------------
1021      External: Delete the window
1022    -------------------------------------------------------------------------- */
1024   NSView *view = FRAME_NS_VIEW (f);
1025   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1026   NSTRACE (x_destroy_window);
1027   check_ns ();
1029   [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1031   BLOCK_INPUT;
1033   free_frame_menubar (f);
1035   if (FRAME_FACE_CACHE (f))
1036     free_frame_faces (f);
1038   if (f == dpyinfo->x_focus_frame)
1039     dpyinfo->x_focus_frame = 0;
1040   if (f == dpyinfo->x_highlight_frame)
1041     dpyinfo->x_highlight_frame = 0;
1042   if (f == dpyinfo->mouse_face_mouse_frame)
1043     {
1044       dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
1045       dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
1046       dpyinfo->mouse_face_window = Qnil;
1047       dpyinfo->mouse_face_deferred_gc = 0;
1048       dpyinfo->mouse_face_mouse_frame = 0;
1049     }
1051   xfree (f->output_data.ns);
1053   [[view window] close];
1054   [view release];
1056   ns_window_num--;
1057   UNBLOCK_INPUT;
1061 void
1062 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1063 /* --------------------------------------------------------------------------
1064      External: Position the window
1065    -------------------------------------------------------------------------- */
1067   NSScreen *screen;
1068   NSView *view = FRAME_NS_VIEW (f);
1070   NSTRACE (x_set_offset);
1072   BLOCK_INPUT;
1074   f->left_pos = xoff;
1075   f->top_pos = yoff;
1076 #ifdef NS_IMPL_GNUSTEP
1077   if (xoff < 100)
1078     f->left_pos = 100;  /* don't overlap menu */
1079 #endif
1081   if (view != nil && (screen = [[view window] screen]))
1082     [[view window] setFrameTopLeftPoint:
1083         NSMakePoint (SCREENMAXBOUND (f->left_pos),
1084                      SCREENMAXBOUND ([screen frame].size.height
1085                                      - NS_TOP_POS (f)))];
1086   UNBLOCK_INPUT;
1090 void
1091 x_set_window_size (struct frame *f, int change_grav, int cols, int rows)
1092 /* --------------------------------------------------------------------------
1093      Adjust window pixel size based on given character grid size
1094      Impl is a bit more complex than other terms, need to do some
1095      internal clipping and also pay attention to screen constraints.
1096    -------------------------------------------------------------------------- */
1098   EmacsView *view = FRAME_NS_VIEW (f);
1099   EmacsToolbar *toolbar = [view toolbar];
1100   NSWindow *window = [view window];
1101   NSScreen *screen = [window screen];
1102   NSRect wr = [window frame];
1103   int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1104   int pixelwidth, pixelheight;
1105   static int oldRows, oldCols, oldFontWidth, oldFontHeight;
1106   static int oldTB;
1107   static struct frame *oldF;
1109   NSTRACE (x_set_window_size);
1111   if (view == nil ||
1112       (f == oldF
1113        && rows == oldRows && cols == oldCols
1114        && oldFontWidth == FRAME_COLUMN_WIDTH (f)
1115        && oldFontHeight == FRAME_LINE_HEIGHT (f)
1116        && oldTB == tb))
1117     return;
1119 /*fprintf (stderr, "\tsetWindowSize: %d x %d, font size %d x %d\n", cols, rows, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f)); */
1121   BLOCK_INPUT;
1123   check_frame_size (f, &rows, &cols);
1124   oldF = f;
1125   oldRows = rows;
1126   oldCols = cols;
1127   oldFontWidth = FRAME_COLUMN_WIDTH (f);
1128   oldFontHeight = FRAME_LINE_HEIGHT (f);
1129   oldTB = tb;
1131   f->scroll_bar_actual_width = NS_SCROLL_BAR_WIDTH (f);
1132   compute_fringe_widths (f, 0);
1134   pixelwidth =  FRAME_TEXT_COLS_TO_PIXEL_WIDTH   (f, cols);
1135   pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
1137   /* If we have a toolbar, take its height into account. */
1138   if (tb)
1139     /* NOTE: previously this would generate wrong result if toolbar not
1140              yet displayed and fixing toolbar_height=32 helped, but
1141              now (200903) seems no longer needed */
1142     FRAME_NS_TOOLBAR_HEIGHT (f) =
1143       NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1144         - FRAME_NS_TITLEBAR_HEIGHT (f);
1145   else
1146     FRAME_NS_TOOLBAR_HEIGHT (f) = 0;
1148   wr.size.width = pixelwidth + f->border_width;
1149   wr.size.height = pixelheight + FRAME_NS_TITLEBAR_HEIGHT (f) 
1150                   + FRAME_NS_TOOLBAR_HEIGHT (f);
1152   /* constrain to screen if we can */
1153   if (screen)
1154     {
1155       NSSize sz = [screen visibleFrame].size;
1156       NSSize ez = { wr.size.width - sz.width, wr.size.height - sz.height };
1157       if (ez.width > 0)
1158         {
1159           int cr = ez.width / FRAME_COLUMN_WIDTH (f) + 1;
1160           cols -= cr;
1161           oldCols = cols;
1162           wr.size.width -= cr * FRAME_COLUMN_WIDTH (f);
1163           pixelwidth -= cr * FRAME_COLUMN_WIDTH (f);
1164         }
1165       if (ez.height > 0)
1166         {
1167           int rr = ez.height / FRAME_LINE_HEIGHT (f) + 1;
1168           rows -= rr;
1169           oldRows = rows;
1170           wr.size.height -= rr * FRAME_LINE_HEIGHT (f);
1171           pixelheight -= rr * FRAME_LINE_HEIGHT (f);
1172         }
1173       wr.origin.x = f->left_pos;
1174       wr.origin.y = [screen frame].size.height - NS_TOP_POS (f)
1175         - wr.size.height;
1176     }
1178   [view setRows: rows andColumns: cols];
1179   [window setFrame: wr display: YES];
1181 /*fprintf (stderr, "\tx_set_window_size %d, %d\t%d, %d\n", cols, rows, pixelwidth, pixelheight); */
1183   /* This is a trick to compensate for Emacs' managing the scrollbar area
1184      as a fixed number of standard character columns.  Instead of leaving
1185      blank space for the extra, we chopped it off above.  Now for
1186      left-hand scrollbars, we shift all rendering to the left by the
1187      difference between the real width and Emacs' imagined one.  For
1188      right-hand bars, don't worry about it since the extra is never used.
1189      (Obviously doesn't work for vertically split windows tho..) */
1190   NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1191     ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1192                   - NS_SCROLL_BAR_WIDTH (f), 0)
1193     : NSMakePoint (0, 0);
1194   [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1195   [view setBoundsOrigin: origin];
1197   change_frame_size (f, rows, cols, 0, 1, 0); /* pretend, delay, safe */
1198   FRAME_PIXEL_WIDTH (f) = pixelwidth;
1199   FRAME_PIXEL_HEIGHT (f) = pixelheight;
1200 /*  SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */
1202   mark_window_cursors_off (XWINDOW (f->root_window));
1203   cancel_mouse_face (f);
1205   UNBLOCK_INPUT;
1210 /* ==========================================================================
1212     Color management
1214    ========================================================================== */
1217 NSColor *
1218 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1220   struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1221   if (idx < 1 || idx >= color_table->avail)
1222     return nil;
1223   return color_table->colors[idx];
1227 unsigned long
1228 ns_index_color (NSColor *color, struct frame *f)
1230   struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1231   int idx;
1232   NSNumber *index;
1234   if (!color_table->colors)
1235     {
1236       color_table->size = NS_COLOR_CAPACITY;
1237       color_table->avail = 1; /* skip idx=0 as marker */
1238       color_table->colors
1239         = (NSColor **)xmalloc (color_table->size * sizeof (NSColor *));
1240       color_table->colors[0] = nil;
1241       color_table->empty_indices = [[NSMutableSet alloc] init];
1242     }
1244   /* do we already have this color ? */
1245   {
1246     int i;
1247     for (i = 1; i < color_table->avail; i++)
1248       {
1249         if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1250           {
1251             [color_table->colors[i] retain];
1252             return i;
1253           }
1254       }
1255   }
1257   if ([color_table->empty_indices count] > 0)
1258     {
1259       index = [color_table->empty_indices anyObject];
1260       [color_table->empty_indices removeObject: index];
1261       idx = [index unsignedIntValue];
1262     }
1263   else
1264     {
1265       if (color_table->avail == color_table->size)
1266         {
1267           color_table->size += NS_COLOR_CAPACITY;
1268           color_table->colors
1269             = (NSColor **)xrealloc (color_table->colors,
1270                                     color_table->size * sizeof (NSColor *));
1271         }
1272       idx = color_table->avail++;
1273     }
1275   color_table->colors[idx] = color;
1276   [color retain];
1277 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1278   return idx;
1282 void
1283 ns_free_indexed_color (unsigned long idx, struct frame *f)
1285   struct ns_color_table *color_table;
1286   NSColor *color;
1287   NSNumber *index;
1289   if (!f)
1290     return;
1292   color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1294   if (idx <= 0 || idx >= color_table->size) {
1295     message1("ns_free_indexed_color: Color index out of range.\n");
1296     return;
1297   }
1299   index = [NSNumber numberWithUnsignedInt: idx];
1300   if ([color_table->empty_indices containsObject: index]) {
1301     message1("ns_free_indexed_color: attempt to free already freed color.\n");
1302     return;
1303   }
1305   color = color_table->colors[idx];
1306   [color release];
1307   color_table->colors[idx] = nil;
1308   [color_table->empty_indices addObject: [NSNumber numberWithUnsignedInt: idx]];
1309 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1313 static int
1314 ns_get_color (const char *name, NSColor **col)
1315 /* --------------------------------------------------------------------------
1316      Parse a color name
1317    -------------------------------------------------------------------------- */
1318 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1319    X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1320    See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1322   NSColor *new = nil;
1323   static char hex[20];
1324   int scaling;
1325   float r = -1.0, g, b;
1326   NSString *nsname = [NSString stringWithUTF8String: name];
1328 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1329   BLOCK_INPUT;
1331   if ([nsname isEqualToString: @"ns_selection_color"])
1332     {
1333       nsname = ns_selection_color;
1334       name = [ns_selection_color UTF8String];
1335     }
1337   /* First, check for some sort of numeric specification. */
1338   hex[0] = '\0';
1340   if (name[0] == '0' || name[0] == '1' || name[0] == '.')  /* RGB decimal */
1341     {
1342       NSScanner *scanner = [NSScanner scannerWithString: nsname];
1343       [scanner scanFloat: &r];
1344       [scanner scanFloat: &g];
1345       [scanner scanFloat: &b];
1346     }
1347   else if (!strncmp(name, "rgb:", 4))  /* A newer X11 format -- rgb:r/g/b */
1348     {
1349       strcpy(hex, name + 4);
1350       scaling = (strlen(hex) - 2) / 3;
1351     }
1352   else if (name[0] == '#')        /* An old X11 format; convert to newer */
1353     {
1354       int len = (strlen(name) - 1);
1355       int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1356       int i;
1357       scaling = strlen(name+start) / 3;
1358       for (i=0; i<3; i++) {
1359         strncpy(hex + i * (scaling + 1), name + start + i * scaling, scaling);
1360         hex[(i+1) * (scaling + 1) - 1] = '/';
1361       }
1362       hex[3 * (scaling + 1) - 1] = '\0';
1363     }
1365   if (hex[0])
1366     {
1367       int rr, gg, bb;
1368       float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1369       if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1370         {
1371           r = rr / fscale;
1372           g = gg / fscale;
1373           b = bb / fscale;
1374         }
1375     }
1377   if (r >= 0.0)
1378     {
1379       *col = [NSColor colorWithCalibratedRed: r green: g blue: b alpha: 1.0];
1380       UNBLOCK_INPUT;
1381       return 0;
1382     }
1384   /* Otherwise, color is expected to be from a list */
1385   {
1386     NSEnumerator *lenum, *cenum;
1387     NSString *name;
1388     NSColorList *clist;
1390 #ifdef NS_IMPL_GNUSTEP
1391     /* XXX: who is wrong, the requestor or the implementation? */
1392     if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1393         == NSOrderedSame)
1394       nsname = @"highlightColor";
1395 #endif
1397     lenum = [[NSColorList availableColorLists] objectEnumerator];
1398     while ( (clist = [lenum nextObject]) && new == nil)
1399       {
1400         cenum = [[clist allKeys] objectEnumerator];
1401         while ( (name = [cenum nextObject]) && new == nil )
1402           {
1403             if ([name compare: nsname
1404                       options: NSCaseInsensitiveSearch] == NSOrderedSame )
1405               new = [clist colorWithKey: name];
1406           }
1407       }
1408   }
1410   if (new)
1411     *col = [new colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1412   UNBLOCK_INPUT;
1413   return new ? 0 : 1;
1417 static NSColor *
1418 ns_get_color_default (const char *name, NSColor *dflt)
1419 /* --------------------------------------------------------------------------
1420      Parse a color or use a default value
1421    -------------------------------------------------------------------------- */
1423   NSColor * col;
1425   if (ns_get_color (name, &col))
1426     return dflt;
1427   else
1428     return col;
1433 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1434 /* --------------------------------------------------------------------------
1435      Convert a Lisp string object to a NS color
1436    -------------------------------------------------------------------------- */
1438   NSTRACE (ns_lisp_to_color);
1439   if (STRINGP (color))
1440     return ns_get_color (SDATA (color), col);
1441   else if (SYMBOLP (color))
1442     return ns_get_color (SDATA (SYMBOL_NAME (color)), col);
1443   return 1;
1447 Lisp_Object
1448 ns_color_to_lisp (NSColor *col)
1449 /* --------------------------------------------------------------------------
1450      Convert a color to a lisp string with the RGB equivalent
1451    -------------------------------------------------------------------------- */
1453   CGFloat red, green, blue, alpha, gray;
1454   char buf[1024];
1455   const char *str;
1456   NSTRACE (ns_color_to_lisp);
1458   BLOCK_INPUT;
1459   if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1461       if ((str =[[col colorNameComponent] UTF8String]))
1462         {
1463           UNBLOCK_INPUT;
1464           return build_string ((char *)str);
1465         }
1467     [[col colorUsingColorSpaceName: NSCalibratedRGBColorSpace]
1468         getRed: &red green: &green blue: &blue alpha: &alpha];
1469   if (red ==green && red ==blue)
1470     {
1471       [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1472             getWhite: &gray alpha: &alpha];
1473       snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1474                 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1475       UNBLOCK_INPUT;
1476       return build_string (buf);
1477     }
1479   snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1480             lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1482   UNBLOCK_INPUT;
1483   return build_string (buf);
1487 void
1488 ns_query_color(void *col, XColor *color_def, int setPixel)
1489 /* --------------------------------------------------------------------------
1490          Get ARGB values out of NSColor col and put them into color_def.
1491          If setPixel, set the pixel to a concatenated version.
1492          and set color_def pixel to the resulting index.
1493    -------------------------------------------------------------------------- */
1495   CGFloat r, g, b, a;
1497   [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1498   color_def->red   = r * 65535;
1499   color_def->green = g * 65535;
1500   color_def->blue  = b * 65535;
1502   if (setPixel == YES)
1503     color_def->pixel
1504       = ARGB_TO_ULONG((int)(a*255),
1505                       (int)(r*255), (int)(g*255), (int)(b*255));
1510 ns_defined_color (struct frame *f, char *name, XColor *color_def, int alloc,
1511                   char makeIndex)
1512 /* --------------------------------------------------------------------------
1513          Return 1 if named color found, and set color_def rgb accordingly.
1514          If makeIndex and alloc are nonzero put the color in the color_table,
1515          and set color_def pixel to the resulting index.
1516          If makeIndex is zero, set color_def pixel to ARGB.
1517          Return 0 if not found
1518    -------------------------------------------------------------------------- */
1520   NSColor *temp;
1521   int notFound = ns_get_color (name, &temp);
1523   NSTRACE (ns_defined_color);
1525   if (notFound)
1526     return 0;
1528   if (makeIndex && alloc)
1529       color_def->pixel = ns_index_color(temp, f); /* [temp retain]; */
1531   ns_query_color (temp, color_def, !makeIndex);
1533   return 1;
1537 unsigned long
1538 ns_get_rgb_color (struct frame *f, float r, float g, float b, float a)
1539 /* --------------------------------------------------------------------------
1540     return an autoreleased RGB color
1541    -------------------------------------------------------------------------- */
1543 /*static int c = 1; fprintf (stderr, "color request %d\n", c++); */
1544   if (r < 0.0) r = 0.0;
1545   else if (r > 1.0) r = 1.0;
1546   if (g < 0.0) g = 0.0;
1547   else if (g > 1.0) g = 1.0;
1548   if (b < 0.0) b = 0.0;
1549   else if (b > 1.0) b = 1.0;
1550   if (a < 0.0) a = 0.0;
1551   else if (a > 1.0) a = 1.0;
1552   return (unsigned long) ns_index_color(
1553     [NSColor colorWithCalibratedRed: r green: g blue: b alpha: a], f);
1557 void
1558 x_set_frame_alpha (struct frame *f)
1559 /* --------------------------------------------------------------------------
1560      change the entire-frame transparency
1561    -------------------------------------------------------------------------- */
1563   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1564   EmacsView *view = FRAME_NS_VIEW (f);
1565   double alpha = 1.0;
1566   double alpha_min = 1.0;
1568   if (dpyinfo->x_highlight_frame == f)
1569     alpha = f->alpha[0];
1570   else
1571     alpha = f->alpha[1];
1573   if (FLOATP (Vframe_alpha_lower_limit))
1574     alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1575   else if (INTEGERP (Vframe_alpha_lower_limit))
1576     alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1578   if (alpha < 0.0)
1579     return;
1580   else if (1.0 < alpha)
1581     alpha = 1.0;
1582   else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1583     alpha = alpha_min;
1585 #ifdef NS_IMPL_COCOA
1586   [[view window] setAlphaValue: alpha];
1587 #endif
1591 /* ==========================================================================
1593     Mouse handling
1595    ========================================================================== */
1598 void
1599 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1600 /* --------------------------------------------------------------------------
1601      Programmatically reposition mouse pointer in pixel coordinates
1602    -------------------------------------------------------------------------- */
1604   NSTRACE (x_set_mouse_pixel_position);
1605   ns_raise_frame (f);
1606 #if 0
1607   /* FIXME: this does not work, and what about GNUstep? */
1608 #ifdef NS_IMPL_COCOA
1609   [FRAME_NS_VIEW (f) lockFocus];
1610   PSsetmouse ((float)pix_x, (float)pix_y);
1611   [FRAME_NS_VIEW (f) unlockFocus];
1612 #endif
1613 #endif
1617 void
1618 x_set_mouse_position (struct frame *f, int h, int v)
1619 /* --------------------------------------------------------------------------
1620      Programmatically reposition mouse pointer in character coordinates
1621    -------------------------------------------------------------------------- */
1623   int pix_x, pix_y;
1625   pix_x = FRAME_COL_TO_PIXEL_X (f, h) + FRAME_COLUMN_WIDTH (f) / 2;
1626   pix_y = FRAME_LINE_TO_PIXEL_Y (f, v) + FRAME_LINE_HEIGHT (f) / 2;
1628   if (pix_x < 0) pix_x = 0;
1629   if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
1631   if (pix_y < 0) pix_y = 0;
1632   if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
1634   x_set_mouse_pixel_position (f, pix_x, pix_y);
1638 static int
1639 note_mouse_movement (struct frame *frame, float x, float y)
1640 /*   ------------------------------------------------------------------------
1641      Called by EmacsView on mouseMovement events.  Passes on
1642      to emacs mainstream code if we moved off of a rect of interest
1643      known as last_mouse_glyph.
1644      ------------------------------------------------------------------------ */
1646 //  NSTRACE (note_mouse_movement);
1648   XSETFRAME (last_mouse_motion_frame, frame);
1650   /* Note, this doesn't get called for enter/leave, since we don't have a
1651      position.  Those are taken care of in the corresponding NSView methods. */
1653   /* has movement gone beyond last rect we were tracking? */
1654   if (x < last_mouse_glyph.origin.x ||
1655       x >= (last_mouse_glyph.origin.x + last_mouse_glyph.size.width) ||
1656       y < last_mouse_glyph.origin.y ||
1657       y >= (last_mouse_glyph.origin.y + last_mouse_glyph.size.height))
1658     {
1659       ns_update_begin(frame);
1660       frame->mouse_moved = 1;
1661       note_mouse_highlight (frame, x, y);
1662       remember_mouse_glyph (frame, x, y, &last_mouse_glyph);
1663       ns_update_end(frame);
1664       return 1;
1665     }
1667   return 0;
1671 static void
1672 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1673                    enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1674                    unsigned long *time)
1675 /* --------------------------------------------------------------------------
1676     External (hook): inform emacs about mouse position and hit parts.
1677     If a scrollbar is being dragged, set bar_window, part, x, y, time.
1678     x & y should be position in the scrollbar (the whole bar, not the handle)
1679     and length of scrollbar respectively
1680    -------------------------------------------------------------------------- */
1682   id view;
1683   NSPoint position;
1684   int xchar, ychar;
1685   Lisp_Object frame, tail;
1686   struct frame *f;
1687   struct ns_display_info *dpyinfo;
1689   NSTRACE (ns_mouse_position);
1691   if (*fp == NULL)
1692     {
1693       fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1694       return;
1695     }
1697   dpyinfo = FRAME_NS_DISPLAY_INFO (*fp);
1699   BLOCK_INPUT;
1701   if (last_mouse_scroll_bar != nil && insist == 0)
1702     {
1703       /* TODO: we do not use this path at the moment because drag events will
1704            go directly to the EmacsScroller.  Leaving code in for now. */
1705       [last_mouse_scroll_bar getMouseMotionPart: (int *)part window: bar_window
1706                                               x: x y: y];
1707       if (time) *time = last_mouse_movement_time;
1708       last_mouse_scroll_bar = nil;
1709     }
1710   else
1711     {
1712       /* Clear the mouse-moved flag for every frame on this display.  */
1713       FOR_EACH_FRAME (tail, frame)
1714         if (FRAME_NS_P (XFRAME (frame))
1715             && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1716           XFRAME (frame)->mouse_moved = 0;
1718       last_mouse_scroll_bar = nil;
1719       if (last_mouse_frame && FRAME_LIVE_P (last_mouse_frame))
1720         f = last_mouse_frame;
1721       else
1722         f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame
1723                                     : SELECTED_FRAME ();
1725       if (f && f->output_data.ns)  /* TODO: 2nd check no longer needed? */
1726         {
1727           view = FRAME_NS_VIEW (*fp);
1729           position = [[view window] mouseLocationOutsideOfEventStream];
1730           position = [view convertPoint: position fromView: nil];
1731           remember_mouse_glyph (f, position.x, position.y, &last_mouse_glyph);
1732 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1734           if (bar_window) *bar_window = Qnil;
1735           if (part) *part = 0; /*scroll_bar_handle; */
1737           if (x) XSETINT (*x, lrint (position.x));
1738           if (y) XSETINT (*y, lrint (position.y));
1739           if (time) *time = last_mouse_movement_time;
1740           *fp = f;
1741         }
1742     }
1744   UNBLOCK_INPUT;
1748 static void
1749 ns_frame_up_to_date (struct frame *f)
1750 /* --------------------------------------------------------------------------
1751     External (hook): Fix up mouse highlighting right after a full update.
1752     Some highlighting was deferred if GC was happening during
1753     note_mouse_highlight (), while other highlighting was deferred for update.
1754    -------------------------------------------------------------------------- */
1756   NSTRACE (ns_frame_up_to_date);
1758   if (FRAME_NS_P (f))
1759     {
1760       struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1761       if ((dpyinfo->mouse_face_deferred_gc||f ==dpyinfo->mouse_face_mouse_frame)
1762       /*&& dpyinfo->mouse_face_mouse_frame*/)
1763         {
1764           BLOCK_INPUT;
1765          ns_update_begin(f);
1766           if (dpyinfo->mouse_face_mouse_frame)
1767             note_mouse_highlight (dpyinfo->mouse_face_mouse_frame,
1768                                   dpyinfo->mouse_face_mouse_x,
1769                                   dpyinfo->mouse_face_mouse_y);
1770           dpyinfo->mouse_face_deferred_gc = 0;
1771          ns_update_end(f);
1772           UNBLOCK_INPUT;
1773         }
1774     }
1778 void
1779 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1780 /* --------------------------------------------------------------------------
1781     External (RIF): set frame mouse pointer type.
1782    -------------------------------------------------------------------------- */
1784   NSTRACE (ns_define_frame_cursor);
1785   if (FRAME_POINTER_TYPE (f) != cursor)
1786     {
1787       EmacsView *view = FRAME_NS_VIEW (f);
1788       FRAME_POINTER_TYPE (f) = cursor;
1789       [[view window] invalidateCursorRectsForView: view];
1790     }
1795 /* ==========================================================================
1797     Keyboard handling
1799    ========================================================================== */
1802 static unsigned
1803 ns_convert_key (unsigned code)
1804 /* --------------------------------------------------------------------------
1805     Internal call used by NSView-keyDown.
1806    -------------------------------------------------------------------------- */
1808   const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym)
1809                                 / sizeof (convert_ns_to_X_keysym[0]));
1810   unsigned keysym;
1811   /* An array would be faster, but less easy to read. */
1812   for (keysym = 0; keysym < last_keysym; keysym += 2)
1813     if (code == convert_ns_to_X_keysym[keysym])
1814       return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
1815   return 0;
1816 /* if decide to use keyCode and Carbon table, use this line:
1817      return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
1821 char *
1822 x_get_keysym_name (int keysym)
1823 /* --------------------------------------------------------------------------
1824     Called by keyboard.c.  Not sure if the return val is important, except
1825     that it be unique.
1826    -------------------------------------------------------------------------- */
1828   static char value[16];
1829   NSTRACE (x_get_keysym_name);
1830   sprintf (value, "%d", keysym);
1831   return value;
1836 /* ==========================================================================
1838     Block drawing operations
1840    ========================================================================== */
1843 static void
1844 ns_redraw_scroll_bars (struct frame *f)
1846   int i;
1847   id view;
1848   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
1849   NSTRACE (ns_judge_scroll_bars);
1850   for (i =[subviews count]-1; i >= 0; i--)
1851     {
1852       view = [subviews objectAtIndex: i];
1853       if (![view isKindOfClass: [EmacsScroller class]]) continue;
1854       [view display];
1855     }
1859 void
1860 ns_clear_frame (struct frame *f)
1861 /* --------------------------------------------------------------------------
1862       External (hook): Erase the entire frame
1863    -------------------------------------------------------------------------- */
1865   NSView *view = FRAME_NS_VIEW (f);
1866   NSRect r;
1868   NSTRACE (ns_clear_frame);
1869   if (ns_in_resize)
1870     return;
1872  /* comes on initial frame because we have
1873     after-make-frame-functions = select-frame */
1874  if (!FRAME_DEFAULT_FACE (f))
1875    return;
1877   mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
1879   output_cursor.hpos = output_cursor.vpos = 0;
1880   output_cursor.x = -1;
1882   r = [view bounds];
1884   BLOCK_INPUT;
1885   ns_focus (f, &r, 1);
1886   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
1887   NSRectFill (r);
1888   ns_unfocus (f);
1890 #ifdef NS_IMPL_COCOA
1891   [[view window] display];  /* redraw resize handle */
1892 #endif
1894   /* as of 2006/11 or so this is now needed */
1895   ns_redraw_scroll_bars (f);
1896   UNBLOCK_INPUT;
1900 void
1901 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
1902 /* --------------------------------------------------------------------------
1903     External (RIF):  Clear section of frame
1904    -------------------------------------------------------------------------- */
1906   NSRect r = NSMakeRect (x, y, width, height);
1907   NSView *view = FRAME_NS_VIEW (f);
1908   struct face *face = FRAME_DEFAULT_FACE (f);
1910   if (!view || !face)
1911     return;
1913   NSTRACE (ns_clear_frame_area);
1915   r = NSIntersectionRect (r, [view frame]);
1916   ns_focus (f, &r, 1);
1917   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
1919 #ifdef NS_IMPL_COCOA
1920   {
1921     /* clip out the resize handle */
1922     NSWindow *window = [FRAME_NS_VIEW (f) window];
1923     NSRect ir
1924       = [view convertRect: ns_resize_handle_rect (window) fromView: nil];
1926     ir = NSIntersectionRect (r, ir);
1927     if (NSIsEmptyRect (ir))
1928       {
1929 #endif
1931   NSRectFill (r);
1933 #ifdef NS_IMPL_COCOA
1934       }
1935     else
1936       {
1937         NSRect r1 = r, r2 = r; /* upper and lower non-intersecting */
1938         r1.size.height -= ir.size.height;
1939         r2.origin.y += r1.size.height;
1940         r2.size.width -= ir.size.width;
1941         r2.size.height = ir.size.height;
1942         NSRectFill (r1);
1943         NSRectFill (r2);
1944       }
1945   }
1946 #endif
1948   ns_unfocus (f);
1949   return;
1953 static void
1954 ns_scroll_run (struct window *w, struct run *run)
1955 /* --------------------------------------------------------------------------
1956     External (RIF):  Insert or delete n lines at line vpos
1957    -------------------------------------------------------------------------- */
1959   struct frame *f = XFRAME (w->frame);
1960   int x, y, width, height, from_y, to_y, bottom_y;
1962   NSTRACE (ns_scroll_run);
1964   /* begin copy from other terms */
1965   /* Get frame-relative bounding box of the text display area of W,
1966      without mode lines.  Include in this box the left and right
1967      fringe of W.  */
1968   window_box (w, -1, &x, &y, &width, &height);
1970   from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
1971   to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
1972   bottom_y = y + height;
1974   if (to_y < from_y)
1975     {
1976       /* Scrolling up.  Make sure we don't copy part of the mode
1977          line at the bottom.  */
1978       if (from_y + run->height > bottom_y)
1979         height = bottom_y - from_y;
1980       else
1981         height = run->height;
1982     }
1983   else
1984     {
1985       /* Scolling down.  Make sure we don't copy over the mode line.
1986          at the bottom.  */
1987       if (to_y + run->height > bottom_y)
1988         height = bottom_y - to_y;
1989       else
1990         height = run->height;
1991     }
1992   /* end copy from other terms */
1994   if (height == 0)
1995       return;
1997   BLOCK_INPUT;
1999   updated_window = w;
2000   x_clear_cursor (w);
2002   {
2003     NSRect srcRect = NSMakeRect (x, from_y, width, height);
2004     NSRect dstRect = NSMakeRect (x, to_y, width, height);
2005     NSPoint dstOrigin = NSMakePoint (x, to_y);
2007     ns_focus (f, &dstRect, 1);
2008     NSCopyBits (0, srcRect , dstOrigin);
2009     ns_unfocus (f);
2010   }
2012   UNBLOCK_INPUT;
2016 static void
2017 ns_after_update_window_line (struct glyph_row *desired_row)
2018 /* --------------------------------------------------------------------------
2019     External (RIF): preparatory to fringe update after text was updated
2020    -------------------------------------------------------------------------- */
2022   struct window *w = updated_window;
2023   struct frame *f;
2024   int width, height;
2026   NSTRACE (ns_after_update_window_line);
2028   /* begin copy from other terms */
2029   xassert (w);
2031   if (!desired_row->mode_line_p && !w->pseudo_window_p)
2032     desired_row->redraw_fringe_bitmaps_p = 1;
2034   /* When a window has disappeared, make sure that no rest of
2035      full-width rows stays visible in the internal border.
2036      Under NS this is drawn inside the fringes. */
2037   if (windows_or_buffers_changed
2038       && (f = XFRAME (w->frame),
2039           width = FRAME_INTERNAL_BORDER_WIDTH (f),
2040           width != 0)
2041       && (height = desired_row->visible_height,
2042           height > 0))
2043     {
2044       int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2046       /* Internal border is drawn below the tool bar.  */
2047       if (WINDOWP (f->tool_bar_window)
2048           && w == XWINDOW (f->tool_bar_window))
2049         y -= width;
2050       /* end copy from other terms */
2052       BLOCK_INPUT;
2053       if (!desired_row->full_width_p)
2054         {
2055           int x1 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2056             + WINDOW_LEFT_FRINGE_WIDTH (w);
2057           int x2 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2058             + FRAME_PIXEL_WIDTH (f) - NS_SCROLL_BAR_WIDTH (f)
2059             - WINDOW_RIGHT_FRINGE_WIDTH (w)
2060             - FRAME_INTERNAL_BORDER_WIDTH (f);
2061           ns_clear_frame_area (f, x1, y, width, height);
2062           ns_clear_frame_area (f, x2, y, width, height);
2063         }
2064       UNBLOCK_INPUT;
2065     }
2069 static void
2070 ns_shift_glyphs_for_insert (struct frame *f,
2071                            int x, int y, int width, int height,
2072                            int shift_by)
2073 /* --------------------------------------------------------------------------
2074     External (RIF): copy an area horizontally, don't worry about clearing src
2075    -------------------------------------------------------------------------- */
2077   NSRect srcRect = NSMakeRect (x, y, width, height);
2078   NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2079   NSPoint dstOrigin = dstRect.origin;
2081   NSTRACE (ns_shift_glyphs_for_insert);
2083   ns_focus (f, &dstRect, 1);
2084   NSCopyBits (0, srcRect, dstOrigin);
2085   ns_unfocus (f);
2090 /* ==========================================================================
2092     Character encoding and metrics
2094    ========================================================================== */
2097 static inline void
2098 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2099 /* --------------------------------------------------------------------------
2100      External (RIF); compute left/right overhang of whole string and set in s
2101    -------------------------------------------------------------------------- */
2103   struct face *face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2104   struct font *font = s->font; /*face->font; */
2106   if (s->char2b)
2107     {
2108       struct font_metrics metrics;
2109       unsigned int codes[2];
2110       codes[0] = *(s->char2b);
2111       codes[1] = *(s->char2b + s->nchars - 1);
2113       font->driver->text_extents (font, codes, 2, &metrics);
2114       s->left_overhang = -metrics.lbearing;
2115       s->right_overhang
2116         = metrics.rbearing > metrics.width
2117         ? metrics.rbearing - metrics.width : 0;
2118     }
2119   else
2120     {
2121       s->left_overhang = 0;
2122       s->right_overhang = ((struct nsfont_info *)font)->ital ?
2123         FONT_HEIGHT (font) * 0.2 : 0;
2124     }
2129 /* ==========================================================================
2131     Fringe and cursor drawing
2133    ========================================================================== */
2136 extern int max_used_fringe_bitmap;
2137 static void
2138 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2139                       struct draw_fringe_bitmap_params *p)
2140 /* --------------------------------------------------------------------------
2141     External (RIF); fringe-related
2142    -------------------------------------------------------------------------- */
2144   struct frame *f = XFRAME (WINDOW_FRAME (w));
2145   struct face *face = p->face;
2146   int rowY;
2147   static EmacsImage **bimgs = NULL;
2148   static int nBimgs = 0;
2149   /* NS-specific: move internal border inside fringe */
2150   int x = p->bx < 0 ? p->x : p->bx;
2151   int wd = p->bx < 0 ? p->wd : p->nx;
2152   BOOL fringeOnVeryLeft
2153     = x - WINDOW_LEFT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w)
2154       - FRAME_INTERNAL_BORDER_WIDTH (f) < 10;
2155   BOOL fringeOnVeryRight
2156     = FRAME_PIXEL_WIDTH (f) - x - wd - FRAME_INTERNAL_BORDER_WIDTH (f)
2157       - WINDOW_RIGHT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w) < 10;
2158   int xAdjust = FRAME_INTERNAL_BORDER_WIDTH (f) *
2159     (fringeOnVeryLeft ? -1 : (fringeOnVeryRight ? 1 : 0));
2161   /* grow bimgs if needed */
2162   if (nBimgs < max_used_fringe_bitmap)
2163     {
2164       EmacsImage **newBimgs
2165         = xmalloc (max_used_fringe_bitmap * sizeof (EmacsImage *));
2166       bzero (newBimgs, max_used_fringe_bitmap * sizeof (EmacsImage *));
2168       if (nBimgs)
2169         {
2170           bcopy (bimgs, newBimgs, nBimgs * sizeof (EmacsImage *));
2171           xfree (bimgs);
2172         }
2174       bimgs = newBimgs;
2175       nBimgs = max_used_fringe_bitmap;
2176     }
2178   /* Must clip because of partially visible lines.  */
2179   rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
2180   if (p->y < rowY)
2181     {
2182       /* Adjust position of "bottom aligned" bitmap on partially
2183          visible last row.  */
2184       int oldY = row->y;
2185       int oldVH = row->visible_height;
2186       row->visible_height = p->h;
2187       row->y -= rowY - p->y;
2188       ns_clip_to_row (w, row, -1, NO);
2189       row->y = oldY;
2190       row->visible_height = oldVH;
2191     }
2192   else
2193     ns_clip_to_row (w, row, -1, YES);
2195   if (p->bx >= 0 && !p->overlay_p)
2196     {
2197       int yAdjust = rowY - FRAME_INTERNAL_BORDER_WIDTH (f) < 5 ?
2198         -FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2199       int yIncr = FRAME_PIXEL_HEIGHT (f) - (p->by+yAdjust + p->ny) < 5 ?
2200         FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2201       if (yAdjust)
2202         yIncr += FRAME_INTERNAL_BORDER_WIDTH (f);
2203       NSRect r = NSMakeRect (p->bx+xAdjust, p->by+yAdjust, p->nx, p->ny+yIncr);
2204       NSRectClip (r);
2205       [ns_lookup_indexed_color(face->background, f) set];
2206       NSRectFill (r);
2207     }
2209   if (p->which)
2210     {
2211       NSRect r = NSMakeRect (p->x+xAdjust, p->y, p->wd, p->h);
2212       NSPoint pt = r.origin;
2213       EmacsImage *img = bimgs[p->which - 1];
2215       if (!img)
2216         {
2217           unsigned short *bits = p->bits + p->dh;
2218           int len = 8 * p->h/8;
2219           int i;
2220           unsigned char *cbits = xmalloc (len);
2222           for (i =0; i<len; i++)
2223             cbits[i] = ~(bits[i] & 0xff);
2224           img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2225                                            flip: NO];
2226           bimgs[p->which - 1] = img;
2227           xfree (cbits);
2228         }
2230       NSRectClip (r);
2231       /* Since we composite the bitmap instead of just blitting it, we need
2232          to erase the whole background. */
2233       [ns_lookup_indexed_color(face->background, f) set];
2234       NSRectFill (r);
2235       pt.y += p->h;
2236       [img setXBMColor: ns_lookup_indexed_color(face->foreground, f)];
2237       [img compositeToPoint: pt operation: NSCompositeSourceOver];
2238     }
2239   ns_unfocus (f);
2243 void
2244 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2245                        int x, int y, int cursor_type, int cursor_width,
2246                        int on_p, int active_p)
2247 /* --------------------------------------------------------------------------
2248      External call (RIF): draw cursor
2249      (modeled after x_draw_window_cursor
2250      FIXME: cursor_width is effectively bogus -- it sometimes gets set
2251      in xdisp.c set_frame_cursor_types, sometimes left uninitialized;
2252      DON'T USE IT (no other terms do)
2253    -------------------------------------------------------------------------- */
2255   NSRect r, s;
2256   int fx, fy, h;
2257   struct frame *f = WINDOW_XFRAME (w);
2258   struct glyph *phys_cursor_glyph;
2259   int overspill;
2261   NSTRACE (dumpcursor);
2262 //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);
2264   if (!on_p)
2265         return;
2267   w->phys_cursor_type = cursor_type;
2268   w->phys_cursor_on_p = on_p;
2270   if (cursor_type == NO_CURSOR)
2271     {
2272       w->phys_cursor_width = 0;
2273       return;
2274     }
2276   if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2277     {
2278       if (glyph_row->exact_window_width_line_p
2279           && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2280         {
2281           glyph_row->cursor_in_fringe_p = 1;
2282           draw_fringe_bitmap (w, glyph_row, 0);
2283         }
2284       return;
2285     }
2287   get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2289   r.origin.x = fx, r.origin.y = fy;
2290   r.size.height = h;
2291   r.size.width = w->phys_cursor_width;
2293   /* FIXME: if we overwrite the internal border area, it does not get erased;
2294      fix by truncating cursor, but better would be to erase properly */
2295   overspill = r.origin.x + r.size.width -
2296     WINDOW_TEXT_TO_FRAME_PIXEL_X (w, WINDOW_BOX_RIGHT_EDGE_X (w) 
2297       - WINDOW_TOTAL_FRINGE_WIDTH (w) - FRAME_INTERNAL_BORDER_WIDTH (f));
2298   if (overspill > 0)
2299     r.size.width -= overspill;
2301   /* TODO: only needed in rare cases with last-resort font in HELLO..
2302      should we do this more efficiently? */
2303   ns_clip_to_row (w, glyph_row, -1, NO); /* do ns_focus(f, &r, 1); if remove */
2304   [FRAME_CURSOR_COLOR (f) set];
2306 #ifdef NS_IMPL_COCOA
2307   /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2308            atomic.  Cleaner ways of doing this should be investigated.
2309            One way would be to set a global variable DRAWING_CURSOR
2310            when making the call to draw_phys..(), don't focus in that
2311            case, then move the ns_unfocus() here after that call. */
2312   NSDisableScreenUpdates ();
2313 #endif
2315   switch (cursor_type)
2316     {
2317     case NO_CURSOR:
2318       break;
2319     case FILLED_BOX_CURSOR:
2320       NSRectFill (r);
2321       break;
2322     case HOLLOW_BOX_CURSOR:
2323       NSRectFill (r);
2324       [FRAME_BACKGROUND_COLOR (f) set];
2325       NSRectFill (NSInsetRect (r, 1, 1));
2326       [FRAME_CURSOR_COLOR (f) set];
2327       break;
2328     case HBAR_CURSOR:
2329       s = r;
2330       s.origin.y += lrint (0.75 * s.size.height);
2331       s.size.height = lrint (s.size.height * 0.25);
2332       NSRectFill (s);
2333       break;
2334     case BAR_CURSOR:
2335       s = r;
2336       s.size.width = min (cursor_width, 2); //FIXME(see above)
2337       NSRectFill (s);
2338       break;
2339     }
2340   ns_unfocus (f);
2342   /* draw the character under the cursor */
2343   if (cursor_type != NO_CURSOR)
2344     draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2346 #ifdef NS_IMPL_COCOA
2347   NSEnableScreenUpdates ();
2348 #endif
2353 static void
2354 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2355 /* --------------------------------------------------------------------------
2356      External (RIF): Draw a vertical line.
2357    -------------------------------------------------------------------------- */
2359   struct frame *f = XFRAME (WINDOW_FRAME (w));
2360   struct face *face;
2361   NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2363   NSTRACE (ns_draw_vertical_window_border);
2365   face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2366   if (face)
2367       [ns_lookup_indexed_color(face->foreground, f) set];
2369   ns_focus (f, &r, 1);
2370   NSRectFill(r);
2371   ns_unfocus (f);
2375 void
2376 show_hourglass (struct atimer *timer)
2378   if (hourglass_shown_p)
2379     return;
2381   BLOCK_INPUT;
2383   /* TODO: add NSProgressIndicator to selected frame (see macfns.c) */
2385   hourglass_shown_p = 1;
2386   UNBLOCK_INPUT;
2390 void
2391 hide_hourglass ()
2393   if (!hourglass_shown_p)
2394     return;
2396   BLOCK_INPUT;
2398   /* TODO: remove NSProgressIndicator from all frames */
2400   hourglass_shown_p = 0;
2401   UNBLOCK_INPUT;
2406 /* ==========================================================================
2408     Glyph drawing operations
2410    ========================================================================== */
2413 static inline NSRect
2414 ns_fix_rect_ibw (NSRect r, int fibw, int frame_pixel_width)
2415 /* --------------------------------------------------------------------------
2416     Under NS we draw internal borders inside fringes, and want full-width
2417     rendering to go all the way to edge.  This function makes that correction.
2418    -------------------------------------------------------------------------- */
2420   if (r.origin.y <= fibw+1)
2421     {
2422       r.size.height += r.origin.y;
2423       r.origin.y = 0;
2424     }
2425   if (r.origin.x <= fibw+1)
2426     {
2427       r.size.width += r.origin.x;
2428       r.origin.x = 0;
2429     }
2430   if (frame_pixel_width - (r.origin.x+r.size.width) <= fibw+1)
2431     r.size.width += fibw;
2433   return r;
2437 static int
2438 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2439 /* --------------------------------------------------------------------------
2440     Wrapper utility to account for internal border width on full-width lines,
2441     and allow top full-width rows to hit the frame top.  nr should be pointer
2442     to two successive NSRects.  Number of rects actually used is returned.
2443    -------------------------------------------------------------------------- */
2445   int n = get_glyph_string_clip_rects (s, nr, 2);
2446   if (s->row->full_width_p)
2447     {
2448       *nr = ns_fix_rect_ibw (*nr, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2449                             FRAME_PIXEL_WIDTH (s->f));
2450       if (n == 2)
2451         *nr = ns_fix_rect_ibw (*(nr+1), FRAME_INTERNAL_BORDER_WIDTH (s->f),
2452                               FRAME_PIXEL_WIDTH (s->f));
2453     }
2454   return n;
2458 static void
2459 ns_draw_box (NSRect r, float thickness, NSColor *col, char left_p, char right_p)
2460 /* --------------------------------------------------------------------------
2461     Draw an unfilled rect inside r, optionally leaving left and/or right open.
2462     Note we can't just use an NSDrawRect command, because of the possibility
2463     of some sides not being drawn, and because the rect will be filled.
2464    -------------------------------------------------------------------------- */
2466   NSRect s = r;
2467   [col set];
2469   /* top, bottom */
2470   s.size.height = thickness;
2471   NSRectFill (s);
2472   s.origin.y += r.size.height - thickness;
2473   NSRectFill (s);
2475   s.size.height = r.size.height;
2476   s.origin.y = r.origin.y;
2478   /* left, right (optional) */
2479   s.size.width = thickness;
2480   if (left_p)
2481     NSRectFill (s);
2482   if (right_p)
2483     {
2484       s.origin.x += r.size.width - thickness;
2485       NSRectFill (s);
2486     }
2490 static void
2491 ns_draw_relief (NSRect r, int thickness, char raised_p,
2492                char top_p, char bottom_p, char left_p, char right_p,
2493                struct glyph_string *s)
2494 /* --------------------------------------------------------------------------
2495     Draw a relief rect inside r, optionally leaving some sides open.
2496     Note we can't just use an NSDrawBezel command, because of the possibility
2497     of some sides not being drawn, and because the rect will be filled.
2498    -------------------------------------------------------------------------- */
2500   static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2501   NSColor *newBaseCol = nil;
2502   NSRect sr = r;
2504   NSTRACE (ns_draw_relief);
2506   /* set up colors */
2508   if (s->face->use_box_color_for_shadows_p)
2509     {
2510       newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2511     }
2512 /*     else if (s->first_glyph->type == IMAGE_GLYPH
2513            && s->img->pixmap
2514            && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2515        {
2516          newBaseCol = IMAGE_BACKGROUND  (s->img, s->f, 0);
2517        } */
2518   else
2519     {
2520       newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2521     }
2523   if (newBaseCol == nil)
2524     newBaseCol = [NSColor grayColor];
2526   if (newBaseCol != baseCol)  /* TODO: better check */
2527     {
2528       [baseCol release];
2529       baseCol = [newBaseCol retain];
2530       [lightCol release];
2531       lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2532       [darkCol release];
2533       darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2534     }
2536   [(raised_p ? lightCol : darkCol) set];
2538   /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2540   /* top */
2541   sr.size.height = thickness;
2542   if (top_p) NSRectFill (sr);
2544   /* left */
2545   sr.size.height = r.size.height;
2546   sr.size.width = thickness;
2547   if (left_p) NSRectFill (sr);
2549   [(raised_p ? darkCol : lightCol) set];
2551   /* bottom */
2552   sr.size.width = r.size.width;
2553   sr.size.height = thickness;
2554   sr.origin.y += r.size.height - thickness;
2555   if (bottom_p) NSRectFill (sr);
2557   /* right */
2558   sr.size.height = r.size.height;
2559   sr.origin.y = r.origin.y;
2560   sr.size.width = thickness;
2561   sr.origin.x += r.size.width - thickness;
2562   if (right_p) NSRectFill (sr);
2566 static void
2567 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2568 /* --------------------------------------------------------------------------
2569       Function modeled after x_draw_glyph_string_box ().
2570       Sets up parameters for drawing.
2571    -------------------------------------------------------------------------- */
2573   int right_x, last_x;
2574   char left_p, right_p;
2575   struct glyph *last_glyph;
2576   NSRect r;
2577   int thickness;
2578   struct face *face;
2580   if (s->hl == DRAW_MOUSE_FACE)
2581     {
2582       face = FACE_FROM_ID
2583         (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2584       if (!face)
2585         face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2586     }
2587   else
2588     face = s->face;
2590   thickness = face->box_line_width;
2592   NSTRACE (ns_dumpglyphs_box_or_relief);
2594   last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2595             ? WINDOW_RIGHT_EDGE_X (s->w)
2596             : window_box_right (s->w, s->area));
2597   last_glyph = (s->cmp || s->img
2598                 ? s->first_glyph : s->first_glyph + s->nchars-1);
2600   right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2601               ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2603   left_p = (s->first_glyph->left_box_line_p
2604             || (s->hl == DRAW_MOUSE_FACE
2605                 && (s->prev == NULL || s->prev->hl != s->hl)));
2606   right_p = (last_glyph->right_box_line_p
2607              || (s->hl == DRAW_MOUSE_FACE
2608                  && (s->next == NULL || s->next->hl != s->hl)));
2610   r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2612   /* expand full-width row over internal borders */
2613   if (s->row->full_width_p)
2614     r = ns_fix_rect_ibw (r, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2615                         FRAME_PIXEL_WIDTH (s->f));
2617   /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
2618   if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
2619     {
2620       ns_draw_box (r, abs (thickness),
2621                    ns_lookup_indexed_color (face->box_color, s->f),
2622                   left_p, right_p);
2623     }
2624   else
2625     {
2626       ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2627                      1, 1, left_p, right_p, s);
2628     }
2632 static void
2633 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2634 /* --------------------------------------------------------------------------
2635       Modeled after x_draw_glyph_string_background, which draws BG in
2636       certain cases.  Others are left to the text rendering routine.
2637    -------------------------------------------------------------------------- */
2639   NSTRACE (ns_maybe_dumpglyphs_background);
2641   if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2642     {
2643       int box_line_width = max (s->face->box_line_width, 0);
2644       if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2645           || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2646         {
2647           struct face *face;
2648           if (s->hl == DRAW_MOUSE_FACE)
2649             {
2650               face = FACE_FROM_ID
2651                 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2652               if (!face)
2653                 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2654             }
2655           else
2656             face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2657           if (!face->stipple)
2658             [(NS_FACE_BACKGROUND (face) != 0
2659               ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2660               : FRAME_BACKGROUND_COLOR (s->f)) set];
2661           else
2662             {
2663               struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (s->f);
2664               [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2665             }
2667           if (s->hl != DRAW_CURSOR)
2668             {
2669               NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2670                                     s->background_width,
2671                                     s->height-2*box_line_width);
2673               /* expand full-width row over internal borders */
2674               if (s->row->full_width_p)
2675                 {
2676                   int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2677                   if (r.origin.y <= fibw+1 + box_line_width)
2678                     {
2679                       r.size.height += r.origin.y;
2680                       r.origin.y = 0;
2681                     }
2682                   if (r.origin.x <= fibw+1)
2683                     {
2684                       r.size.width += 2*r.origin.x;
2685                       r.origin.x = 0;
2686                     }
2687                   if (FRAME_PIXEL_WIDTH (s->f) - (r.origin.x + r.size.width)
2688                       <= fibw+1)
2689                     r.size.width += fibw;
2690                 }
2692               NSRectFill (r);
2693             }
2695           s->background_filled_p = 1;
2696         }
2697     }
2701 static void
2702 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2703 /* --------------------------------------------------------------------------
2704       Renders an image and associated borders.
2705    -------------------------------------------------------------------------- */
2707   EmacsImage *img = s->img->pixmap;
2708   int box_line_vwidth = max (s->face->box_line_width, 0);
2709   int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2710   int bg_x, bg_y, bg_height;
2711   int th;
2712   char raised_p;
2713   NSRect br;
2714   struct face *face;
2716   NSTRACE (ns_dumpglyphs_image);
2718   if (s->face->box != FACE_NO_BOX
2719       && s->first_glyph->left_box_line_p && s->slice.x == 0)
2720     x += abs (s->face->box_line_width);
2722   bg_x = x;
2723   bg_y =  s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2724   bg_height = s->height;
2725   /* other terms have this, but was causing problems w/tabbar mode */
2726   /* - 2 * box_line_vwidth; */
2728   if (s->slice.x == 0) x += s->img->hmargin;
2729   if (s->slice.y == 0) y += s->img->vmargin;
2731   /* Draw BG: if we need larger area than image itself cleared, do that,
2732      otherwise, since we composite the image under NS (instead of mucking
2733      with its background color), we must clear just the image area. */
2734   if (s->hl == DRAW_MOUSE_FACE)
2735     {
2736       face = FACE_FROM_ID
2737        (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2738       if (!face)
2739        face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2740     }
2741   else
2742     face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2744   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
2746   if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
2747       || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
2748     {
2749       br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
2750       s->background_filled_p = 1;
2751     }
2752   else
2753     {
2754       br = NSMakeRect (x, y, s->slice.width, s->slice.height);
2755     }
2757   /* expand full-width row over internal borders */
2758   if (s->row->full_width_p)
2759     {
2760       int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2761       if (br.origin.y <= fibw+1 + box_line_vwidth)
2762         {
2763           br.size.height += br.origin.y;
2764           br.origin.y = 0;
2765         }
2766       if (br.origin.x <= fibw+1 + box_line_vwidth)
2767         {
2768           br.size.width += br.origin.x;
2769           br.origin.x = 0;
2770         }
2771       if (FRAME_PIXEL_WIDTH (s->f) - (br.origin.x + br.size.width) <= fibw+1)
2772         br.size.width += fibw;
2773     }
2775   NSRectFill (br);
2777   /* Draw the image.. do we need to draw placeholder if img ==nil? */
2778   if (img != nil)
2779     [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
2780                 operation: NSCompositeSourceOver];
2782   /* Draw relief, if requested */
2783   if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
2784     {
2785       if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
2786         {
2787           th = tool_bar_button_relief >= 0 ?
2788             tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2789           raised_p = (s->hl == DRAW_IMAGE_RAISED);
2790         }
2791       else
2792         {
2793           th = abs (s->img->relief);
2794           raised_p = (s->img->relief > 0);
2795         }
2797       r.origin.x = x - th;
2798       r.origin.y = y - th;
2799       r.size.width = s->slice.width + 2*th-1;
2800       r.size.height = s->slice.height + 2*th-1;
2801       ns_draw_relief (r, th, raised_p,
2802                       s->slice.y == 0,
2803                       s->slice.y + s->slice.height == s->img->height,
2804                       s->slice.x == 0,
2805                       s->slice.x + s->slice.width == s->img->width, s);
2806     }
2810 static void
2811 ns_dumpglyphs_stretch (struct glyph_string *s)
2813   NSRect r[2];
2814   int n, i;
2815   struct face *face;
2817   if (!s->background_filled_p)
2818     {
2819       n = ns_get_glyph_string_clip_rect (s, r);
2820       *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
2822       for (i=0; i<n; i++)
2823         {
2824           if (!s->row->full_width_p)
2825             {
2826               /* truncate to avoid overwriting fringe and/or scrollbar */
2827               int overrun = max (0, (s->x + s->background_width)
2828                                   - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
2829                                     - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
2830               r[i].size.width -= overrun;
2832               /* XXX: Try to work between problem where a stretch glyph on
2833                  a partially-visible bottom row will clear part of the
2834                  modeline, and another where list-buffers headers and similar
2835                  rows erroneously have visible_height set to 0.  Not sure
2836                  where this is coming from as other terms seem not to show. */
2837               r[i].size.height = min (s->height, s->row->visible_height);
2838             }
2840           /* expand full-width rows over internal borders */
2841           else
2842             {
2843               r[i] = ns_fix_rect_ibw (r[i], FRAME_INTERNAL_BORDER_WIDTH (s->f),
2844                                       FRAME_PIXEL_WIDTH (s->f));
2845             }
2847           /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
2848              overwriting cursor (usually when cursor on a tab) */
2849           if (s->hl == DRAW_CURSOR)
2850             {
2851               r[i].origin.x += s->width;
2852               r[i].size.width -= s->width;
2853             }
2854         }
2856       ns_focus (s->f, r, n);
2858       if (s->hl == DRAW_MOUSE_FACE)
2859        {
2860          face = FACE_FROM_ID
2861            (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2862          if (!face)
2863            face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2864        }
2865       else
2866        face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2868       [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
2870       NSRectFill (r[0]);
2871       NSRectFill (r[1]);
2872       ns_unfocus (s->f);
2873       s->background_filled_p = 1;
2874     }
2878 static void
2879 ns_draw_glyph_string (struct glyph_string *s)
2880 /* --------------------------------------------------------------------------
2881       External (RIF): Main draw-text call.
2882    -------------------------------------------------------------------------- */
2884   /* TODO (optimize): focus for box and contents draw */
2885   NSRect r[2];
2886   int n;
2887   char box_drawn_p = 0;
2889   NSTRACE (ns_draw_glyph_string);
2891   if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
2892     {
2893       int width;
2894       struct glyph_string *next;
2896       for (width = 0, next = s->next;
2897            next && width < s->right_overhang;
2898            width += next->width, next = next->next)
2899         if (next->first_glyph->type != IMAGE_GLYPH)
2900           {
2901             if (next->first_glyph->type != STRETCH_GLYPH)
2902               {
2903                 n = ns_get_glyph_string_clip_rect (s->next, r);
2904                 ns_focus (s->f, r, n);
2905                 ns_maybe_dumpglyphs_background (s->next, 1);
2906                 ns_unfocus (s->f);
2907               }
2908             else
2909               {
2910                 ns_dumpglyphs_stretch (s->next);
2911               }
2912             next->num_clips = 0;
2913           }
2914     }
2916   if (!s->for_overlaps && s->face->box != FACE_NO_BOX
2917         && (s->first_glyph->type == CHAR_GLYPH
2918             || s->first_glyph->type == COMPOSITE_GLYPH))
2919     {
2920       n = ns_get_glyph_string_clip_rect (s, r);
2921       ns_focus (s->f, r, n);
2922       ns_maybe_dumpglyphs_background (s, 1);
2923       ns_dumpglyphs_box_or_relief (s);
2924       ns_unfocus (s->f);
2925       box_drawn_p = 1;
2926     }
2928   switch (s->first_glyph->type)
2929     {
2931     case IMAGE_GLYPH:
2932       n = ns_get_glyph_string_clip_rect (s, r);
2933       ns_focus (s->f, r, n);
2934       ns_dumpglyphs_image (s, r[0]);
2935       ns_unfocus (s->f);
2936       break;
2938     case STRETCH_GLYPH:
2939       ns_dumpglyphs_stretch (s);
2940       break;
2942     case CHAR_GLYPH:
2943     case COMPOSITE_GLYPH:
2944       n = ns_get_glyph_string_clip_rect (s, r);
2945       ns_focus (s->f, r, n);
2947       if (s->for_overlaps || (s->cmp_from > 0
2948                               && ! s->first_glyph->u.cmp.automatic))
2949         s->background_filled_p = 1;
2950       else
2951         ns_maybe_dumpglyphs_background
2952           (s, s->first_glyph->type == COMPOSITE_GLYPH);
2954       ns_tmp_flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
2955                     (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
2956                      (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
2957                       NS_DUMPGLYPH_NORMAL));
2958       ns_tmp_font = (struct nsfont_info *)s->face->font;
2959       if (ns_tmp_font == NULL)
2960           ns_tmp_font = (struct nsfont_info *)FRAME_FONT (s->f);
2962       ns_tmp_font->font.driver->draw
2963         (s, 0, s->nchars, s->x, s->y,
2964          (ns_tmp_flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
2965          || ns_tmp_flags == NS_DUMPGLYPH_MOUSEFACE);
2967       ns_unfocus (s->f);
2968       break;
2970     default:
2971       abort ();
2972     }
2974   /* Draw box if not done already. */
2975   if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
2976     {
2977       n = ns_get_glyph_string_clip_rect (s, r);
2978       ns_focus (s->f, r, n);
2979       ns_dumpglyphs_box_or_relief (s);
2980       ns_unfocus (s->f);
2981     }
2983   s->num_clips = 0;
2988 /* ==========================================================================
2990     Event loop
2992    ========================================================================== */
2995 static void
2996 ns_send_appdefined (int value)
2997 /* --------------------------------------------------------------------------
2998     Internal: post an appdefined event which EmacsApp-sendEvent will
2999               recognize and take as a command to halt the event loop.
3000    -------------------------------------------------------------------------- */
3002   /*NSTRACE (ns_send_appdefined); */
3004   /* Only post this event if we haven't already posted one.  This will end
3005        the [NXApp run] main loop after having processed all events queued at
3006        this moment.  */
3007   if (send_appdefined)
3008     {
3009       NSEvent *nxev;
3011       /* We only need one NX_APPDEFINED event to stop NXApp from running.  */
3012       send_appdefined = NO;
3014       /* Don't need wakeup timer any more */
3015       if (timed_entry)
3016         {
3017           [timed_entry invalidate];
3018           [timed_entry release];
3019           timed_entry = nil;
3020         }
3022       /* Ditto for file descriptor poller */
3023       if (fd_entry)
3024         {
3025           [fd_entry invalidate];
3026           [fd_entry release];
3027           fd_entry = nil;
3028         }
3030       nxev = [NSEvent otherEventWithType: NSApplicationDefined
3031                                 location: NSMakePoint (0, 0)
3032                            modifierFlags: 0
3033                                timestamp: 0
3034                             windowNumber: [[NSApp mainWindow] windowNumber]
3035                                  context: [NSApp context]
3036                                  subtype: 0
3037                                    data1: value
3038                                    data2: 0];
3040       /* Post an application defined event on the event queue.  When this is
3041          received the [NXApp run] will return, thus having processed all
3042          events which are currently queued.  */
3043       [NSApp postEvent: nxev atStart: NO];
3044     }
3048 static int
3049 ns_read_socket (struct terminal *terminal, int expected,
3050                 struct input_event *hold_quit)
3051 /* --------------------------------------------------------------------------
3052      External (hook): Post an event to ourself and keep reading events until
3053      we read it back again.  In effect process all events which were waiting.
3054      From 21+ we have to manage the event buffer ourselves.
3055    -------------------------------------------------------------------------- */
3057   struct input_event ev;
3058   int nevents;
3060 /* NSTRACE (ns_read_socket); */
3062   if (interrupt_input_blocked)
3063     {
3064       interrupt_input_pending = 1;
3065 #ifdef SYNC_INPUT
3066       pending_signals = 1;
3067 #endif
3068       return -1;
3069     }
3071   interrupt_input_pending = 0;
3072 #ifdef SYNC_INPUT
3073   pending_signals = pending_atimers;
3074 #endif
3076   BLOCK_INPUT;
3077   n_emacs_events_pending = 0;
3078   EVENT_INIT (ev);
3079   emacs_event = &ev;
3080   q_event_ptr = hold_quit;
3082   /* we manage autorelease pools by allocate/reallocate each time around
3083      the loop; strict nesting is occasionally violated but seems not to
3084      matter.. earlier methods using full nesting caused major memory leaks */
3085   [outerpool release];
3086   outerpool = [[NSAutoreleasePool alloc] init];
3088   /* If have pending open-file requests, attend to the next one of those. */
3089   if (ns_pending_files && [ns_pending_files count] != 0
3090       && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3091     {
3092       [ns_pending_files removeObjectAtIndex: 0];
3093     }
3094   /* Deal with pending service requests. */
3095   else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3096     && [(EmacsApp *)
3097          NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3098                       withArg: [ns_pending_service_args objectAtIndex: 0]])
3099     {
3100       [ns_pending_service_names removeObjectAtIndex: 0];
3101       [ns_pending_service_args removeObjectAtIndex: 0];
3102     }
3103   else
3104     {
3105       /* Run and wait for events.  We must always send one NX_APPDEFINED event
3106          to ourself, otherwise [NXApp run] will never exit.  */
3107       send_appdefined = YES;
3109       /* If called via ns_select, this is called once with expected=1,
3110          because we expect either the timeout or file descriptor activity.
3111          In this case the first event through will either be real input or
3112          one of these.  read_avail_input() then calls once more with expected=0
3113          and in that case we need to return quickly if there is nothing.
3114          If we're being called outside of that, it's also OK to return quickly
3115          after one iteration through the event loop, since other terms do
3116          this and emacs expects it. */
3117       if (!(inNsSelect && expected))
3118         {
3119           /* Post an application defined event on the event queue.  When this is
3120              received the [NXApp run] will return, thus having processed all
3121              events which are currently queued, if any.  */
3122           ns_send_appdefined (-1);
3123         }
3125       [NSApp run];
3126     }
3128   nevents = n_emacs_events_pending;
3129   n_emacs_events_pending = 0;
3130   emacs_event = q_event_ptr = NULL;
3131   UNBLOCK_INPUT;
3133   return nevents;
3138 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3139            fd_set *exceptfds, struct timeval *timeout)
3140 /* --------------------------------------------------------------------------
3141      Replacement for select, checking for events
3142    -------------------------------------------------------------------------- */
3144   int result;
3145   double time;
3146   NSEvent *ev;
3147 /*  NSTRACE (ns_select); */
3149   if (NSApp == nil || inNsSelect == 1 /* || ([NSApp isActive] == NO &&
3150                       [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
3151  inMode:NSDefaultRunLoopMode dequeue:NO] == nil) */)
3152     return select (nfds, readfds, writefds, exceptfds, timeout);
3154   /* Save file descriptor set, which gets overwritten in calls to select ()
3155      Note, this is called from process.c, and only readfds is ever set */
3156   if (readfds)
3157     {
3158       memcpy (&select_readfds, readfds, sizeof (fd_set));
3159       select_nfds = nfds;
3160     }
3161   else
3162     select_nfds = 0;
3164     /* Try an initial select for pending data on input files */
3165   select_timeout.tv_sec = select_timeout.tv_usec = 0;
3166   result = select (nfds, readfds, writefds, exceptfds, &select_timeout);
3167   if (result)
3168     return result;
3170   /* if (!timeout || timed_entry || fd_entry)
3171        fprintf (stderr, "assertion failed: timeout null or timed_entry/fd_entry non-null in ns_select\n"); */
3173     /* set a timeout and run the main AppKit event loop while continuing
3174        to monitor the files */
3175   time = ((double) timeout->tv_sec) + ((double) timeout->tv_usec)/1000000.0;
3176   timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3177                                            target: NSApp
3178                                          selector: @selector (timeout_handler:)
3179                                          userInfo: 0
3180                                           repeats: YES] /* for safe removal */
3181                                                          retain];
3183   /* set a periodic task to try the select () again */
3184   fd_entry = [[NSTimer scheduledTimerWithTimeInterval: 0.1
3185                                                target: NSApp
3186                                              selector: @selector (fd_handler:)
3187                                              userInfo: 0
3188                                               repeats: YES]
3189                retain];
3191   /* Let Application dispatch events until it receives an event of the type
3192      NX_APPDEFINED, which should only be sent by timeout_handler.
3193      We tell read_avail_input() that input is "expected" because we do expect
3194      either the timeout or fd handler to fire, and if they don't, the original
3195      call from process.c that got us here expects us to wait until some input
3196      comes. */
3197   inNsSelect = 1;
3198   gobble_input (1);
3199   ev = last_appdefined_event;
3200   inNsSelect = 0;
3202   if (ev)
3203     {
3204       int t;
3205       if ([ev type] != NSApplicationDefined)
3206         abort ();
3208       t = [ev data1];
3209       last_appdefined_event = 0;
3211       if (t == -2)
3212         {
3213           /* The NX_APPDEFINED event we received was a timeout. */
3214           return 0;
3215         }
3216       else if (t == -1)
3217         {
3218           /* The NX_APPDEFINED event we received was the result of
3219              at least one real input event arriving.  */
3220           errno = EINTR;
3221           return -1;
3222         }
3223       else
3224         {
3225           /* Received back from select () in fd_handler; copy the results */
3226           if (readfds)
3227             memcpy (readfds, &select_readfds, sizeof (fd_set));
3228           return t;
3229         }
3230     }
3231   /* never reached, shut compiler up */
3232   return 0;
3237 /* ==========================================================================
3239     Scrollbar handling
3241    ========================================================================== */
3244 static void
3245 ns_set_vertical_scroll_bar (struct window *window,
3246                            int portion, int whole, int position)
3247 /* --------------------------------------------------------------------------
3248       External (hook): Update or add scrollbar
3249    -------------------------------------------------------------------------- */
3251   Lisp_Object win;
3252   NSRect r, v;
3253   struct frame *f = XFRAME (WINDOW_FRAME (window));
3254   EmacsView *view = FRAME_NS_VIEW (f);
3255   int window_y, window_height;
3256   BOOL barOnVeryLeft, barOnVeryRight;
3257   int top, left, height, width, sb_width, sb_left;
3258   EmacsScroller *bar;
3259 static int count = 0;
3261   /* optimization; display engine sends WAY too many of these.. */
3262   if (!NILP (window->vertical_scroll_bar))
3263     {
3264       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3265       if ([bar checkSamePosition: position portion: portion whole: whole])
3266         {
3267           if (view->scrollbarsNeedingUpdate == 0)
3268             {
3269               if (!windows_or_buffers_changed)
3270                   return;
3271             }
3272           else
3273             view->scrollbarsNeedingUpdate--;
3274         }
3275     }
3277   NSTRACE (ns_set_vertical_scroll_bar);
3279   /* Get dimensions.  */
3280   window_box (window, -1, 0, &window_y, 0, &window_height);
3281   top = window_y;
3282   height = window_height;
3283   width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3284   left = WINDOW_SCROLL_BAR_AREA_X (window);
3286   if (top < 5) /* top scrollbar adjustment */
3287     {
3288       top -= FRAME_INTERNAL_BORDER_WIDTH (f);
3289       height += FRAME_INTERNAL_BORDER_WIDTH (f);
3290     }
3292   /* allow for displaying a skinnier scrollbar than char area allotted */
3293   sb_width = (WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) > 0) ?
3294     WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) : width;
3296   barOnVeryLeft = left < 5;
3297   barOnVeryRight = FRAME_PIXEL_WIDTH (f) - left - width < 5;
3298   sb_left = left + FRAME_INTERNAL_BORDER_WIDTH (f)
3299       * (barOnVeryLeft ? -1 : (barOnVeryRight ? 1 : 0));
3301   r = NSMakeRect (sb_left, top, sb_width, height);
3302   /* the parent view is flipped, so we need to flip y value */
3303   v = [view frame];
3304   r.origin.y = (v.size.height - r.size.height - r.origin.y);
3306   XSETWINDOW (win, window);
3307   BLOCK_INPUT;
3309   /* we want at least 5 lines to display a scrollbar */
3310   if (WINDOW_TOTAL_LINES (window) < 5)
3311     {
3312       if (!NILP (window->vertical_scroll_bar))
3313         {
3314           bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3315           [bar removeFromSuperview];
3316           window->vertical_scroll_bar = Qnil;
3317         }
3318       ns_clear_frame_area (f, sb_left, top, width, height);
3319       UNBLOCK_INPUT;
3320       return;
3321     }
3323   if (NILP (window->vertical_scroll_bar))
3324     {
3325       ns_clear_frame_area (f, sb_left, top, width, height);
3326       bar = [[EmacsScroller alloc] initFrame: r window: win];
3327       window->vertical_scroll_bar = make_save_value (bar, 0);
3328     }
3329   else
3330     {
3331       NSRect oldRect;
3332       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3333       oldRect = [bar frame];
3334       r.size.width = oldRect.size.width;
3335       if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3336         {
3337           if (oldRect.origin.x != r.origin.x)
3338               ns_clear_frame_area (f, sb_left, top, width, height);
3339           [bar setFrame: r];
3340         }
3341     }
3343   [bar setPosition: position portion: portion whole: whole];
3344   UNBLOCK_INPUT;
3348 static void
3349 ns_condemn_scroll_bars (struct frame *f)
3350 /* --------------------------------------------------------------------------
3351      External (hook): arrange for all frame's scrollbars to be removed
3352      at next call to judge_scroll_bars, except for those redeemed.
3353    -------------------------------------------------------------------------- */
3355   int i;
3356   id view;
3357   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3359   NSTRACE (ns_condemn_scroll_bars);
3361   for (i =[subviews count]-1; i >= 0; i--)
3362     {
3363       view = [subviews objectAtIndex: i];
3364       if ([view isKindOfClass: [EmacsScroller class]])
3365         [view condemn];
3366     }
3370 static void
3371 ns_redeem_scroll_bar (struct window *window)
3372 /* --------------------------------------------------------------------------
3373      External (hook): arrange to spare this window's scrollbar
3374      at next call to judge_scroll_bars.
3375    -------------------------------------------------------------------------- */
3377   id bar;
3378   NSTRACE (ns_redeem_scroll_bar);
3379   if (!NILP (window->vertical_scroll_bar))
3380     {
3381       bar =XNS_SCROLL_BAR (window->vertical_scroll_bar);
3382       [bar reprieve];
3383     }
3387 static void
3388 ns_judge_scroll_bars (struct frame *f)
3389 /* --------------------------------------------------------------------------
3390      External (hook): destroy all scrollbars on frame that weren't
3391      redeemed after call to condemn_scroll_bars.
3392    -------------------------------------------------------------------------- */
3394   int i;
3395   id view;
3396   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3397   NSTRACE (ns_judge_scroll_bars);
3398   for (i =[subviews count]-1; i >= 0; i--)
3399     {
3400       view = [subviews objectAtIndex: i];
3401       if (![view isKindOfClass: [EmacsScroller class]]) continue;
3402       [view judge];
3403     }
3407 void
3408 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
3410   /* XXX irrelevant under NS */
3415 /* ==========================================================================
3417     Initialization
3419    ========================================================================== */
3422 x_display_pixel_height (dpyinfo)
3423      struct ns_display_info *dpyinfo;
3425   NSScreen *screen = [NSScreen mainScreen];
3426   return [screen frame].size.height;
3430 x_display_pixel_width (dpyinfo)
3431      struct ns_display_info *dpyinfo;
3433   NSScreen *screen = [NSScreen mainScreen];
3434   return [screen frame].size.width;
3438 static Lisp_Object ns_string_to_lispmod (const char *s)
3439 /* --------------------------------------------------------------------------
3440      Convert modifier name to lisp symbol
3441    -------------------------------------------------------------------------- */
3443   if (!strncmp (SDATA (SYMBOL_NAME (Qmeta)), s, 10))
3444     return Qmeta;
3445   else if (!strncmp (SDATA (SYMBOL_NAME (Qsuper)), s, 10))
3446     return Qsuper;
3447   else if (!strncmp (SDATA (SYMBOL_NAME (Qcontrol)), s, 10))
3448     return Qcontrol;
3449   else if (!strncmp (SDATA (SYMBOL_NAME (Qalt)), s, 10))
3450     return Qalt;
3451   else if (!strncmp (SDATA (SYMBOL_NAME (Qhyper)), s, 10))
3452     return Qhyper;
3453   else if (!strncmp (SDATA (SYMBOL_NAME (Qnone)), s, 10))
3454     return Qnone;
3455   else
3456     return Qnil;
3460 static Lisp_Object ns_mod_to_lisp (int m)
3461 /* --------------------------------------------------------------------------
3462      Convert modifier code (see lisp.h) to lisp symbol
3463    -------------------------------------------------------------------------- */
3465   if (m == CHAR_META)
3466     return Qmeta;
3467   else if (m == CHAR_SUPER)
3468     return Qsuper;
3469   else if (m == CHAR_CTL)
3470     return Qcontrol;
3471   else if (m == CHAR_ALT)
3472     return Qalt;
3473   else if (m == CHAR_HYPER)
3474     return Qhyper;
3475   else /* if (m == 0) */
3476     return Qnone;
3480 static void
3481 ns_set_default_prefs ()
3482 /* --------------------------------------------------------------------------
3483       Initialize preference variables to defaults
3484    -------------------------------------------------------------------------- */
3486   ns_alternate_modifier = Qmeta;
3487   ns_command_modifier = Qsuper;
3488   ns_control_modifier = Qcontrol;
3489   ns_function_modifier = Qnone;
3490   ns_antialias_text = Qt;
3491   ns_antialias_threshold = 10.0; /* not exposed to lisp side */
3492   ns_confirm_quit = Qnil;
3496 static void
3497 ns_default (const char *parameter, Lisp_Object *result,
3498            Lisp_Object yesval, Lisp_Object noval,
3499            BOOL is_float, BOOL is_modstring)
3500 /* --------------------------------------------------------------------------
3501       Check a parameter value in user's preferences
3502    -------------------------------------------------------------------------- */
3504   const char *value;
3506   if ( (value =[[[NSUserDefaults standardUserDefaults]
3507                    stringForKey: [NSString stringWithUTF8String: parameter]]
3508                 UTF8String]) )
3509     {
3510       double f;
3511       char *pos;
3512       if (strcasecmp (value, "YES") == 0)
3513         *result = yesval;
3514       else if (strcasecmp (value, "NO") == 0)
3515         *result = noval;
3516       else if (is_float && (f = strtod (value, &pos), pos != value))
3517         *result = make_float (f);
3518       else if (is_modstring && value)
3519         *result = ns_string_to_lispmod (value);
3520       else fprintf (stderr,
3521                    "Bad value for default \"%s\": \"%s\"\n", parameter, value);
3522     }
3526 void
3527 ns_initialize_display_info (struct ns_display_info *dpyinfo)
3528 /* --------------------------------------------------------------------------
3529       Initialize global info and storage for display.
3530    -------------------------------------------------------------------------- */
3532     NSScreen *screen = [NSScreen mainScreen];
3533     NSWindowDepth depth = [screen depth];
3535     dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
3536     dpyinfo->resy = 72.27;
3537     dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
3538                                                   NSColorSpaceFromDepth (depth)]
3539                 && ![NSCalibratedWhiteColorSpace isEqualToString:
3540                                                  NSColorSpaceFromDepth (depth)];
3541     dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
3542     dpyinfo->image_cache = make_image_cache ();
3543     dpyinfo->color_table
3544       = (struct ns_color_table *)xmalloc (sizeof (struct ns_color_table));
3545     dpyinfo->color_table->colors = NULL;
3546     dpyinfo->root_window = 42; /* a placeholder.. */
3548     dpyinfo->mouse_face_mouse_frame = NULL;
3549     dpyinfo->mouse_face_deferred_gc = 0;
3550     dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
3551     dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
3552     dpyinfo->mouse_face_face_id = DEFAULT_FACE_ID;
3553     dpyinfo->mouse_face_window = dpyinfo->mouse_face_overlay = Qnil;
3554     dpyinfo->mouse_face_hidden = 0;
3556     dpyinfo->mouse_face_mouse_x = dpyinfo->mouse_face_mouse_y = 0;
3557     dpyinfo->mouse_face_defer = 0;
3559     dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
3561     dpyinfo->n_fonts = 0;
3562     dpyinfo->smallest_font_height = 1;
3563     dpyinfo->smallest_char_width = 1;
3567 /* This and next define (many of the) public functions in this file. */
3568 /* x_... are generic versions in xdisp.c that we, and other terms, get away
3569          with using despite presence in the "system dependent" redisplay
3570          interface.  In addition, many of the ns_ methods have code that is
3571          shared with all terms, indicating need for further refactoring. */
3572 extern frame_parm_handler ns_frame_parm_handlers[];
3573 static struct redisplay_interface ns_redisplay_interface =
3575   ns_frame_parm_handlers,
3576   x_produce_glyphs,
3577   x_write_glyphs,
3578   x_insert_glyphs,
3579   x_clear_end_of_line,
3580   ns_scroll_run,
3581   ns_after_update_window_line,
3582   ns_update_window_begin,
3583   ns_update_window_end,
3584   x_cursor_to,
3585   ns_flush,
3586   0, /* flush_display_optional */
3587   x_clear_window_mouse_face,
3588   x_get_glyph_overhangs,
3589   x_fix_overlapping_area,
3590   ns_draw_fringe_bitmap,
3591   0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
3592   0, /* destroy_fringe_bitmap */
3593   ns_compute_glyph_string_overhangs,
3594   ns_draw_glyph_string, /* interface to nsfont.m */
3595   ns_define_frame_cursor,
3596   ns_clear_frame_area,
3597   ns_draw_window_cursor,
3598   ns_draw_vertical_window_border,
3599   ns_shift_glyphs_for_insert
3603 static void
3604 ns_delete_display (struct ns_display_info *dpyinfo)
3606   /* TODO... */
3610 /* This function is called when the last frame on a display is deleted. */
3611 static void
3612 ns_delete_terminal (struct terminal *terminal)
3614   struct ns_display_info *dpyinfo = terminal->display_info.ns;
3615   int i;
3617   /* Protect against recursive calls.  delete_frame in
3618      delete_terminal calls us back when it deletes our last frame.  */
3619   if (!terminal->name)
3620     return;
3622   BLOCK_INPUT;
3624   x_destroy_all_bitmaps (dpyinfo);
3625   ns_delete_display (dpyinfo);
3626   UNBLOCK_INPUT;
3630 static struct terminal *
3631 ns_create_terminal (struct ns_display_info *dpyinfo)
3632 /* --------------------------------------------------------------------------
3633       Set up use of NS before we make the first connection.
3634    -------------------------------------------------------------------------- */
3636   struct terminal *terminal;
3638   NSTRACE (ns_create_terminal);
3640   terminal = create_terminal ();
3642   terminal->type = output_ns;
3643   terminal->display_info.ns = dpyinfo;
3644   dpyinfo->terminal = terminal;
3646   terminal->rif = &ns_redisplay_interface;
3648   terminal->clear_frame_hook = ns_clear_frame;
3649   terminal->ins_del_lines_hook = 0; /* XXX vestigial? */
3650   terminal->delete_glyphs_hook = 0; /* XXX vestigial? */
3651   terminal->ring_bell_hook = ns_ring_bell;
3652   terminal->reset_terminal_modes_hook = ns_reset_terminal_modes;
3653   terminal->set_terminal_modes_hook = ns_set_terminal_modes;
3654   terminal->update_begin_hook = ns_update_begin;
3655   terminal->update_end_hook = ns_update_end;
3656   terminal->set_terminal_window_hook = NULL; /* XXX vestigial? */
3657   terminal->read_socket_hook = ns_read_socket;
3658   terminal->frame_up_to_date_hook = ns_frame_up_to_date;
3659   terminal->mouse_position_hook = ns_mouse_position;
3660   terminal->frame_rehighlight_hook = ns_frame_rehighlight;
3661   terminal->frame_raise_lower_hook = ns_frame_raise_lower;
3663   terminal->fullscreen_hook = 0; /* see XTfullscreen_hook */
3665   terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
3666   terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
3667   terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
3668   terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
3670   terminal->delete_frame_hook = x_destroy_window;
3671   terminal->delete_terminal_hook = ns_delete_terminal;
3673   terminal->scroll_region_ok = 1;
3674   terminal->char_ins_del_ok = 1;
3675   terminal->line_ins_del_ok = 1;
3676   terminal->fast_clear_end_of_line = 1;
3677   terminal->memory_below_frame = 0;
3679   return terminal;
3683 struct ns_display_info *
3684 ns_term_init (Lisp_Object display_name)
3685 /* --------------------------------------------------------------------------
3686      Start the Application and get things rolling.
3687    -------------------------------------------------------------------------- */
3689   struct terminal *terminal;
3690   struct ns_display_info *dpyinfo;
3691   static int ns_initialized = 0;
3692   Lisp_Object tmp;
3694   NSTRACE (ns_term_init);
3696   /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
3697   /*GSDebugAllocationActive (YES); */
3698   BLOCK_INPUT;
3699   handling_signal = 0;
3701   if (!ns_initialized)
3702     {
3703       baud_rate = 38400;
3704       Fset_input_interrupt_mode (Qnil);
3705       ns_initialized = 1;
3706     }
3708   ns_pending_files = [[NSMutableArray alloc] init];
3709   ns_pending_service_names = [[NSMutableArray alloc] init];
3710   ns_pending_service_args = [[NSMutableArray alloc] init];
3712   /* Start app and create the main menu, window, view.
3713      Needs to be here because ns_initialize_display_info () uses AppKit classes.
3714      The view will then ask the NSApp to stop and return to Emacs. */
3715   [EmacsApp sharedApplication];
3716   if (NSApp == nil)
3717     return NULL;
3718   [NSApp setDelegate: NSApp];
3720   /* debugging: log all notifications */
3721   /*   [[NSNotificationCenter defaultCenter] addObserver: NSApp
3722                                          selector: @selector (logNotification:)
3723                                              name: nil object: nil]; */
3725   dpyinfo = (struct ns_display_info *)xmalloc (sizeof (struct ns_display_info));
3726   bzero (dpyinfo, sizeof (struct ns_display_info));
3728   ns_initialize_display_info (dpyinfo);
3729   terminal = ns_create_terminal (dpyinfo);
3731   terminal->kboard = (KBOARD *) xmalloc (sizeof (KBOARD));
3732   init_kboard (terminal->kboard);
3733   terminal->kboard->Vwindow_system = Qns;
3734   terminal->kboard->next_kboard = all_kboards;
3735   all_kboards = terminal->kboard;
3736   /* Don't let the initial kboard remain current longer than necessary.
3737      That would cause problems if a file loaded on startup tries to
3738      prompt in the mini-buffer.  */
3739   if (current_kboard == initial_kboard)
3740     current_kboard = terminal->kboard;
3741   terminal->kboard->reference_count++;
3743   dpyinfo->next = x_display_list;
3744   x_display_list = dpyinfo;
3746   /* Put it on ns_display_name_list */
3747   ns_display_name_list = Fcons (Fcons (display_name, Qnil),
3748                                 ns_display_name_list);
3749   dpyinfo->name_list_element = XCAR (ns_display_name_list);
3751   /* Set the name of the terminal. */
3752   terminal->name = (char *) xmalloc (SBYTES (display_name) + 1);
3753   strncpy (terminal->name, SDATA (display_name), SBYTES (display_name));
3754   terminal->name[SBYTES (display_name)] = 0;
3756   UNBLOCK_INPUT; 
3758   /* Read various user defaults. */
3759   ns_set_default_prefs ();
3760   if (!inhibit_x_resources)
3761     {
3762       ns_default ("GSFontAntiAlias", &ns_antialias_text,
3763                  Qt, Qnil, NO, NO);
3764       tmp = Qnil;
3765       /* this is a standard variable */
3766       ns_default ("AppleAntiAliasingThreshold", &tmp,
3767                  make_float (10.0), make_float (6.0), YES, NO);
3768       ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
3769     }
3771   ns_selection_color = [[NSUserDefaults standardUserDefaults]
3772                          stringForKey: @"AppleHighlightColor"];
3773   if (ns_selection_color == nil)
3774     ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
3775   
3776   {
3777     NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
3779     if ( cl == nil )
3780       {
3781         Lisp_Object color_file, color_map, color;
3782         int r,g,b;
3783         unsigned long c;
3784         char *name;
3786         color_file = Fexpand_file_name (build_string ("rgb.txt"),
3787                          Fsymbol_value (intern ("data-directory")));
3788         if (NILP (Ffile_readable_p (color_file)))
3789           fatal ("Could not find %s.\n", SDATA (color_file));
3791         color_map = Fx_load_color_file (color_file);
3792         if (NILP (color_map))
3793           fatal ("Could not read %s.\n", SDATA (color_file));
3795         cl = [[NSColorList alloc] initWithName: @"Emacs"];
3796         for ( ; CONSP (color_map); color_map = XCDR (color_map))
3797           {
3798             color = XCAR (color_map);
3799             name = SDATA (XCAR (color));
3800             c = XINT (XCDR (color));
3801             [cl setColor:
3802                   [NSColor colorWithCalibratedRed: RED_FROM_ULONG (c) / 255.0
3803                                             green: GREEN_FROM_ULONG (c) / 255.0
3804                                              blue: BLUE_FROM_ULONG (c) / 255.0
3805                                             alpha: 1.0]
3806                   forKey: [NSString stringWithUTF8String: name]];
3807           }
3808         [cl writeToFile: nil];
3809       }
3810   }
3812   {
3813     char c[128];
3814 #ifdef NS_IMPL_GNUSTEP
3815     strncpy (c, gnustep_base_version, sizeof (c));
3816 #else
3817     /*PSnextrelease (128, c); */
3818     snprintf (c, sizeof (c), "%g", NSAppKitVersionNumber);
3819 #endif
3820     Vwindow_system_version = build_string (c);
3821   }
3823   delete_keyboard_wait_descriptor (0);
3825   ns_app_name = [[NSProcessInfo processInfo] processName];
3827 /* Set up OS X app menu */
3828 #ifdef NS_IMPL_COCOA
3829   {
3830     NSMenu *appMenu;
3831     NSMenuItem *item;
3832     /* set up the application menu */
3833     svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
3834     [svcsMenu setAutoenablesItems: NO];
3835     appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
3836     [appMenu setAutoenablesItems: NO];
3837     mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
3838     dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
3840     [appMenu insertItemWithTitle: @"About Emacs"
3841                           action: @selector (orderFrontStandardAboutPanel:)
3842                    keyEquivalent: @""
3843                          atIndex: 0];
3844     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
3845     [appMenu insertItemWithTitle: @"Preferences..."
3846                           action: @selector (showPreferencesWindow:)
3847                    keyEquivalent: @","
3848                          atIndex: 2];
3849     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
3850     item = [appMenu insertItemWithTitle: @"Services"
3851                                  action: @selector (menuDown:)
3852                           keyEquivalent: @""
3853                                 atIndex: 4];
3854     [appMenu setSubmenu: svcsMenu forItem: item];
3855     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
3856     [appMenu insertItemWithTitle: @"Hide Emacs"
3857                           action: @selector (hide:)
3858                    keyEquivalent: @"h"
3859                          atIndex: 6];
3860     item =  [appMenu insertItemWithTitle: @"Hide Others"
3861                           action: @selector (hideOtherApplications:)
3862                    keyEquivalent: @"h"
3863                          atIndex: 7];
3864     [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
3865     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
3866     [appMenu insertItemWithTitle: @"Quit Emacs"
3867                           action: @selector (terminate:)
3868                    keyEquivalent: @"q"
3869                          atIndex: 9];
3871     item = [mainMenu insertItemWithTitle: ns_app_name                       
3872                                   action: @selector (menuDown:)
3873                            keyEquivalent: @""
3874                                  atIndex: 0];
3875     [mainMenu setSubmenu: appMenu forItem: item];
3876     [dockMenu insertItemWithTitle: @"New Frame"
3877                            action: @selector (newFrame:)
3878                     keyEquivalent: @""
3879                           atIndex: 0];
3881     [NSApp setMainMenu: mainMenu];
3882     [NSApp setAppleMenu: appMenu];
3883     [NSApp setServicesMenu: svcsMenu];
3884     /* Needed at least on Cocoa, to get dock menu to show windows */
3885     [NSApp setWindowsMenu: [[NSMenu alloc] init]];
3886   }
3887 #endif /* MAC OS X menu setup */
3889   [NSApp run];
3891   return dpyinfo;
3895 extern Lisp_Object Vauto_save_list_file_name;
3896 void
3897 ns_term_shutdown (int sig)
3899   /* code not reached in emacs.c after this is called by shut_down_emacs: */
3900   if (STRINGP (Vauto_save_list_file_name))
3901     unlink (SDATA (Vauto_save_list_file_name));
3903   if (sig == 0 || sig == SIGTERM)
3904     {
3905       [NSApp terminate: NSApp];
3906     }
3907   else // force a stack trace to happen
3908     {
3909       abort();
3910     }
3914 /* ==========================================================================
3916     EmacsApp implementation
3918    ========================================================================== */
3921 @implementation EmacsApp
3923 - (void)logNotification: (NSNotification *)notification
3925   const char *name = [[notification name] UTF8String];
3926   if (!strstr (name, "Update") && !strstr (name, "NSMenu")
3927       && !strstr (name, "WindowNumber"))
3928     NSLog (@"notification: '%@'", [notification name]);
3932 - (void)sendEvent: (NSEvent *)theEvent
3933 /* --------------------------------------------------------------------------
3934      Called when NSApp is running for each event received.  Used to stop
3935      the loop when we choose, since there's no way to just run one iteration.
3936    -------------------------------------------------------------------------- */
3938   int type = [theEvent type];
3939   NSWindow *window = [theEvent window];
3940 /*  NSTRACE (sendEvent); */
3941 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
3943   if (type == NSCursorUpdate && window == nil)
3944     {
3945       fprintf (stderr, "Dropping external cursor update event.\n");
3946       return;
3947     }
3949 #ifdef NS_IMPL_COCOA
3950   /* pass mouse down in resize handle and subsequent drags directly to
3951      EmacsWindow so we can generate continuous redisplays */
3952   if (ns_in_resize)
3953     {
3954       if (type == NSLeftMouseDragged)
3955         {
3956           [window mouseDragged: theEvent];
3957           return;
3958         }
3959       else if (type == NSLeftMouseUp)
3960         {
3961           [window mouseUp: theEvent];
3962           return;
3963         }
3964     }
3965   else if (type == NSLeftMouseDown)
3966     {
3967       NSRect r = ns_resize_handle_rect (window);
3968       if (NSPointInRect ([theEvent locationInWindow], r))
3969         {
3970           ns_in_resize = YES;
3971           [window mouseDown: theEvent];
3972           return;
3973         }
3974     }
3975 #endif
3977   if (type == NSApplicationDefined)
3978     {
3979       /* Events posted by ns_send_appdefined interrupt the run loop here.
3980          But, if a modal window is up, an appdefined can still come through,
3981          (e.g., from a makeKeyWindow event) but stopping self also stops the
3982          modal loop. Just defer it until later. */
3983       if ([NSApp modalWindow] == nil)
3984         {
3985           last_appdefined_event = theEvent;
3986           [self stop: self];
3987         }
3988       else
3989         {
3990           send_appdefined = YES;
3991         }
3992     }
3994   [super sendEvent: theEvent];
3998 - (void)showPreferencesWindow: (id)sender
4000   struct frame *emacsframe = SELECTED_FRAME ();
4001   NSEvent *theEvent = [NSApp currentEvent];
4003   if (!emacs_event)
4004     return;
4005   emacs_event->kind = NS_NONKEY_EVENT;
4006   emacs_event->code = KEY_NS_SHOW_PREFS;
4007   emacs_event->modifiers = 0;
4008   EV_TRAILER (theEvent);
4012 - (void)newFrame: (id)sender
4014   struct frame *emacsframe = SELECTED_FRAME ();
4015   NSEvent *theEvent = [NSApp currentEvent];
4017   if (!emacs_event)
4018     return;
4019   emacs_event->kind = NS_NONKEY_EVENT;
4020   emacs_event->code = KEY_NS_NEW_FRAME;
4021   emacs_event->modifiers = 0;
4022   EV_TRAILER (theEvent);
4026 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4027 - (BOOL) openFile: (NSString *)fileName
4029   struct frame *emacsframe = SELECTED_FRAME ();
4030   NSEvent *theEvent = [NSApp currentEvent];
4032   if (!emacs_event)
4033     return NO;
4035   emacs_event->kind = NS_NONKEY_EVENT;
4036   emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4037   ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4038   ns_input_line = Qnil; /* can be start or cons start,end */
4039   emacs_event->modifiers =0;
4040   EV_TRAILER (theEvent);
4042   return YES;
4046 /* **************************************************************************
4048       EmacsApp delegate implementation
4050    ************************************************************************** */
4052 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4053 /* --------------------------------------------------------------------------
4054      When application is loaded, terminate event loop in ns_term_init
4055    -------------------------------------------------------------------------- */
4057   NSTRACE (applicationDidFinishLaunching);
4058   [NSApp setServicesProvider: NSApp];
4059   ns_send_appdefined (-2);
4063 /* Termination sequences:
4064     C-x C-c:
4065     Cmd-Q:
4066     MenuBar | File | Exit:
4067     Select Quit from App menubar:
4068         -terminate
4069         KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4070         ns_term_shutdown()
4072     Select Quit from Dock menu:
4073     Logout attempt:
4074         -appShouldTerminate
4075           Cancel -> Nothing else
4076           Accept ->
4077           
4078           -terminate
4079           KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4080           ns_term_shutdown()
4084 - (void) terminate: (id)sender
4086   struct frame *emacsframe = SELECTED_FRAME ();
4087   
4088   if (!emacs_event)
4089     return;
4090   
4091   emacs_event->kind = NS_NONKEY_EVENT;
4092   emacs_event->code = KEY_NS_POWER_OFF;
4093   emacs_event->arg = Qt; /* mark as non-key event */
4094   EV_TRAILER ((id)nil);
4098 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4100   int ret;
4102   if (NILP (ns_confirm_quit)) //   || ns_shutdown_properly  --> TO DO
4103     return NSTerminateNow;
4105     ret = NSRunAlertPanel(ns_app_name,
4106                           [NSString stringWithUTF8String:"Exit requested.  Would you like to Save Buffers and Exit, or Cancel the request?"],
4107                           @"Save Buffers and Exit", @"Cancel", nil);
4109     if (ret == NSAlertDefaultReturn)
4110         return NSTerminateNow;
4111     else if (ret == NSAlertAlternateReturn)
4112         return NSTerminateCancel;
4113     return NSTerminateNow;  /* just in case */
4117 /*   Notification from the Workspace to open a file */
4118 - (BOOL)application: sender openFile: (NSString *)file
4120   [ns_pending_files addObject: file];
4121   return YES;
4125 /*   Open a file as a temporary file */
4126 - (BOOL)application: sender openTempFile: (NSString *)file
4128   [ns_pending_files addObject: file];
4129   return YES;
4133 /*   Notification from the Workspace to open a file noninteractively (?) */
4134 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4136   [ns_pending_files addObject: file];
4137   return YES;
4141 /*   Notification from the Workspace to open multiple files */
4142 - (void)application: sender openFiles: (NSArray *)fileList
4144   NSEnumerator *files = [fileList objectEnumerator];
4145   NSString *file;
4146   while ((file = [files nextObject]) != nil)
4147     [ns_pending_files addObject: file];
4149   [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4154 /* Handle dock menu requests.  */
4155 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4157   return dockMenu;
4161 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4162 - (void)applicationWillBecomeActive: (NSNotification *)notification
4164   //ns_app_active=YES;
4166 - (void)applicationDidBecomeActive: (NSNotification *)notification
4168   //ns_app_active=YES;
4170 - (void)applicationDidResignActive: (NSNotification *)notification
4172   //ns_app_active=NO;
4173   ns_send_appdefined (-1);
4178 /* ==========================================================================
4180     EmacsApp aux handlers for managing event loop
4182    ========================================================================== */
4185 - (void)timeout_handler: (NSTimer *)timedEntry
4186 /* --------------------------------------------------------------------------
4187      The timeout specified to ns_select has passed.
4188    -------------------------------------------------------------------------- */
4190   /*NSTRACE (timeout_handler); */
4191   ns_send_appdefined (-2);
4194 extern void update_window_cursor (struct window *w, int on);
4196 - (void)fd_handler: (NSTimer *) fdEntry
4197 /* --------------------------------------------------------------------------
4198      Check data waiting on file descriptors and terminate if so
4199    -------------------------------------------------------------------------- */
4201   int result;
4202   /* NSTRACE (fd_handler); */
4204   if (select_nfds == 0)
4205     return;
4207   memcpy (&t_readfds, &select_readfds, sizeof (fd_set));
4209   select_timeout.tv_sec = select_timeout.tv_usec = 0;
4210   result = select (select_nfds, &t_readfds, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
4211                   &select_timeout);
4212   if (result)
4213     {
4214       memcpy (&select_readfds, &t_readfds, sizeof (fd_set));
4215       ns_send_appdefined (result);
4216     }
4221 /* ==========================================================================
4223     Service provision
4225    ========================================================================== */
4227 /* called from system: queue for next pass through event loop */
4228 - (void)requestService: (NSPasteboard *)pboard
4229               userData: (NSString *)userData
4230                  error: (NSString **)error
4232   [ns_pending_service_names addObject: userData];
4233   [ns_pending_service_args addObject: [NSString stringWithUTF8String:
4234       SDATA (ns_string_from_pasteboard (pboard))]];
4238 /* called from ns_read_socket to clear queue */
4239 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
4241   struct frame *emacsframe = SELECTED_FRAME ();
4242   NSEvent *theEvent = [NSApp currentEvent];
4244   if (!emacs_event)
4245     return NO;
4247   emacs_event->kind = NS_NONKEY_EVENT;
4248   emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
4249   ns_input_spi_name = build_string ([name UTF8String]);
4250   ns_input_spi_arg = build_string ([arg UTF8String]);
4251   emacs_event->modifiers = EV_MODIFIERS (theEvent);
4252   EV_TRAILER (theEvent);
4254   return YES;
4258 @end  /* EmacsApp */
4262 /* ==========================================================================
4264     EmacsView implementation
4266    ========================================================================== */
4269 @implementation EmacsView
4271 /* needed to inform when window closed from LISP */
4272 - (void) setWindowClosing: (BOOL)closing
4274   windowClosing = closing;
4278 - (void)dealloc
4280   NSTRACE (EmacsView_dealloc);
4281   [toolbar release];
4282   [super dealloc];
4286 /* called on font panel selection */
4287 - (void)changeFont: (id)sender
4289   NSEvent *e =[[self window] currentEvent];
4290   struct face *face =FRAME_DEFAULT_FACE (emacsframe);
4291   id newFont;
4292   float size;
4294   NSTRACE (changeFont);
4295   if (!emacs_event)
4296     return;
4298   if (newFont = [sender convertFont:
4299                            ((struct nsfont_info *)face->font)->nsfont])
4300     {
4301       SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
4303       emacs_event->kind = NS_NONKEY_EVENT;
4304       emacs_event->modifiers = 0;
4305       emacs_event->code = KEY_NS_CHANGE_FONT;
4307       size = [newFont pointSize];
4308       ns_input_fontsize = make_number (lrint (size));
4309       ns_input_font = build_string ([[newFont familyName] UTF8String]);
4310       EV_TRAILER (e);
4311     }
4315 - (BOOL)acceptsFirstResponder
4317   NSTRACE (acceptsFirstResponder);
4318   return YES;
4322 - (void)resetCursorRects
4324   NSRect visible = [self visibleRect];
4325   NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
4326   NSTRACE (resetCursorRects);
4328   if (currentCursor == nil)
4329     currentCursor = [NSCursor arrowCursor];
4331   if (!NSIsEmptyRect (visible))
4332     [self addCursorRect: visible cursor: currentCursor];
4333   [currentCursor setOnMouseEntered: YES];
4338 /*****************************************************************************/
4339 /* Keyboard handling. */
4340 #define NS_KEYLOG 0
4342 - (void)keyDown: (NSEvent *)theEvent
4344   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4345   int code;
4346   unsigned fnKeysym = 0;
4347   int flags;
4348   static NSMutableArray *nsEvArray;
4349   static BOOL firstTime = YES;
4351   NSTRACE (keyDown);
4353   /* Rhapsody and OS X give up and down events for the arrow keys */
4354   if (ns_fake_keydown == YES)
4355     ns_fake_keydown = NO;
4356   else if ([theEvent type] != NSKeyDown)
4357     return;
4359   if (!emacs_event)
4360     return;
4362  if (![[self window] isKeyWindow]
4363      && [[theEvent window] isKindOfClass: [EmacsWindow class]]
4364      /* we must avoid an infinite loop here. */
4365      && (EmacsView *)[[theEvent window] delegate] != self)
4366    {
4367      /* XXX: There is an occasional condition in which, when Emacs display
4368          updates a different frame from the current one, and temporarily
4369          selects it, then processes some interrupt-driven input
4370          (dispnew.c:3878), OS will send the event to the correct NSWindow, but
4371          for some reason that window has its first responder set to the NSView
4372          most recently updated (I guess), which is not the correct one. */
4373      [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
4374      return;
4375    }
4377   if (nsEvArray == nil)
4378     nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
4380   [NSCursor setHiddenUntilMouseMoves: YES];
4382   if (dpyinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
4383     {
4384       clear_mouse_face (dpyinfo);
4385       dpyinfo->mouse_face_hidden = 1;
4386     }
4388   if (!processingCompose)
4389     {
4390       code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
4391         0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
4392       /* (Carbon way: [theEvent keyCode]) */
4394       /* is it a "function key"? */
4395       fnKeysym = ns_convert_key (code);
4396       if (fnKeysym)
4397         {
4398           /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
4399              because Emacs treats Delete and KP-Delete same (in simple.el). */
4400           if (fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
4401             code = 0xFF08; /* backspace */
4402           else
4403             code = fnKeysym;
4404         }
4406       /* are there modifiers? */
4407       emacs_event->modifiers = 0;
4408       flags = [theEvent modifierFlags];
4410       if (flags & NSHelpKeyMask)
4411           emacs_event->modifiers |= hyper_modifier;
4413       if (flags & NSShiftKeyMask)
4414         emacs_event->modifiers |= shift_modifier;
4416       if (flags & NSCommandKeyMask)
4417         {
4418           emacs_event->modifiers |= parse_solitary_modifier (ns_command_modifier);
4419           /* if super (default), take input manager's word so things like
4420              dvorak / qwerty layout work */
4421           if (EQ (ns_command_modifier, Qsuper)
4422               && !fnKeysym
4423               && [[theEvent characters] length] != 0)
4424             {
4425               /* XXX: the code we get will be unshifted, so if we have
4426                  a shift modifier, must convert ourselves */
4427               if (!(flags & NSShiftKeyMask))
4428                 code = [[theEvent characters] characterAtIndex: 0];
4429 #if 0
4430               /* this is ugly and also requires linking w/Carbon framework
4431                  (for LMGetKbdType) so for now leave this rare (?) case
4432                  undealt with.. in future look into CGEvent methods */
4433               else
4434                 {
4435                   long smv = GetScriptManagerVariable (smKeyScript);
4436                   Handle uchrHandle = GetResource
4437                     ('uchr', GetScriptVariable (smv, smScriptKeys));
4438                   UInt32 dummy = 0;
4439                   UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
4440                                  [[theEvent characters] characterAtIndex: 0],
4441                                  kUCKeyActionDisplay,
4442                                  (flags & ~NSCommandKeyMask) >> 8,
4443                                  LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
4444                                  &dummy, 1, &dummy, &code);
4445                   code &= 0xFF;
4446                 }
4447 #endif
4448             }
4449         }
4451       if (flags & NSControlKeyMask)
4452           emacs_event->modifiers |=
4453             parse_solitary_modifier (ns_control_modifier);
4455       if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
4456           emacs_event->modifiers |=
4457             parse_solitary_modifier (ns_function_modifier);
4459       if (flags & NSAlternateKeyMask) /* default = meta */
4460         {
4461           if ((NILP (ns_alternate_modifier) || EQ (ns_alternate_modifier, Qnone))
4462               && !fnKeysym)
4463             {   /* accept pre-interp alt comb */
4464               if ([[theEvent characters] length] > 0)
4465                 code = [[theEvent characters] characterAtIndex: 0];
4466               /*HACK: clear lone shift modifier to stop next if from firing */
4467               if (emacs_event->modifiers == shift_modifier)
4468                 emacs_event->modifiers = 0;
4469             }
4470           else
4471               emacs_event->modifiers |=
4472                 parse_solitary_modifier (ns_alternate_modifier);
4473         }
4475   if (NS_KEYLOG)
4476     fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
4477              code, fnKeysym, flags, emacs_event->modifiers);
4479       /* if it was a function key or had modifiers, pass it directly to emacs */
4480       if (fnKeysym || (emacs_event->modifiers
4481                        && [[theEvent charactersIgnoringModifiers] length] > 0))
4482 /*[[theEvent characters] length] */
4483         {
4484           emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4485           if (code < 0x20)
4486             code |= (1<<28)|(3<<16);
4487           else if (code == 0x7f)
4488             code |= (1<<28)|(3<<16);
4489           else if (!fnKeysym)
4490             emacs_event->kind = code > 0xFF
4491               ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4493           emacs_event->code = code;
4494           EV_TRAILER (theEvent);
4495           return;
4496         }
4497     }
4499   /* if we get here we should send the key for input manager processing */
4500   if (firstTime && [[NSInputManager currentInputManager]
4501                      wantsToDelayTextChangeNotifications] == NO)
4502     fprintf (stderr,
4503           "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
4504   firstTime = NO;
4506   if (NS_KEYLOG && !processingCompose)
4507     fprintf (stderr, "keyDown: Begin compose sequence.\n");
4509   processingCompose = YES;
4510   [nsEvArray addObject: theEvent];
4511   [self interpretKeyEvents: nsEvArray];
4512   [nsEvArray removeObject: theEvent];
4516 #ifdef NS_IMPL_COCOA
4517 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
4518    decided not to send key-down for.
4519    See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
4520    This only applies on Tiger and earlier.
4521    If it matches one of these, send it on to keyDown. */
4522 -(void)keyUp: (NSEvent *)theEvent
4524   int flags = [theEvent modifierFlags];
4525   int code = [theEvent keyCode];
4526   if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
4527       code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
4528     {
4529       if (NS_KEYLOG)
4530         fprintf (stderr, "keyUp: passed test");
4531       ns_fake_keydown = YES;
4532       [self keyDown: theEvent];
4533     }
4535 #endif
4538 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
4541 /* <NSTextInput>: called when done composing;
4542    NOTE: also called when we delete over working text, followed immed.
4543          by doCommandBySelector: deleteBackward: */
4544 - (void)insertText: (id)aString
4546   int code;
4547   int len = [(NSString *)aString length];
4548   int i;
4550   if (NS_KEYLOG)
4551     NSLog (@"insertText '%@'\tlen = %d", aString, len);
4552   processingCompose = NO;
4554   if (!emacs_event)
4555     return;
4557   /* first, clear any working text */
4558   if (workingText != nil)
4559     [self deleteWorkingText];
4561   /* now insert the string as keystrokes */
4562   for (i =0; i<len; i++)
4563     {
4564       code = [aString characterAtIndex: i];
4565       /* TODO: still need this? */
4566       if (code == 0x2DC)
4567         code = '~'; /* 0x7E */
4568       emacs_event->modifiers = 0;
4569       emacs_event->kind
4570         = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4571       emacs_event->code = code;
4572       EV_TRAILER ((id)nil);
4573     }
4577 /* <NSTextInput>: inserts display of composing characters */
4578 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
4580   NSString *str = [aString respondsToSelector: @selector (string)] ?
4581     [aString string] : aString;
4582   if (NS_KEYLOG)
4583     NSLog (@"setMarkedText '%@' len =%d range %d from %d", str, [str length],
4584            selRange.length, selRange.location);
4586   if (workingText != nil)
4587     [self deleteWorkingText];
4588   if ([str length] == 0)
4589     return;
4591   if (!emacs_event)
4592     return;
4594   processingCompose = YES;
4595   workingText = [str copy];
4596   ns_working_text = build_string ([workingText UTF8String]);
4598   emacs_event->kind = NS_TEXT_EVENT;
4599   emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
4600   EV_TRAILER ((id)nil);
4604 /* delete display of composing characters [not in <NSTextInput>] */
4605 - (void)deleteWorkingText
4607   if (workingText == nil)
4608     return;
4609   if (NS_KEYLOG)
4610     NSLog(@"deleteWorkingText len =%d\n", [workingText length]);
4611   [workingText release];
4612   workingText = nil;
4613   processingCompose = NO;
4615   if (!emacs_event)
4616     return;
4618   emacs_event->kind = NS_TEXT_EVENT;
4619   emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
4620   EV_TRAILER ((id)nil);
4624 - (BOOL)hasMarkedText
4626   return workingText != nil;
4630 - (NSRange)markedRange
4632   NSRange rng = workingText != nil
4633     ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
4634   if (NS_KEYLOG)
4635     NSLog (@"markedRange request");
4636   return rng;
4640 - (void)unmarkText
4642   if (NS_KEYLOG)
4643     NSLog (@"unmark (accept) text");
4644   [self deleteWorkingText];
4645   processingCompose = NO;
4649 /* used to position char selection windows, etc. */
4650 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
4652   NSRect rect;
4653   NSPoint pt;
4654   struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
4655   if (NS_KEYLOG)
4656     NSLog (@"firstRectForCharRange request");
4658   rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
4659   rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
4660   pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
4661   pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
4662                                        +FRAME_LINE_HEIGHT (emacsframe));
4664   pt = [self convertPoint: pt toView: nil];
4665   pt = [[self window] convertBaseToScreen: pt];
4666   rect.origin = pt;
4667   return rect;
4671 - (long)conversationIdentifier
4673   return (long)self;
4677 - (void)doCommandBySelector: (SEL)aSelector
4679   if (NS_KEYLOG)
4680     NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
4682   if (aSelector == @selector (deleteBackward:))
4683     {
4684       /* happens when user backspaces over an ongoing composition:
4685          throw a 'delete' into the event queue */
4686       if (!emacs_event)
4687         return;
4688       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4689       emacs_event->code = 0xFF08;
4690       EV_TRAILER ((id)nil);
4691     }
4694 - (NSArray *)validAttributesForMarkedText
4696   static NSArray *arr = nil;
4697   if (arr == nil) arr = [NSArray new];
4698  /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
4699   return arr;
4702 - (NSRange)selectedRange
4704   if (NS_KEYLOG)
4705     NSLog (@"selectedRange request");
4706   return NSMakeRange (NSNotFound, 0);
4709 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
4711   if (NS_KEYLOG)
4712     NSLog (@"characterIndexForPoint request");
4713   return 0;
4716 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
4718   static NSAttributedString *str = nil;
4719   if (str == nil) str = [NSAttributedString new];
4720   if (NS_KEYLOG)
4721     NSLog (@"attributedSubstringFromRange request");
4722   return str;
4725 /* End <NSTextInput> impl. */
4726 /*****************************************************************************/
4729 /* This is what happens when the user presses a mouse button.  */
4730 - (void)mouseDown: (NSEvent *)theEvent
4732   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
4733   Lisp_Object window;
4735   NSTRACE (mouseDown);
4737   [self deleteWorkingText];
4739   if (!emacs_event)
4740     return;
4742   last_mouse_frame = emacsframe;
4743   /* appears to be needed to prevent spurious movement events generated on
4744      button clicks */
4745   last_mouse_frame->mouse_moved = 0;
4747   if ([theEvent type] == NSScrollWheel)
4748     {
4749       float delta = [theEvent deltaY];
4750       /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
4751       if (delta == 0)
4752         return;
4753       emacs_event->kind = WHEEL_EVENT;
4754       emacs_event->code = 0;
4755       emacs_event->modifiers = EV_MODIFIERS (theEvent) |
4756         ((delta > 0) ? up_modifier : down_modifier);
4757     }
4758   else
4759     {
4760       emacs_event->kind = MOUSE_CLICK_EVENT;
4761       emacs_event->code = EV_BUTTON (theEvent);
4762       emacs_event->modifiers = EV_MODIFIERS (theEvent)
4763                              | EV_UDMODIFIERS (theEvent);
4764     }
4765   XSETINT (emacs_event->x, lrint (p.x));
4766   XSETINT (emacs_event->y, lrint (p.y));
4767   EV_TRAILER (theEvent);
4771 - (void)rightMouseDown: (NSEvent *)theEvent
4773   NSTRACE (rightMouseDown);
4774   [self mouseDown: theEvent];
4778 - (void)otherMouseDown: (NSEvent *)theEvent
4780   NSTRACE (otherMouseDown);
4781   [self mouseDown: theEvent];
4785 - (void)mouseUp: (NSEvent *)theEvent
4787   NSTRACE (mouseUp);
4788   [self mouseDown: theEvent];
4792 - (void)rightMouseUp: (NSEvent *)theEvent
4794   NSTRACE (rightMouseUp);
4795   [self mouseDown: theEvent];
4799 - (void)otherMouseUp: (NSEvent *)theEvent
4801   NSTRACE (otherMouseUp);
4802   [self mouseDown: theEvent];
4806 - (void) scrollWheel: (NSEvent *)theEvent
4808   NSTRACE (scrollWheel);
4809   [self mouseDown: theEvent];
4813 /* Tell emacs the mouse has moved. */
4814 - (void)mouseMoved: (NSEvent *)e
4816   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4817   Lisp_Object frame;
4819 //  NSTRACE (mouseMoved);
4821   last_mouse_movement_time = EV_TIMESTAMP (e);
4822   last_mouse_motion_position
4823     = [self convertPoint: [e locationInWindow] fromView: nil];
4825   /* update any mouse face */
4826   if (dpyinfo->mouse_face_hidden)
4827     {
4828       dpyinfo->mouse_face_hidden = 0;
4829       clear_mouse_face (dpyinfo);
4830     }
4832   /* tooltip handling */
4833   previous_help_echo_string = help_echo_string;
4834   help_echo_string = Qnil;
4836   if (!note_mouse_movement (emacsframe, last_mouse_motion_position.x,
4837                             last_mouse_motion_position.y))
4838     help_echo_string = previous_help_echo_string;
4840   XSETFRAME (frame, emacsframe);
4841   if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
4842     {
4843       /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
4844          (note_mouse_highlight), which is called through the
4845          note_mouse_movement () call above */
4846       gen_help_event (help_echo_string, frame, help_echo_window,
4847                       help_echo_object, help_echo_pos);
4848     }
4849   else
4850     {
4851       help_echo_string = Qnil;
4852       gen_help_event (Qnil, frame, Qnil, Qnil, 0);
4853     }
4855   if (emacsframe->mouse_moved && send_appdefined)
4856     ns_send_appdefined (-1);
4860 - (void)mouseDragged: (NSEvent *)e
4862   NSTRACE (mouseDragged);
4863   [self mouseMoved: e];
4867 - (void)rightMouseDragged: (NSEvent *)e
4869   NSTRACE (rightMouseDragged);
4870   [self mouseMoved: e];
4874 - (void)otherMouseDragged: (NSEvent *)e
4876   NSTRACE (otherMouseDragged);
4877   [self mouseMoved: e];
4881 - (BOOL)windowShouldClose: (id)sender
4883   NSEvent *e =[[self window] currentEvent];
4885   NSTRACE (windowShouldClose);
4886   windowClosing = YES;
4887   if (!emacs_event)
4888     return NO;
4889   emacs_event->kind = DELETE_WINDOW_EVENT;
4890   emacs_event->modifiers = 0;
4891   emacs_event->code = 0;
4892   EV_TRAILER (e);
4893   /* Don't close this window, let this be done from lisp code.  */
4894   return NO;
4898 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
4899 /* normalize frame to gridded text size */
4901   NSTRACE (windowWillResize);
4902 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
4904   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe,
4905 #ifdef NS_IMPL_GNUSTEP
4906                                         frameSize.width + 3);
4907 #else
4908                                         frameSize.width);
4909 #endif
4910   if (cols < MINWIDTH)
4911     cols = MINWIDTH;
4912   frameSize.width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (emacsframe, cols);
4914   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, frameSize.height
4915 #ifdef NS_IMPL_GNUSTEP
4916       - FRAME_NS_TITLEBAR_HEIGHT (emacsframe) + 3
4917         - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
4918 #else
4919       - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
4920         - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
4921 #endif
4922   if (rows < MINHEIGHT)
4923     rows = MINHEIGHT;
4924   frameSize.height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows)
4925                        + FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
4926                        + FRAME_NS_TOOLBAR_HEIGHT (emacsframe);
4927 #ifdef NS_IMPL_COCOA
4928   {
4929     /* this sets window title to have size in it; the wm does this under GS */
4930     NSRect r = [[self window] frame];
4931     if (r.size.height == frameSize.height && r.size.width == frameSize.width)
4932       {
4933         if (old_title != 0)
4934           {
4935             xfree (old_title);
4936             old_title = 0;
4937           }
4938       }
4939     else
4940       {
4941         char *size_title;
4942         NSWindow *window = [self window];
4943         if (old_title == 0)
4944           {
4945             const char *t = [[[self window] title] UTF8String];
4946             char *pos = strstr (t, "  â€”  ");
4947             if (pos)
4948               *pos = '\0';
4949             old_title = (char *) xmalloc (strlen (t) + 1);
4950             strcpy (old_title, t);
4951           }
4952         size_title = xmalloc (strlen (old_title) + 40);
4953         sprintf (size_title, "%s  â€”  (%d x %d)", old_title, cols, rows);
4954         [window setTitle: [NSString stringWithUTF8String: size_title]];
4955         [window display];
4956         xfree (size_title);
4957       }
4958   }
4959 #endif /* NS_IMPL_COCOA */
4960 /*fprintf (stderr,"    ...size became %.0f x %.0f  (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
4962   return frameSize;
4966 - (void)windowDidResize: (NSNotification *)notification
4968   NSWindow *theWindow = [notification object];
4970 #ifdef NS_IMPL_GNUSTEP
4971    /* in GNUstep, at least currently, it's possible to get a didResize
4972       without getting a willResize.. therefore we need to act as if we got
4973       the willResize now */
4974   NSSize sz = [theWindow frame].size;
4975   sz = [self windowWillResize: theWindow toSize: sz];
4976 #endif /* NS_IMPL_GNUSTEP */
4978   NSTRACE (windowDidResize);
4979 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
4981 #ifdef NS_IMPL_COCOA
4982   if (old_title != 0)
4983     {
4984       xfree (old_title);
4985       old_title = 0;
4986     }
4987 #endif /* NS_IMPL_COCOA */
4989   /* Avoid loop under GNUstep due to call at beginning of this function.
4990      (x_set_window_size causes a resize which causes
4991      a "windowDidResize" which calls x_set_window_size).  */
4992 #ifndef NS_IMPL_GNUSTEP
4993   if (cols > 0 && rows > 0)
4994      x_set_window_size (emacsframe, 0, cols, rows);
4995 #endif
4997   ns_send_appdefined (-1);
5001 - (void)windowDidBecomeKey: (NSNotification *)notification
5002 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5004   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5005   struct frame *old_focus = dpyinfo->x_focus_frame;
5007   NSTRACE (windowDidBecomeKey);
5009   if (emacsframe != old_focus)
5010     dpyinfo->x_focus_frame = emacsframe;
5012   ns_frame_rehighlight (emacsframe);
5014   if (emacs_event)
5015     {
5016       emacs_event->kind = FOCUS_IN_EVENT;
5017       EV_TRAILER ((id)nil);
5018     }
5022 - (void)windowDidResignKey: (NSNotification *)notification
5023 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5025   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5026   NSTRACE (windowDidResignKey);
5028   if (dpyinfo->x_focus_frame == emacsframe)
5029     dpyinfo->x_focus_frame = 0;
5031   ns_frame_rehighlight (emacsframe);
5033   /* FIXME: for some reason needed on second and subsequent clicks away
5034             from sole-frame Emacs to get hollow box to show */
5035   if (!windowClosing && [[self window] isVisible] == YES)
5036     {
5037       x_update_cursor (emacsframe, 1);
5038       x_set_frame_alpha (emacsframe);
5039     }
5041   if (emacs_event)
5042     {
5043       [self deleteWorkingText];
5044       emacs_event->kind = FOCUS_IN_EVENT;
5045       EV_TRAILER ((id)nil);
5046     }
5050 - (void)windowWillMiniaturize: sender
5052   NSTRACE (windowWillMiniaturize);
5056 - (BOOL)isFlipped
5058   return YES;
5062 - (BOOL)isOpaque
5064   return NO;
5068 - initFrameFromEmacs: (struct frame *)f
5070   NSRect r, wr;
5071   Lisp_Object tem;
5072   NSWindow *win;
5073   NSButton *toggleButton;
5074   int vbextra = NS_SCROLL_BAR_WIDTH (f);
5075   NSSize sz;
5076   NSColor *col;
5077   NSString *name;
5079   NSTRACE (initFrameFromEmacs);
5081   windowClosing = NO;
5082   processingCompose = NO;
5083   scrollbarsNeedingUpdate = 0;
5085 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
5087   r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
5088                  FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
5089   [self initWithFrame: r];
5090   [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
5092   FRAME_NS_VIEW (f) = self;
5093   emacsframe = f;
5094   old_title = 0;
5096   win = [[EmacsWindow alloc]
5097             initWithContentRect: r
5098                       styleMask: (NSResizableWindowMask |
5099                                   NSMiniaturizableWindowMask |
5100                                   NSClosableWindowMask)
5101                         backing: NSBackingStoreBuffered
5102                           defer: YES];
5104   wr = [win frame];
5105   f->border_width = wr.size.width - r.size.width;
5106   FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
5108   [win setAcceptsMouseMovedEvents: YES];
5109   [win setDelegate: self];
5110   [win useOptimizedDrawing: YES];
5112   sz.width = FRAME_COLUMN_WIDTH (f);
5113   sz.height = FRAME_LINE_HEIGHT (f);
5114   [win setResizeIncrements: sz];
5116   [[win contentView] addSubview: self];
5118   if (ns_drag_types)
5119     [self registerForDraggedTypes: ns_drag_types];
5121   tem = f->name;
5122   name = [NSString stringWithUTF8String:
5123                    NILP (tem) ? (unsigned char *)"Emacs" : SDATA (tem)];
5124   [win setTitle: name];
5126   /* toolbar support */
5127   toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
5128                          [NSString stringWithFormat: @"Emacs Frame %d",
5129                                    ns_window_num]];
5130   [win setToolbar: toolbar];
5131   [toolbar setVisible: NO];
5132 #ifdef NS_IMPL_COCOA
5133   toggleButton = [win standardWindowButton: NSWindowToolbarButton];
5134   [toggleButton setTarget: self];
5135   [toggleButton setAction: @selector (toggleToolbar: )];
5136 #endif
5137   FRAME_NS_TOOLBAR_HEIGHT (f) = 0;
5139   tem = f->icon_name;
5140   if (!NILP (tem))
5141     [win setMiniwindowTitle:
5142            [NSString stringWithUTF8String: SDATA (tem)]];
5144   {
5145     NSScreen *screen = [win screen];
5147     if (screen != 0)
5148       [win setFrameTopLeftPoint: NSMakePoint
5149            (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
5150             IN_BOUND (-SCREENMAX,
5151                      [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
5152   }
5154   [win makeFirstResponder: self];
5156   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5157                                   (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
5158   [win setBackgroundColor: col];
5159   if ([col alphaComponent] != 1.0)
5160     [win setOpaque: NO];
5162   [self allocateGState];
5164   ns_window_num++;
5165   return self;
5169 - (void)windowDidMove: sender
5171   NSWindow *win = [self window];
5172   NSRect r = [win frame];
5173   NSScreen *screen = [win screen];
5175   NSTRACE (windowDidMove);
5177   if (!emacsframe->output_data.ns)
5178     return;
5179   if (screen != nil)
5180     {
5181       emacsframe->left_pos = r.origin.x;
5182       emacsframe->top_pos =
5183         [screen frame].size.height - (r.origin.y + r.size.height);
5184     }
5188 /* Called AFTER method below, but before our windowWillResize call there leads
5189    to windowDidResize -> x_set_window_size.  Update emacs' notion of frame
5190    location so set_window_size moves the frame. */
5191 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
5193   NSTRACE (windowShouldZoom);
5194   emacsframe->left_pos = (int)newFrame.origin.x;
5195   emacsframe->top_pos = [[sender screen] frame].size.height
5196                             - (newFrame.origin.y+newFrame.size.height);
5197   return YES;
5201 /* Override to do something slightly nonstandard, but nice.  First click on
5202    zoom button will zoom vertically.  Second will zoom completely.  Third
5203    returns to original. */
5204 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
5205                         defaultFrame:(NSRect)defaultFrame
5207   NSRect result = [sender frame];
5208   static NSRect ns_userRect = { 0, 0, 0, 0 };
5210   NSTRACE (windowWillUseStandardFrame);
5212   if (abs (defaultFrame.size.height - result.size.height)
5213       > FRAME_LINE_HEIGHT (emacsframe))
5214     {
5215       /* first click */
5216       ns_userRect = result;
5217       result.size.height = defaultFrame.size.height;
5218       result.origin.y = defaultFrame.origin.y;
5219     }
5220   else
5221     {
5222       if (abs (defaultFrame.size.width - result.size.width)
5223           > FRAME_COLUMN_WIDTH (emacsframe))
5224         result = defaultFrame;  /* second click */
5225       else
5226         result = ns_userRect.size.height ? ns_userRect : result;  /* restore */
5227     }
5229   [self windowWillResize: sender toSize: result.size];
5230   return result;
5234 - (void)windowDidDeminiaturize: sender
5236   NSTRACE (windowDidDeminiaturize);
5237   if (!emacsframe->output_data.ns)
5238     return;
5239   emacsframe->async_iconified = 0;
5240   emacsframe->async_visible   = 1;
5241   windows_or_buffers_changed++;
5243   if (emacs_event)
5244     {
5245       emacs_event->kind = ICONIFY_EVENT;
5246       EV_TRAILER ((id)nil);
5247     }
5251 - (void)windowDidExpose: sender
5253   NSTRACE (windowDidExpose);
5254   if (!emacsframe->output_data.ns)
5255     return;
5256   emacsframe->async_visible = 1;
5257   SET_FRAME_GARBAGED (emacsframe);
5259   if (send_appdefined)
5260     ns_send_appdefined (-1);
5264 - (void)windowDidMiniaturize: sender
5266   NSTRACE (windowDidMiniaturize);
5267   if (!emacsframe->output_data.ns)
5268     return;
5270   emacsframe->async_iconified = 1;
5271   emacsframe->async_visible = 0;
5273   if (emacs_event)
5274     {
5275       emacs_event->kind = ICONIFY_EVENT;
5276       EV_TRAILER ((id)nil);
5277     }
5281 - (void)mouseEntered: (NSEvent *)theEvent
5283   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5284   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5285   NSTRACE (mouseEntered);
5287   last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5291 - (void)mouseExited: (NSEvent *)theEvent
5293   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5294   NSRect r;
5295   struct ns_display_info *dpyinfo
5296     = emacsframe ? FRAME_NS_DISPLAY_INFO (emacsframe) : NULL;
5298   NSTRACE (mouseExited);
5300   if (dpyinfo || !emacsframe)
5301     return;
5303   last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5305   if (emacsframe == dpyinfo->mouse_face_mouse_frame)
5306     {
5307       clear_mouse_face (dpyinfo);
5308       dpyinfo->mouse_face_mouse_frame = 0;
5309     }
5313 - menuDown: sender
5315   NSTRACE (menuDown);
5316   if (context_menu_value == -1)
5317     context_menu_value = [sender tag];
5318   else
5319     find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
5320                                   emacsframe->menu_bar_vector,
5321                                   (void *)[sender tag]);
5322   ns_send_appdefined (-1);
5323   return self;
5327 - (EmacsToolbar *)toolbar
5329   return toolbar;
5333 /* this gets called on toolbar button click */
5334 - toolbarClicked: (id)item
5336   NSEvent *theEvent;
5337   int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
5339   NSTRACE (toolbarClicked);
5341   if (!emacs_event)
5342     return self;
5344   /* send first event (for some reason two needed) */
5345   theEvent = [[self window] currentEvent];
5346   emacs_event->kind = TOOL_BAR_EVENT;
5347   XSETFRAME (emacs_event->arg, emacsframe);
5348   EV_TRAILER (theEvent);
5350   emacs_event->kind = TOOL_BAR_EVENT;
5351 /*   XSETINT (emacs_event->code, 0); */
5352   emacs_event->arg = AREF (emacsframe->tool_bar_items,
5353                           idx + TOOL_BAR_ITEM_KEY);
5354   emacs_event->modifiers = EV_MODIFIERS (theEvent);
5355   EV_TRAILER (theEvent);
5356   return self;
5360 - toggleToolbar: (id)sender
5362   if (!emacs_event)
5363     return self;
5365   emacs_event->kind = NS_NONKEY_EVENT;
5366   emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
5367   EV_TRAILER ((id)nil);
5368   return self;
5372 - (void)drawRect: (NSRect)rect
5374   int x = NSMinX (rect), y = NSMinY (rect);
5375   int width = NSWidth (rect), height = NSHeight (rect);
5377   NSTRACE (drawRect);
5379   if (!emacsframe || !emacsframe->output_data.ns || ns_in_resize)
5380     return;
5382   ns_clear_frame_area (emacsframe, x, y, width, height);
5383   expose_frame (emacsframe, x, y, width, height);
5385   /*
5386     drawRect: may be called (at least in OS X 10.5) for invisible
5387     views as well for some reason.  Thus, do not infer visibility 
5388     here.
5390     emacsframe->async_visible = 1;
5391     emacsframe->async_iconified = 0;
5392   */
5396 /* NSDraggingDestination protocol methods.  Actually this is not really a
5397    protocol, but a category of Object.  O well...  */
5399 -(NSUInteger) draggingEntered: (id <NSDraggingInfo>) sender
5401   NSTRACE (draggingEntered);
5402   return NSDragOperationGeneric;
5406 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
5408   return YES;
5412 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
5414   id pb;
5415   int x, y;
5416   NSString *type;
5417   NSEvent *theEvent = [[self window] currentEvent];
5418   NSPoint position;
5420   NSTRACE (performDragOperation);
5422   if (!emacs_event)
5423     return;
5425   position = [self convertPoint: [sender draggingLocation] fromView: nil];
5426   x = lrint (position.x);  y = lrint (position.y);
5428   pb = [sender draggingPasteboard];
5429   type = [pb availableTypeFromArray: ns_drag_types];
5430   if (type == 0)
5431     {
5432       return NO;
5433     }
5434   else if ([type isEqualToString: NSFilenamesPboardType])
5435     {
5436       NSArray *files;
5437       NSEnumerator *fenum;
5438       NSString *file;
5440       if (!(files = [pb propertyListForType: type]))
5441         return NO;
5443       fenum = [files objectEnumerator];
5444       while ( (file = [fenum nextObject]) )
5445         {
5446           emacs_event->kind = NS_NONKEY_EVENT;
5447           emacs_event->code = KEY_NS_DRAG_FILE;
5448           XSETINT (emacs_event->x, x);
5449           XSETINT (emacs_event->y, y);
5450           ns_input_file = append2 (ns_input_file,
5451                                    build_string ([file UTF8String]));
5452           emacs_event->modifiers = EV_MODIFIERS (theEvent);
5453           EV_TRAILER (theEvent);
5454         }
5455       return YES;
5456     }
5457   else if ([type isEqualToString: NSURLPboardType])
5458     {
5459       NSString *file;
5460       NSURL *fileURL;
5462       if (!(fileURL = [NSURL URLFromPasteboard: pb]) ||
5463           [fileURL isFileURL] == NO)
5464         return NO;
5466       file = [fileURL path];
5467       emacs_event->kind = NS_NONKEY_EVENT;
5468       emacs_event->code = KEY_NS_DRAG_FILE;
5469       XSETINT (emacs_event->x, x);
5470       XSETINT (emacs_event->y, y);
5471       ns_input_file = append2 (ns_input_file, build_string ([file UTF8String]));
5472       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5473       EV_TRAILER (theEvent);
5474       return YES;
5475     }
5476   else if ([type isEqualToString: NSStringPboardType]
5477            || [type isEqualToString: NSTabularTextPboardType])
5478     {
5479       NSString *data;
5481       if (! (data = [pb stringForType: type]))
5482         return NO;
5484       emacs_event->kind = NS_NONKEY_EVENT;
5485       emacs_event->code = KEY_NS_DRAG_TEXT;
5486       XSETINT (emacs_event->x, x);
5487       XSETINT (emacs_event->y, y);
5488       ns_input_text = build_string ([data UTF8String]);
5489       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5490       EV_TRAILER (theEvent);
5491       return YES;
5492     }
5493   else if ([type isEqualToString: NSColorPboardType])
5494     {
5495       NSColor *c = [NSColor colorFromPasteboard: pb];
5496       emacs_event->kind = NS_NONKEY_EVENT;
5497       emacs_event->code = KEY_NS_DRAG_COLOR;
5498       XSETINT (emacs_event->x, x);
5499       XSETINT (emacs_event->y, y);
5500       ns_input_color = ns_color_to_lisp (c);
5501       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5502       EV_TRAILER (theEvent);
5503       return YES;
5504     }
5505   else if ([type isEqualToString: NSFontPboardType])
5506     {
5507       /* impl based on GNUstep NSTextView.m */
5508       NSData *data = [pb dataForType: NSFontPboardType];
5509       NSDictionary *dict = [NSUnarchiver unarchiveObjectWithData: data];
5510       NSFont *font = [dict objectForKey: NSFontAttributeName];
5511       char fontSize[10];
5513       if (font == nil)
5514         return NO;
5516       emacs_event->kind = NS_NONKEY_EVENT;
5517       emacs_event->code = KEY_NS_CHANGE_FONT;
5518       XSETINT (emacs_event->x, x);
5519       XSETINT (emacs_event->y, y);
5520       ns_input_font = build_string ([[font fontName] UTF8String]);
5521       snprintf (fontSize, 10, "%f", [font pointSize]);
5522       ns_input_fontsize = build_string (fontSize);
5523       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5524       EV_TRAILER (theEvent);
5525       return YES;
5526     }
5527   else
5528     {
5529       error ("Invalid data type in dragging pasteboard.");
5530       return NO;
5531     }
5535 - validRequestorForSendType: (NSString *)typeSent
5536                  returnType: (NSString *)typeReturned
5538   NSTRACE (validRequestorForSendType);
5539   if ([ns_send_types indexOfObjectIdenticalTo: typeSent] != NSNotFound &&
5540       [ns_return_types indexOfObjectIdenticalTo: typeSent] != NSNotFound)
5541     return self;
5543   return [super validRequestorForSendType: typeSent
5544                                returnType: typeReturned];
5548 /* The next two methods are part of NSServicesRequests informal protocol,
5549    supposedly called when a services menu item is chosen from this app.
5550    But this should not happen because we override the services menu with our
5551    own entries which call ns-perform-service.
5552    Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
5553    So let's at least stub them out until further investigation can be done. */
5555 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
5557   /* we could call ns_string_from_pasteboard(pboard) here but then it should
5558      be written into the buffer in place of the existing selection..
5559      ordinary service calls go through functions defined in ns-win.el */
5560   return NO;
5563 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
5565   /* supposed to write for as many of types as we are able */
5566   return NO;
5570 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
5571    (gives a miniaturized version of the window); currently we use the latter for
5572    frames whose active buffer doesn't correspond to any file
5573    (e.g., '*scratch*') */
5574 - setMiniwindowImage: (BOOL) setMini
5576   id image = [[self window] miniwindowImage];
5577   NSTRACE (setMiniwindowImage);
5579   /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
5580      about "AppleDockIconEnabled" notwithstanding, however the set message
5581      below has its effect nonetheless. */
5582   if (image != emacsframe->output_data.ns->miniimage)
5583     {
5584       if (image && [image isKindOfClass: [EmacsImage class]])
5585         [image release];
5586       [[self window] setMiniwindowImage:
5587                        setMini ? emacsframe->output_data.ns->miniimage : nil];
5588     }
5590   return self;
5594 - (void) setRows: (int) r andColumns: (int) c
5596   rows = r;
5597   cols = c;
5600 @end  /* EmacsView */
5604 /* ==========================================================================
5606     EmacsWindow implementation
5608    ========================================================================== */
5610 @implementation EmacsWindow
5612 /* called only on resize clicks by special case in EmacsApp-sendEvent */
5613 - (void)mouseDown: (NSEvent *)theEvent
5615   if (ns_in_resize)
5616     {
5617       NSSize size = [[theEvent window] frame].size;
5618       grabOffset = [theEvent locationInWindow];
5619       grabOffset.x = size.width - grabOffset.x;
5620     }
5621   else
5622     [super mouseDown: theEvent];
5626 /* stop resizing */
5627 - (void)mouseUp: (NSEvent *)theEvent
5629   if (ns_in_resize)
5630     {
5631       struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
5632       ns_in_resize = NO;
5633       ns_set_name_as_filename (f);
5634       [self display];
5635       ns_send_appdefined (-1);
5636     }
5637   else
5638     [super mouseUp: theEvent];
5642 /* send resize events */
5643 - (void)mouseDragged: (NSEvent *)theEvent
5645   if (ns_in_resize)
5646     {
5647       NSPoint p = [theEvent locationInWindow];
5648       NSSize size, vettedSize, origSize = [self frame].size;
5650       size.width = p.x + grabOffset.x;
5651       size.height = origSize.height - p.y + grabOffset.y;
5653       if (size.width == origSize.width && size.height == origSize.height)
5654         return;
5656       vettedSize = [[self delegate] windowWillResize: self toSize: size];
5657       if (vettedSize.width != size.width || vettedSize.height != size.height)
5658         {
5659           [[NSNotificationCenter defaultCenter]
5660             postNotificationName: NSWindowDidResizeNotification
5661                           object: self];
5662         }
5663     }
5664   else
5665     [super mouseDragged: theEvent];
5668 @end /* EmacsWindow */
5671 /* ==========================================================================
5673     EmacsScroller implementation
5675    ========================================================================== */
5678 @implementation EmacsScroller
5680 /* for repeat button push */
5681 #define SCROLL_BAR_FIRST_DELAY 0.5
5682 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
5684 + (CGFloat) scrollerWidth
5686   /* TODO: if we want to allow variable widths, this is the place to do it,
5687            however neither GNUstep nor Cocoa support it very well */
5688   return [NSScroller scrollerWidth];
5692 - initFrame: (NSRect )r window: (Lisp_Object)nwin
5694   NSTRACE (EmacsScroller_initFrame);
5696   r.size.width = [EmacsScroller scrollerWidth];
5697   [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
5698   [self setContinuous: YES];
5699   [self setEnabled: YES];
5701   /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
5702      locked against the top and bottom edges, and right edge on OS X, where
5703      scrollers are on right. */
5704 #ifdef NS_IMPL_GNUSTEP
5705   [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
5706 #else
5707   [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
5708 #endif
5710   win = nwin;
5711   condemned = NO;
5712   pixel_height = NSHeight (r);
5713   min_portion = 20 / pixel_height;
5715   frame = XFRAME (XWINDOW (win)->frame);
5716   if (FRAME_LIVE_P (frame))
5717     {
5718       int i;
5719       EmacsView *view = FRAME_NS_VIEW (frame);
5720       NSView *sview = [[view window] contentView];
5721       NSArray *subs = [sview subviews];
5723       /* disable optimization stopping redraw of other scrollbars */
5724       view->scrollbarsNeedingUpdate = 0;
5725       for (i =[subs count]-1; i >= 0; i--)
5726         if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
5727           view->scrollbarsNeedingUpdate++;
5728       [sview addSubview: self];
5729     }
5731 /*  [self setFrame: r]; */
5733   return self;
5737 - (void)setFrame: (NSRect)newRect
5739   NSTRACE (EmacsScroller_setFrame);
5740 /*  BLOCK_INPUT; */
5741   pixel_height = NSHeight (newRect);
5742   min_portion = 20 / pixel_height;
5743   [super setFrame: newRect];
5744   [self display];
5745 /*  UNBLOCK_INPUT; */
5749 - (void)dealloc
5751   NSTRACE (EmacsScroller_dealloc);
5752   if (!NILP (win))
5753     XWINDOW (win)->vertical_scroll_bar = Qnil;
5754   [super dealloc];
5758 - condemn
5760   NSTRACE (condemn);
5761   condemned =YES;
5762   return self;
5766 - reprieve
5768   NSTRACE (reprieve);
5769   condemned =NO;
5770   return self;
5774 - judge
5776   NSTRACE (judge);
5777   if (condemned)
5778     {
5779       BLOCK_INPUT;
5780       /* ensure other scrollbar updates after deletion */
5781       EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
5782       if (view != nil)
5783         view->scrollbarsNeedingUpdate++;
5784       [self removeFromSuperview];
5785       [self release];
5786       UNBLOCK_INPUT;
5787     }
5788   return self;
5792 - (void)resetCursorRects
5794   NSRect visible = [self visibleRect];
5795   NSTRACE (resetCursorRects);
5797   if (!NSIsEmptyRect (visible))
5798     [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
5799   [[NSCursor arrowCursor] setOnMouseEntered: YES];
5803 - (int) checkSamePosition: (int) position portion: (int) portion
5804                     whole: (int) whole
5806   return em_position ==position && em_portion ==portion && em_whole ==whole
5807     && portion != whole; /* needed for resize empty buf */
5811 - setPosition: (int)position portion: (int)portion whole: (int)whole
5813   NSTRACE (setPosition);
5815   em_position = position;
5816   em_portion = portion;
5817   em_whole = whole;
5819   if (portion >= whole)
5820     [self setFloatValue: 0.0 knobProportion: 1.0];
5821   else
5822     {
5823       float pos, por;
5824       portion = max ((float)whole*min_portion/pixel_height, portion);
5825       pos = (float)position / (whole - portion);
5826       por = (float)portion/whole;
5827       [self setFloatValue: pos knobProportion: por];
5828     }
5829   return self;
5832 /* FIXME: unused at moment (see ns_mouse_position) at the moment because
5833      drag events will go directly to the EmacsScroller.  Leaving in for now. */
5834 -(void)getMouseMotionPart: (int *)part window: (Lisp_Object *)window
5835                         x: (Lisp_Object *)x y: ( Lisp_Object *)y
5837   *part = last_hit_part;
5838   *window = win;
5839   XSETINT (*y, pixel_height);
5840   if ([self floatValue] > 0.999)
5841     XSETINT (*x, pixel_height);
5842   else
5843     XSETINT (*x, pixel_height * [self floatValue]);
5847 /* set up emacs_event */
5848 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
5850   if (!emacs_event)
5851     return;
5853   emacs_event->part = last_hit_part;
5854   emacs_event->code = 0;
5855   emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
5856   emacs_event->frame_or_window = win;
5857   emacs_event->timestamp = EV_TIMESTAMP (e);
5858   emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
5859   emacs_event->arg = Qnil;
5860   XSETINT (emacs_event->x, loc * pixel_height);
5861   XSETINT (emacs_event->y, pixel_height-20);
5863   n_emacs_events_pending++;
5864   kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
5865   EVENT_INIT (*emacs_event);
5866   ns_send_appdefined (-1);
5870 /* called manually thru timer to implement repeated button action w/hold-down */
5871 - repeatScroll: (NSTimer *)scrollEntry
5873   NSEvent *e = [[self window] currentEvent];
5874   NSPoint p =  [[self window] mouseLocationOutsideOfEventStream];
5875   BOOL inKnob = [self testPart: p] == NSScrollerKnob;
5877   /* clear timer if need be */
5878   if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
5879     {
5880         [scroll_repeat_entry invalidate];
5881         [scroll_repeat_entry release];
5882         scroll_repeat_entry = nil;
5884         if (inKnob)
5885           return self;
5887         scroll_repeat_entry
5888           = [[NSTimer scheduledTimerWithTimeInterval:
5889                         SCROLL_BAR_CONTINUOUS_DELAY
5890                                             target: self
5891                                           selector: @selector (repeatScroll:)
5892                                           userInfo: 0
5893                                            repeats: YES]
5894               retain];
5895     }
5897   [self sendScrollEventAtLoc: 0 fromEvent: e];
5898   return self;
5902 /* Asynchronous mouse tracking for scroller.  This allows us to dispatch
5903    mouseDragged events without going into a modal loop. */
5904 - (void)mouseDown: (NSEvent *)e
5906   NSRect sr, kr;
5907   /* hitPart is only updated AFTER event is passed on */
5908   NSScrollerPart part = [self testPart: [e locationInWindow]];
5909   double inc = 0.0, loc, kloc, pos;
5910   int edge = 0;
5912   NSTRACE (EmacsScroller_mouseDown);
5914   switch (part)
5915     {
5916     case NSScrollerDecrementPage:
5917         last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
5918     case NSScrollerIncrementPage:
5919         last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
5920     case NSScrollerDecrementLine:
5921       last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
5922     case NSScrollerIncrementLine:
5923       last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
5924     case NSScrollerKnob:
5925       last_hit_part = scroll_bar_handle; break;
5926     case NSScrollerKnobSlot:  /* GNUstep-only */
5927       last_hit_part = scroll_bar_move_ratio; break;
5928     default:  /* NSScrollerNoPart? */
5929       fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
5930                (long) part);
5931       return;
5932     }
5934   if (inc != 0.0)
5935     {
5936       pos = 0;      /* ignored */
5938       /* set a timer to repeat, as we can't let superclass do this modally */
5939       scroll_repeat_entry
5940         = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
5941                                             target: self
5942                                           selector: @selector (repeatScroll:)
5943                                           userInfo: 0
5944                                            repeats: YES]
5945             retain];
5946     }
5947   else
5948     {
5949       /* handle, or on GNUstep possibly slot */
5950       NSEvent *fake_event;
5952       /* compute float loc in slot and mouse offset on knob */
5953       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
5954                       toView: nil];
5955       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
5956       if (loc <= 0.0)
5957         {
5958           loc = 0.0;
5959           edge = -1;
5960         }
5961       else if (loc >= NSHeight (sr))
5962         {
5963           loc = NSHeight (sr);
5964           edge = 1;
5965         }
5967       if (edge)
5968         kloc = 0.5 * edge;
5969       else
5970         {
5971           kr = [self convertRect: [self rectForPart: NSScrollerKnob]
5972                           toView: nil];
5973           kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
5974         }
5975       last_mouse_offset = kloc;
5977       /* if knob, tell emacs a location offset by knob pos
5978          (to indicate top of handle) */
5979       if (part == NSScrollerKnob)
5980           pos = (loc - last_mouse_offset) / NSHeight (sr);
5981       else
5982         /* else this is a slot click on GNUstep: go straight there */
5983         pos = loc / NSHeight (sr);
5985       /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
5986       fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
5987                                       location: [e locationInWindow]
5988                                  modifierFlags: [e modifierFlags]
5989                                      timestamp: [e timestamp]
5990                                   windowNumber: [e windowNumber]
5991                                        context: [e context]
5992                                    eventNumber: [e eventNumber]
5993                                     clickCount: [e clickCount]
5994                                       pressure: [e pressure]];
5995       [super mouseUp: fake_event];
5996     }
5998   if (part != NSScrollerKnob)
5999     [self sendScrollEventAtLoc: pos fromEvent: e];
6003 /* Called as we manually track scroller drags, rather than superclass. */
6004 - (void)mouseDragged: (NSEvent *)e
6006     NSRect sr;
6007     double loc, pos;
6008     int edge = 0;
6010     NSTRACE (EmacsScroller_mouseDragged);
6012       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6013                       toView: nil];
6014       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6016       if (loc <= 0.0)
6017         {
6018           loc = 0.0;
6019           edge = -1;
6020         }
6021       else if (loc >= NSHeight (sr) + last_mouse_offset)
6022         {
6023           loc = NSHeight (sr) + last_mouse_offset;
6024           edge = 1;
6025         }
6027       pos = /*(edge ? loc :*/ (loc - last_mouse_offset) / NSHeight (sr);
6028       [self sendScrollEventAtLoc: pos fromEvent: e];
6032 - (void)mouseUp: (NSEvent *)e
6034   if (scroll_repeat_entry)
6035     {
6036       [scroll_repeat_entry invalidate];
6037       [scroll_repeat_entry release];
6038       scroll_repeat_entry = nil;
6039     }
6040   last_hit_part = 0;
6044 /* treat scrollwheel events in the bar as though they were in the main window */
6045 - (void) scrollWheel: (NSEvent *)theEvent
6047   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
6048   [view mouseDown: theEvent];
6051 @end  /* EmacsScroller */
6056 /* ==========================================================================
6058    Font-related functions; these used to be in nsfaces.m
6060    ========================================================================== */
6063 Lisp_Object
6064 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
6066   struct font *font = XFONT_OBJECT (font_object);
6068   if (fontset < 0)
6069     fontset = fontset_from_font (font_object);
6070   FRAME_FONTSET (f) = fontset;
6072   if (FRAME_FONT (f) == font)
6073     /* This font is already set in frame F.  There's nothing more to
6074        do.  */
6075     return font_object;
6077   FRAME_FONT (f) = font;
6079   FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
6080   FRAME_COLUMN_WIDTH (f) = font->average_width;
6081   FRAME_SPACE_WIDTH (f) = font->space_width;
6082   FRAME_LINE_HEIGHT (f) = font->height;
6084   compute_fringe_widths (f, 1);
6086   /* Compute the scroll bar width in character columns.  */
6087   if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
6088     {
6089       int wid = FRAME_COLUMN_WIDTH (f);
6090       FRAME_CONFIG_SCROLL_BAR_COLS (f)
6091         = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
6092     }
6093   else
6094     {
6095       int wid = FRAME_COLUMN_WIDTH (f);
6096       FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
6097     }
6099   /* Now make the frame display the given font.  */
6100   if (FRAME_NS_WINDOW (f) != 0)
6101         x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
6103   return font_object;
6107 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
6108 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
6109          in 1.43. */
6111 const char *
6112 ns_xlfd_to_fontname (const char *xlfd)
6113 /* --------------------------------------------------------------------------
6114     Convert an X font name (XLFD) to an NS font name.
6115     Only family is used.
6116     The string returned is temporarily allocated.
6117    -------------------------------------------------------------------------- */
6119   char *name = xmalloc (180);
6120   int i, len;
6121   const char *ret;
6123   if (!strncmp (xlfd, "--", 2))
6124     sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
6125   else
6126     sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
6128   /* stopgap for malformed XLFD input */
6129   if (strlen (name) == 0)
6130     strcpy (name, "Monaco");
6132   /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
6133      also uppercase after '-' or ' ' */
6134   name[0] = toupper (name[0]);
6135   for (len =strlen (name), i =0; i<len; i++)
6136     {
6137       if (name[i] == '$')
6138         {
6139           name[i] = '-';
6140           if (i+1<len)
6141             name[i+1] = toupper (name[i+1]);
6142         }
6143       else if (name[i] == '_')
6144         {
6145           name[i] = ' ';
6146           if (i+1<len)
6147             name[i+1] = toupper (name[i+1]);
6148         }
6149     }
6150 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name);  */
6151   ret = [[NSString stringWithUTF8String: name] UTF8String];
6152   xfree (name);
6153   return ret;
6157 void
6158 syms_of_nsterm ()
6160   NSTRACE (syms_of_nsterm);
6161   DEFVAR_LISP ("ns-input-file", &ns_input_file,
6162               "The file specified in the last NS event.");
6163   ns_input_file =Qnil;
6165   DEFVAR_LISP ("ns-input-text", &ns_input_text,
6166               "The data received in the last NS text drag event.");
6167   ns_input_text =Qnil;
6169   DEFVAR_LISP ("ns-working-text", &ns_working_text,
6170               "String for visualizing working composition sequence.");
6171   ns_working_text =Qnil;
6173   DEFVAR_LISP ("ns-input-font", &ns_input_font,
6174               "The font specified in the last NS event.");
6175   ns_input_font =Qnil;
6177   DEFVAR_LISP ("ns-input-fontsize", &ns_input_fontsize,
6178               "The fontsize specified in the last NS event.");
6179   ns_input_fontsize =Qnil;
6181   DEFVAR_LISP ("ns-input-line", &ns_input_line,
6182                "The line specified in the last NS event.");
6183   ns_input_line =Qnil;
6185   DEFVAR_LISP ("ns-input-color", &ns_input_color,
6186                "The color specified in the last NS event.");
6187   ns_input_color =Qnil;
6189   DEFVAR_LISP ("ns-input-spi-name", &ns_input_spi_name,
6190                "The service name specified in the last NS event.");
6191   ns_input_spi_name =Qnil;
6193   DEFVAR_LISP ("ns-input-spi-arg", &ns_input_spi_arg,
6194                "The service argument specified in the last NS event.");
6195   ns_input_spi_arg =Qnil;
6197   DEFVAR_LISP ("ns-alternate-modifier", &ns_alternate_modifier,
6198                "This variable describes the behavior of the alternate or option key.\n\
6199 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6200 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6201 at all, allowing it to be used at a lower level for accented character entry.");
6203   DEFVAR_LISP ("ns-command-modifier", &ns_command_modifier,
6204                "This variable describes the behavior of the command key.\n\
6205 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6207   DEFVAR_LISP ("ns-control-modifier", &ns_control_modifier,
6208                "This variable describes the behavior of the control key.\n\
6209 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6211   DEFVAR_LISP ("ns-function-modifier", &ns_function_modifier,
6212                "This variable describes the behavior of the function key (on laptops).\n\
6213 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6214 Set to none means that the function key is not interpreted by Emacs at all,\n\
6215 allowing it to be used at a lower level for accented character entry.");
6217   DEFVAR_LISP ("ns-antialias-text", &ns_antialias_text,
6218                "Non-nil (the default) means to render text antialiased. Only has an effect on OS X Panther and above.");
6220   DEFVAR_LISP ("ns-confirm-quit", &ns_confirm_quit,
6221                "Whether to confirm application quit using dialog.");
6223   staticpro (&ns_display_name_list);
6224   ns_display_name_list = Qnil;
6226   staticpro (&last_mouse_motion_frame);
6227   last_mouse_motion_frame = Qnil;
6229   /* from 23+ we need to tell emacs what modifiers there are.. */
6230   Qmodifier_value = intern ("modifier-value");
6231   Qalt = intern ("alt");
6232   Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
6233   Qhyper = intern ("hyper");
6234   Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
6235   Qmeta = intern ("meta");
6236   Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
6237   Qsuper = intern ("super");
6238   Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
6239   Qcontrol = intern ("control");
6240   Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
6242   /* TODO: move to common code */
6243   DEFVAR_LISP ("x-toolkit-scroll-bars", &Vx_toolkit_scroll_bars,
6244                doc: /* If not nil, Emacs uses toolkit scroll bars.  */);
6245 #ifdef USE_TOOLKIT_SCROLL_BARS
6246   Vx_toolkit_scroll_bars = Qt;
6247 #else
6248   Vx_toolkit_scroll_bars = Qnil;
6249 #endif
6251   /* these are unsupported but we need the declarations to avoid whining
6252      messages from cus-start.el */
6253   DEFVAR_BOOL ("x-use-underline-position-properties",
6254                &x_use_underline_position_properties,
6255      doc: /* NOT SUPPORTED UNDER NS.
6256 *Non-nil means make use of UNDERLINE_POSITION font properties.
6257 A value of nil means ignore them.  If you encounter fonts with bogus
6258 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
6259 to 4.1, set this to nil.
6261 NOTE: Not supported on Mac yet.  */);
6262   x_use_underline_position_properties = 0;
6264   DEFVAR_BOOL ("x-underline-at-descent-line",
6265                &x_underline_at_descent_line,
6266      doc: /* NOT SUPPORTED UNDER NS.
6267 *Non-nil means to draw the underline at the same place as the descent line.
6268 A value of nil means to draw the underline according to the value of the
6269 variable `x-use-underline-position-properties', which is usually at the
6270 baseline level.  The default value is nil.  */);
6271   x_underline_at_descent_line = 0;
6273   /* Tell emacs about this window system. */
6274   Fprovide (intern ("ns"), Qnil);
6278 // arch-tag: 6eaa8f7d-a69b-4e1c-b43d-ab31defbe0d2