(ispell-check-minver): Declare.
[emacs.git] / src / nsterm.m
blob3c79acea2dfdedbae4a336012188b36abae6d42c
1 /* NeXT/Open/GNUstep / MacOSX communication module.
2    Copyright (C) 1989, 1993, 1994, 2005, 2006, 2008, 2009
3      Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.  */
21 Originally by Carl Edman
22 Updated by Christian Limpach (chris@nice.ch)
23 OpenStep/Rhapsody port by Scott Bender (sbender@harmony-ds.com)
24 MacOSX/Aqua port by Christophe de Dinechin (descubes@earthlink.net)
25 GNUstep port and post-20 update by Adrian Robert (arobert@cogsci.ucsd.edu)
28 /* This should be the first include, as it may set up #defines affecting
29    interpretation of even the system includes. */
30 #include "config.h"
32 #include <math.h>
33 #include <sys/types.h>
34 #include <time.h>
35 #include <unistd.h>
37 #include "lisp.h"
38 #include "blockinput.h"
39 #include "sysselect.h"
40 #include "nsterm.h"
41 #include "systime.h"
42 #include "character.h"
43 #include "fontset.h"
44 #include "composite.h"
45 #include "ccl.h"
47 #include "termhooks.h"
48 #include "termopts.h"
49 #include "termchar.h"
51 #include "window.h"
52 #include "keyboard.h"
54 #include "font.h"
56 /* call tracing */
57 #if 0
58 int term_trace_num = 0;
59 #define NSTRACE(x)        fprintf (stderr, "%s:%d: [%d] " #x "\n",         \
60                                 __FILE__, __LINE__, ++term_trace_num)
61 #else
62 #define NSTRACE(x)
63 #endif
66 /* ==========================================================================
68     Local declarations
70    ========================================================================== */
72 /* Special keycodes that we pass down the event chain */
73 #define KEY_NS_POWER_OFF               ((1<<28)|(0<<16)|1)
74 #define KEY_NS_OPEN_FILE               ((1<<28)|(0<<16)|2)
75 #define KEY_NS_OPEN_TEMP_FILE          ((1<<28)|(0<<16)|3)
76 #define KEY_NS_DRAG_FILE               ((1<<28)|(0<<16)|4)
77 #define KEY_NS_DRAG_COLOR              ((1<<28)|(0<<16)|5)
78 #define KEY_NS_DRAG_TEXT               ((1<<28)|(0<<16)|6)
79 #define KEY_NS_CHANGE_FONT             ((1<<28)|(0<<16)|7)
80 #define KEY_NS_OPEN_FILE_LINE          ((1<<28)|(0<<16)|8)
81 #define KEY_NS_INSERT_WORKING_TEXT     ((1<<28)|(0<<16)|9)
82 #define KEY_NS_DELETE_WORKING_TEXT     ((1<<28)|(0<<16)|10)
83 #define KEY_NS_SPI_SERVICE_CALL        ((1<<28)|(0<<16)|11)
84 #define KEY_NS_NEW_FRAME               ((1<<28)|(0<<16)|12)
86 /* Convert a symbol indexed with an NSxxx value to a value as defined
87    in keyboard.c (lispy_function_key). I hope this is a correct way
88    of doing things... */
89 static unsigned convert_ns_to_X_keysym[] =
91   NSHomeFunctionKey,            0x50,
92   NSLeftArrowFunctionKey,       0x51,
93   NSUpArrowFunctionKey,         0x52,
94   NSRightArrowFunctionKey,      0x53,
95   NSDownArrowFunctionKey,       0x54,
96   NSPageUpFunctionKey,          0x55,
97   NSPageDownFunctionKey,        0x56,
98   NSEndFunctionKey,             0x57,
99   NSBeginFunctionKey,           0x58,
100   NSSelectFunctionKey,          0x60,
101   NSPrintFunctionKey,           0x61,
102   NSExecuteFunctionKey,         0x62,
103   NSInsertFunctionKey,          0x63,
104   NSUndoFunctionKey,            0x65,
105   NSRedoFunctionKey,            0x66,
106   NSMenuFunctionKey,            0x67,
107   NSFindFunctionKey,            0x68,
108   NSHelpFunctionKey,            0x6A,
109   NSBreakFunctionKey,           0x6B,
111   NSF1FunctionKey,              0xBE,
112   NSF2FunctionKey,              0xBF,
113   NSF3FunctionKey,              0xC0,
114   NSF4FunctionKey,              0xC1,
115   NSF5FunctionKey,              0xC2,
116   NSF6FunctionKey,              0xC3,
117   NSF7FunctionKey,              0xC4,
118   NSF8FunctionKey,              0xC5,
119   NSF9FunctionKey,              0xC6,
120   NSF10FunctionKey,             0xC7,
121   NSF11FunctionKey,             0xC8,
122   NSF12FunctionKey,             0xC9,
123   NSF13FunctionKey,             0xCA,
124   NSF14FunctionKey,             0xCB,
125   NSF15FunctionKey,             0xCC,
127   NSBackspaceCharacter,         0x08,  /* 8: Not on some KBs. */
128   NSDeleteCharacter,            0xFF,  /* 127: Big 'delete' key upper right. */
129   NSDeleteFunctionKey,          0x9F,  /* 63272: Del forw key off main array. */
131   NSTabCharacter,               0x09,
132   0x19,                         0x09,  /* left tab->regular since pass shift */
133   NSCarriageReturnCharacter,    0x0D,
134   NSNewlineCharacter,           0x0D,
135   NSEnterCharacter,             0x8D,
137   0x1B,                         0x1B   /* escape */
141 /* Lisp communications */
142 Lisp_Object ns_input_file, ns_input_font, ns_input_fontsize, ns_input_line;
143 Lisp_Object ns_input_color, ns_input_text, ns_working_text;
144 Lisp_Object ns_input_spi_name, ns_input_spi_arg;
145 Lisp_Object Vx_toolkit_scroll_bars;
146 static Lisp_Object Qmodifier_value;
147 /* TODO: unsure why these defined in term files, anyway we need in keymap.c */
148 Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper;
149 extern Lisp_Object Qcursor_color, Qcursor_type, Qns;
152 EmacsPrefsController *prefsController;
154 /* Defaults managed through the OpenStep defaults system.  These pertain to
155    the NS interface specifically.  Although a customization group could be
156    created, it's more natural to manage them via defaults. */
158 /* Specifies which emacs modifier should be generated when NS receives
159    the Alternate modifer.  May be Qnone or any of the modifier lisp symbols. */
160 Lisp_Object ns_alternate_modifier;
162 /* Specifies which emacs modifier should be generated when NS receives
163    the Command modifer.  May be any of the modifier lisp symbols. */
164 Lisp_Object ns_command_modifier;
166 /* Specifies which emacs modifier should be generated when NS receives
167    the Control modifer.  May be any of the modifier lisp symbols. */
168 Lisp_Object ns_control_modifier;
170 /* Specifies which emacs modifier should be generated when NS receives
171    the Function modifer (laptops).  May be any of the modifier lisp symbols. */
172 Lisp_Object ns_function_modifier;
174 /* A floating point value specifying vertical stretch (positive) or shrink
175   (negative) of text line spacing.  Zero means default spacing.
176   YES indicates 0.5, NO indicates 0.0. */
177 Lisp_Object ns_expand_space;
179 /* Control via default 'GSFontAntiAlias' on OS X and GNUstep. */
180 Lisp_Object ns_antialias_text;
182 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
183    the maximum font size to NOT antialias.  On GNUstep there is currently
184    no way to control this behavior. */
185 float ns_antialias_threshold;
187 /* Controls use of an undocumented CG function to do Quickdraw-style font
188    smoothing (less heavy) instead of regular Quartz smoothing. */
189 Lisp_Object ns_use_qd_smoothing;
191 /* Used to pick up AppleHighlightColor on OS X */
192 Lisp_Object ns_use_system_highlight_color;
193 NSString *ns_selection_color;
196 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
198 /* Display variables */
199 struct ns_display_info *x_display_list; /* Chain of existing displays */
200 Lisp_Object ns_display_name_list;
201 long context_menu_value = 0;
203 /* display update */
204 NSPoint last_mouse_motion_position;
205 static NSRect last_mouse_glyph;
206 static unsigned long last_mouse_movement_time = 0;
207 static Lisp_Object last_mouse_motion_frame;
208 static EmacsScroller *last_mouse_scroll_bar = nil;
209 static struct frame *ns_updating_frame;
210 static NSView *focus_view = NULL;
211 static int ns_window_num =0;
212 static NSRect uRect;
213 static BOOL gsaved = NO;
214 BOOL ns_in_resize = NO;
215 int ns_tmp_flags; /* FIXME */
216 struct nsfont_info *ns_tmp_font; /* FIXME */
217 /*static int debug_lock = 0; */
219 #ifdef NS_IMPL_COCOA
220 /* This undocumented Quartz function controls how fonts are anti-aliased.
221    (Found from code in Mac wxWindows impl, discovered by running `nm' on
222    the "QD" framework.)
223    Mode 0 is normal anti-aliasing, mode 1 is no anti-aliasing, and mode 2 is
224    4-bit pixel-aligned anti-aliasing (the old QuickDraw standard). */
225 extern void CGContextSetFontRenderingMode (CGContextRef cg, int v);
226 #endif
229 /* event loop */
230 static BOOL send_appdefined = YES;
231 static NSEvent *last_appdefined_event = 0;
232 static NSTimer *timed_entry = 0;
233 static NSTimer *fd_entry = nil;
234 static NSTimer *scroll_repeat_entry = nil;
235 static fd_set select_readfds, t_readfds;
236 static struct timeval select_timeout;
237 static int select_nfds;
238 static NSAutoreleasePool *outerpool;
239 static BOOL ns_shutdown_properly = NO;
240 static struct input_event *emacs_event = NULL;
241 static struct input_event *q_event_ptr = NULL;
242 static int n_emacs_events_pending = 0;
243 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
244   *ns_pending_service_args;
245 static BOOL inNsSelect = 0;
247 /* Convert modifiers in a NeXTSTEP event to emacs style modifiers.  */
248 #define NS_FUNCTION_KEY_MASK 0x800000
249 #define EV_MODIFIERS(e)                               \
250     ((([e modifierFlags] & NSHelpKeyMask) ?           \
251            hyper_modifier : 0)                        \
252      | (([e modifierFlags] & NSAlternateKeyMask) ?    \
253            parse_solitary_modifier (ns_alternate_modifier) : 0)   \
254      | (([e modifierFlags] & NSShiftKeyMask) ?        \
255            shift_modifier : 0)                        \
256      | (([e modifierFlags] & NSControlKeyMask) ?      \
257            parse_solitary_modifier (ns_control_modifier) : 0)     \
258      | (([e modifierFlags] & NS_FUNCTION_KEY_MASK) ?  \
259            parse_solitary_modifier (ns_function_modifier) : 0)    \
260      | (([e modifierFlags] & NSCommandKeyMask) ?      \
261            parse_solitary_modifier (ns_command_modifier):0))
263 #define EV_UDMODIFIERS(e)                                      \
264     ((([e type] == NSLeftMouseDown) ? down_modifier : 0)       \
265      | (([e type] == NSRightMouseDown) ? down_modifier : 0)    \
266      | (([e type] == NSOtherMouseDown) ? down_modifier : 0)    \
267      | (([e type] == NSLeftMouseDragged) ? down_modifier : 0)  \
268      | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
269      | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
270      | (([e type] == NSLeftMouseUp)   ? up_modifier   : 0)     \
271      | (([e type] == NSRightMouseUp)   ? up_modifier   : 0)    \
272      | (([e type] == NSOtherMouseUp)   ? up_modifier   : 0))
274 #define EV_BUTTON(e)                                                         \
275     ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 :    \
276       (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
277      [e buttonNumber] - 1)
279 /* Convert the time field to a timestamp in milliseconds. */
280 #ifdef NS_IMPL_GNUSTEP
281 /* Apple says timestamp is in seconds, but GNUstep seems to be returning msec */
282 #define EV_TIMESTAMP(e) ([e timestamp])
283 #else
284 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
285 #endif /* not gnustep */
287 /* This is a piece of code which is common to all the event handling
288    methods.  Maybe it should even be a function.  */
289 #define EV_TRAILER(e)                                         \
290   {                                                           \
291   XSETFRAME (emacs_event->frame_or_window, [NSApp isActive] ? \
292              emacsframe : SELECTED_FRAME ());                 \
293   if (e) emacs_event->timestamp = EV_TIMESTAMP (e);           \
294   n_emacs_events_pending++;                                   \
295   kbd_buffer_store_event_hold (emacs_event, q_event_ptr);     \
296   EVENT_INIT (*emacs_event);                                  \
297   ns_send_appdefined (-1);                                    \
298   }
300 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
302 /* TODO: get rid of need for these forward declarations */
303 static void ns_condemn_scroll_bars (struct frame *f);
304 static void ns_judge_scroll_bars (struct frame *f);
306 /* unused variables needed for compatibility reasons */
307 int x_use_underline_position_properties, x_underline_at_descent_line;
308 /* FIXME: figure out what to do with underline_minimum_offset. */
311 /* ==========================================================================
313     Utilities
315    ========================================================================== */
318 static Lisp_Object
319 append2 (Lisp_Object list, Lisp_Object item)
320 /* --------------------------------------------------------------------------
321    Utility to append to a list
322    -------------------------------------------------------------------------- */
324   Lisp_Object array[2];
325   array[0] = list;
326   array[1] = Fcons (item, Qnil);
327   return Fnconc (2, &array[0]);
331 void
332 ns_init_paths ()
333 /* --------------------------------------------------------------------------
334    Used to allow emacs to find its resources under Emacs.app
335    Called from emacs.c at startup.
336    -------------------------------------------------------------------------- */
338   NSBundle *bundle = [NSBundle mainBundle];
339   NSString *binDir = [bundle bundlePath], *resourceDir = [bundle resourcePath];
340   NSString *resourcePath, *resourcePaths;
341   NSRange range;
342   BOOL onWindows = NO; /* how do I determine this? */
343   NSString *pathSeparator = onWindows ? @";" : @":";
344   NSFileManager *fileManager = [NSFileManager defaultManager];
345   BOOL isDir;
346 /*NSLog (@"ns_init_paths: '%@'\n%@\n", [[NSBundle mainBundle] bundlePath], [[NSBundle mainBundle] resourcePath]); */
348   /* get bindir from base */
349   range = [resourceDir rangeOfString: @"Contents"];
350   if (range.location != NSNotFound)
351     {
352       binDir = [binDir stringByAppendingPathComponent: @"Contents"];
353 #ifdef NS_IMPL_COCOA
354       binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
355 #endif
356     }
358   /* the following based on Andrew Choi's init_mac_osx_environment () */
359   if (!getenv ("EMACSLOADPATH"))
360     {
361       NSArray *paths = [resourceDir stringsByAppendingPaths:
362                                   [NSArray arrayWithObjects:
363                                          @"site-lisp", @"lisp", @"leim", nil]];
364       NSEnumerator *pathEnum = [paths objectEnumerator];
365       resourcePaths = @"";
366       while (resourcePath = [pathEnum nextObject])
367         {
368           if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
369             if (isDir)
370               {
371                 if ([resourcePaths length] > 0)
372                   resourcePaths
373                     = [resourcePaths stringByAppendingString: pathSeparator];
374                 resourcePaths
375                   = [resourcePaths stringByAppendingString: resourcePath];
376               }
377         }
378       if ([resourcePaths length] > 0)
379         setenv ("EMACSLOADPATH", [resourcePaths UTF8String], 1);
380 /*NSLog (@"loadPath: '%s'\n", resourcePaths); */
381     }
383   if (!getenv ("EMACSPATH"))
384     {
385       NSArray *paths = [binDir stringsByAppendingPaths:
386                                   [NSArray arrayWithObjects: @"bin",
387                                                              @"lib-exec", nil]];
388       NSEnumerator *pathEnum = [paths objectEnumerator];
389       resourcePaths = @"";
390       while (resourcePath = [pathEnum nextObject])
391         {
392           if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
393             if (isDir)
394               {
395                 if ([resourcePaths length] > 0)
396                   resourcePaths
397                     = [resourcePaths stringByAppendingString: pathSeparator];
398                 resourcePaths
399                   = [resourcePaths stringByAppendingString: resourcePath];
400               }
401         }
402       if ([resourcePaths length] > 0)
403         setenv ("EMACSPATH", [resourcePaths UTF8String], 1);
404     }
406   resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
407   if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
408     {
409       if (isDir)
410         {
411           if (!getenv ("EMACSDATA"))
412             setenv ("EMACSDATA", [resourcePath UTF8String], 1);
413           if (!getenv ("EMACSDOC"))
414             setenv ("EMACSDOC", [resourcePath UTF8String], 1);
415         }
416     }
418   if (!getenv ("INFOPATH"))
419     {
420       resourcePath = [resourceDir stringByAppendingPathComponent: @"info"];
421       if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
422         if (isDir)
423           setenv ("INFOPATH", [resourcePath UTF8String], 1);
424     }
428 static int
429 timeval_subtract (struct timeval *result, struct timeval x, struct timeval y)
430 /* --------------------------------------------------------------------------
431    Subtract the `struct timeval' values X and Y, storing the result in RESULT.
432    Return 1 if the difference is negative, otherwise 0.
433    -------------------------------------------------------------------------- */
435   /* Perform the carry for the later subtraction by updating y.
436      This is safer because on some systems
437      the tv_sec member is unsigned.  */
438   if (x.tv_usec < y.tv_usec)
439     {
440       int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
441       y.tv_usec -= 1000000 * nsec;
442       y.tv_sec += nsec;
443     }
444   if (x.tv_usec - y.tv_usec > 1000000)
445     {
446       int nsec = (y.tv_usec - x.tv_usec) / 1000000;
447       y.tv_usec += 1000000 * nsec;
448       y.tv_sec -= nsec;
449     }
451   /* Compute the time remaining to wait.  tv_usec is certainly positive.  */
452   result->tv_sec = x.tv_sec - y.tv_sec;
453   result->tv_usec = x.tv_usec - y.tv_usec;
455   /* Return indication of whether the result should be considered negative.  */
456   return x.tv_sec < y.tv_sec;
459 static void
460 ns_timeout (int usecs)
461 /* --------------------------------------------------------------------------
462      Blocking timer utility used by ns_ring_bell
463    -------------------------------------------------------------------------- */
465   struct timeval wakeup;
467   EMACS_GET_TIME (wakeup);
469   /* Compute time to wait until, propagating carry from usecs.  */
470   wakeup.tv_usec += usecs;
471   wakeup.tv_sec += (wakeup.tv_usec / 1000000);
472   wakeup.tv_usec %= 1000000;
474   /* Keep waiting until past the time wakeup.  */
475   while (1)
476     {
477       struct timeval timeout;
479       EMACS_GET_TIME (timeout);
481       /* In effect, timeout = wakeup - timeout.
482          Break if result would be negative.  */
483       if (timeval_subtract (&timeout, wakeup, timeout))
484         break;
486       /* Try to wait that long--but we might wake up sooner.  */
487       select (0, NULL, NULL, NULL, &timeout);
488     }
492 void
493 ns_release_object (void *obj)
494 /* --------------------------------------------------------------------------
495     Release an object (callable from C)
496    -------------------------------------------------------------------------- */
498     [(id)obj release];
502 void
503 ns_retain_object (void *obj)
504 /* --------------------------------------------------------------------------
505     Retain an object (callable from C)
506    -------------------------------------------------------------------------- */
508     [(id)obj retain];
512 void *
513 ns_alloc_autorelease_pool ()
514 /* --------------------------------------------------------------------------
515      Allocate a pool for temporary objects (callable from C)
516    -------------------------------------------------------------------------- */
518   return [[NSAutoreleasePool alloc] init];
522 void
523 ns_release_autorelease_pool (void *pool)
524 /* --------------------------------------------------------------------------
525      Free a pool and temporary objects it refers to (callable from C)
526    -------------------------------------------------------------------------- */
528   ns_release_object (pool);
533 /* ==========================================================================
535     Focus (clipping) and screen update
537    ========================================================================== */
539 static NSRect
540 ns_resize_handle_rect (NSWindow *window)
542   NSRect r = [window frame];
543   r.origin.x = r.size.width - RESIZE_HANDLE_SIZE;
544   r.origin.y = 0;
545   r.size.width = r.size.height = RESIZE_HANDLE_SIZE;
546   return r;
550 static void
551 ns_update_begin (struct frame *f)
552 /* --------------------------------------------------------------------------
553    Prepare for a grouped sequence of drawing calls
554    23: external (RIF) call; now split w/ and called before update_window_begin
555    -------------------------------------------------------------------------- */
557   NSView *view = FRAME_NS_VIEW (f);
558   NSTRACE (ns_update_begin);
560   ns_updating_frame = f;
561   [view lockFocus];
563 #ifdef NS_IMPL_GNUSTEP
564   uRect = NSMakeRect (0, 0, 0, 0);
565 #endif
569 static void
570 ns_update_window_begin (struct window *w)
571 /* --------------------------------------------------------------------------
572    Prepare for a grouped sequence of drawing calls
573    23: external (RIF) call; now split with and called after update_begin
574    -------------------------------------------------------------------------- */
576   struct frame *f = XFRAME (WINDOW_FRAME (w));
577   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
578   NSTRACE (ns_update_window_begin);
580   updated_window = w;
581   set_output_cursor (&w->cursor);
583   BLOCK_INPUT;
585   if (f == dpyinfo->mouse_face_mouse_frame)
586     {
587       /* Don't do highlighting for mouse motion during the update.  */
588       dpyinfo->mouse_face_defer = 1;
590         /* If the frame needs to be redrawn,
591            simply forget about any prior mouse highlighting.  */
592       if (FRAME_GARBAGED_P (f))
593         dpyinfo->mouse_face_window = Qnil;
595       /* (further code for mouse faces ifdef'd out in other terms elided) */
596     }
598   UNBLOCK_INPUT;
602 static void
603 ns_update_window_end (struct window *w, int cursor_on_p,
604                       int mouse_face_overwritten_p)
605 /* --------------------------------------------------------------------------
606    Finished a grouped sequence of drawing calls
607    23: external (RIF) call; now split with and called before update_window_end
608    -------------------------------------------------------------------------- */
610   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (XFRAME (w->frame));
612   /* note: this fn is nearly identical in all terms */
613   if (!w->pseudo_window_p)
614     {
615       BLOCK_INPUT;
617       if (cursor_on_p)
618         display_and_set_cursor (w, 1,
619                                 output_cursor.hpos, output_cursor.vpos,
620                                 output_cursor.x, output_cursor.y);
622       if (draw_window_fringes (w, 1))
623         x_draw_vertical_border (w);
625       UNBLOCK_INPUT;
626     }
628   /* If a row with mouse-face was overwritten, arrange for
629      frame_up_to_date to redisplay the mouse highlight.  */
630   if (mouse_face_overwritten_p)
631     {
632       dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
633       dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
634       dpyinfo->mouse_face_window = Qnil;
635     }
637   updated_window = NULL;
638   NSTRACE (update_window_end);
642 static void
643 ns_update_end (struct frame *f)
644 /* --------------------------------------------------------------------------
645    Finished a grouped sequence of drawing calls
646    23: external (RIF) call; now split with and called after update_window_end
647    -------------------------------------------------------------------------- */
649   NSView *view = FRAME_NS_VIEW (f);
651 /*   if (f == FRAME_NS_DISPLAY_INFO (f)->mouse_face_mouse_frame) */
652     FRAME_NS_DISPLAY_INFO (f)->mouse_face_defer = 0;
654   BLOCK_INPUT;
656 #ifdef NS_IMPL_GNUSTEP
657   /* trigger flush only in the rectangle we tracked as being drawn */
658   [view unlockFocusNeedsFlush: NO];
659 /*fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", uRect.origin.x, uRect.origin.y, uRect.size.width, uRect.size.height); */
660   [view lockFocusInRect: uRect];
661 #endif
663   [view unlockFocus];
664   [[view window] flushWindow];
666   UNBLOCK_INPUT;
667   ns_updating_frame = NULL;
668   NSTRACE (ns_update_end);
672 static void
673 ns_flush (struct frame *f)
674 /* --------------------------------------------------------------------------
675    23: external (RIF) call
676    NS impl is no-op since currently we flush in ns_update_end and elsewhere
677    -------------------------------------------------------------------------- */
679     NSTRACE (ns_flush);
683 static void
684 ns_focus (struct frame *f, NSRect *r, int n)
685 /* --------------------------------------------------------------------------
686    Internal: Focus on given frame.  During small local updates this is used to
687      draw, however during large updates, ns_update_begin and ns_update_end are
688      called to wrap the whole thing, in which case these calls are stubbed out.
689      Except, on GNUstep, we accumulate the rectangle being drawn into, because
690      the back end won't do this automatically, and will just end up flushing
691      the entire window.
692    -------------------------------------------------------------------------- */
694 //  NSTRACE (ns_focus);
695 #ifdef NS_IMPL_GNUSTEP
696   NSRect u;
697     if (n == 2)
698       u = NSUnionRect (r[0], r[1]);
699     else if (r)
700       u = *r;
701 #endif
702 /* static int c =0;
703    fprintf (stderr, "focus: %d", c++);
704    if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
705    fprintf (stderr, "\n"); */
707   if (f != ns_updating_frame)
708     {
709       NSView *view = FRAME_NS_VIEW (f);
710       if (view != focus_view)
711         {
712           if (focus_view != NULL)
713             {
714               [focus_view unlockFocus];
715               [[focus_view window] flushWindow];
716 /*debug_lock--; */
717             }
719           if (view)
720 #ifdef NS_IMPL_GNUSTEP
721             r ? [view lockFocusInRect: u] : [view lockFocus];
722 #else
723             [view lockFocus];
724 #endif
725           focus_view = view;
726 /*if (view) debug_lock++; */
727         }
728 #ifdef NS_IMPL_GNUSTEP
729       else
730         {
731           /* more than one rect being drawn into */
732           if (view && r)
733             {
734               [view unlockFocus]; /* add prev rect to redraw list */
735               [view lockFocusInRect: u]; /* focus for draw in new rect */
736             }
737         }
738 #endif
739     }
740 #ifdef NS_IMPL_GNUSTEP
741   else
742     {
743       /* in batch mode, but in GNUstep must still track rectangles explicitly */
744       uRect = (r ? NSUnionRect (uRect, u) : [FRAME_NS_VIEW (f) visibleRect]);
745     }
746 #endif
748   /*23: clipping */
749   if (r)
750     {
751       [[NSGraphicsContext currentContext] saveGraphicsState];
752       if (n == 2)
753         NSRectClipList (r, 2);
754       else
755         NSRectClip (*r);
756       gsaved = YES;
757     }
761 static void
762 ns_unfocus (struct frame *f)
763 /* --------------------------------------------------------------------------
764      Internal: Remove focus on given frame
765    -------------------------------------------------------------------------- */
767 //  NSTRACE (ns_unfocus);
769   if (gsaved)
770     {
771       [[NSGraphicsContext currentContext] restoreGraphicsState];
772       gsaved = NO;
773     }
775   if (f != ns_updating_frame)
776     {
777       if (focus_view != NULL)
778         {
779           [focus_view unlockFocus];
780           [[focus_view window] flushWindow];
781           focus_view = NULL;
782 /*debug_lock--; */
783         }
784     }
788 static void
789 ns_clip_to_row (struct window *w, struct glyph_row *row, int area, BOOL gc)
790 /* --------------------------------------------------------------------------
791      23: Internal (but parallels other terms): Focus drawing on given row
792    -------------------------------------------------------------------------- */
794   struct frame *f = XFRAME (WINDOW_FRAME (w));
795   NSRect clip_rect;
796   int window_x, window_y, window_width;
798   window_box (w, area, &window_x, &window_y, &window_width, 0);
800   clip_rect.origin.x = window_x - FRAME_INTERNAL_BORDER_WIDTH (f);
801   clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
802   clip_rect.origin.y = max (clip_rect.origin.y, window_y);
803   clip_rect.size.width = window_width + 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
804   clip_rect.size.height = row->visible_height;
806   /* allow a full-height row at the top when requested
807      (used to draw fringe all the way through internal border area) */
808   if (gc && clip_rect.origin.y < 5)
809     {
810       clip_rect.origin.y -= FRAME_INTERNAL_BORDER_WIDTH (f);
811       clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
812     }
814   /* likewise at bottom */
815   if (gc &&
816       FRAME_PIXEL_HEIGHT (f) - (clip_rect.origin.y + clip_rect.size.height) < 5)
817     clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
819   ns_focus (f, &clip_rect, 1);
823 static void
824 ns_ring_bell ()
825 /* --------------------------------------------------------------------------
826      "Beep" routine
827    -------------------------------------------------------------------------- */
829   NSTRACE (ns_ring_bell);
830   if (visible_bell)
831     {
832       NSAutoreleasePool *pool;
833       struct frame *frame = SELECTED_FRAME ();
834       NSView *view;
836       BLOCK_INPUT;
837       pool = [[NSAutoreleasePool alloc] init];
839       view = FRAME_NS_VIEW (frame);
840       if (view != nil)
841         {
842           NSRect r, surr;
843           NSPoint dim = NSMakePoint (128, 128);
845           r = [view bounds];
846           r.origin.x += (r.size.width - dim.x) / 2;
847           r.origin.y += (r.size.height - dim.y) / 2;
848           r.size.width = dim.x;
849           r.size.height = dim.y;
850           /* XXX: cacheImageInRect under GNUstep does not account for
851              offset in x_set_window_size, so overestimate (4 fine on Cocoa) */
852           surr = NSInsetRect (r, -10, -10);
853           ns_focus (frame, &surr, 1);
854           [[view window] cacheImageInRect: surr];
855           [ns_lookup_indexed_color (NS_FACE_FOREGROUND
856                                       (FRAME_DEFAULT_FACE (frame)), frame) set];
857           NSRectFill (r);
858           [[view window] flushWindow];
859           ns_timeout (150000);
860           [[view window] restoreCachedImage];
861           [[view window] flushWindow];
862           ns_unfocus (frame);
863         }
864       [pool release];
865       UNBLOCK_INPUT;
866     }
867   else
868     {
869       NSBeep ();
870     }
874 static void
875 ns_reset_terminal_modes (struct terminal *terminal)
876 /*  Externally called as hook */
878   NSTRACE (ns_reset_terminal_modes);
881 static void
882 ns_set_terminal_modes (struct terminal *terminal)
883 /*  Externally called as hook */
885   NSTRACE (ns_set_terminal_modes);
890 /* ==========================================================================
892     Frame / window manager related functions
894    ========================================================================== */
897 static void
898 ns_raise_frame (struct frame *f)
899 /* --------------------------------------------------------------------------
900      Bring window to foreground and make it active
901    -------------------------------------------------------------------------- */
903   NSView *view = FRAME_NS_VIEW (f);
904   check_ns ();
905   BLOCK_INPUT;
906   [[view window] makeKeyAndOrderFront: NSApp];
907   UNBLOCK_INPUT;
911 static void
912 ns_lower_frame (struct frame *f)
913 /* --------------------------------------------------------------------------
914      Send window to back
915    -------------------------------------------------------------------------- */
917   NSView *view = FRAME_NS_VIEW (f);
918   check_ns ();
919   BLOCK_INPUT;
920   [[view window] orderBack: NSApp];
921   UNBLOCK_INPUT;
925 static void
926 ns_frame_raise_lower (struct frame *f, int raise)
927 /* --------------------------------------------------------------------------
928      External (hook)
929    -------------------------------------------------------------------------- */
931   NSTRACE (ns_frame_raise_lower);
933   if (raise)
934     ns_raise_frame (f);
935   else
936     ns_lower_frame (f);
940 static void
941 ns_frame_rehighlight (struct frame *frame)
942 /* --------------------------------------------------------------------------
943      External (hook): called on things like window switching within frame
944    -------------------------------------------------------------------------- */
946   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
947   struct frame *old_highlight = dpyinfo->x_highlight_frame;
949   NSTRACE (ns_frame_rehighlight);
950   if (dpyinfo->x_focus_frame)
951     {
952       dpyinfo->x_highlight_frame
953         = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
954            ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
955            : dpyinfo->x_focus_frame);
956       if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
957         {
958           FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
959           dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
960         }
961     }
962   else
963       dpyinfo->x_highlight_frame = 0;
965   if (dpyinfo->x_highlight_frame &&
966          dpyinfo->x_highlight_frame != old_highlight)
967     {
968       if (old_highlight)
969         {
970           x_update_cursor (old_highlight, 1);
971           x_set_frame_alpha (old_highlight);
972         }
973       if (dpyinfo->x_highlight_frame)
974         {
975           x_update_cursor (dpyinfo->x_highlight_frame, 1);
976           x_set_frame_alpha (dpyinfo->x_highlight_frame);
977         }
978     }
982 void
983 x_make_frame_visible (struct frame *f)
984 /* --------------------------------------------------------------------------
985      External: Show the window (X11 semantics)
986    -------------------------------------------------------------------------- */
988   NSTRACE (x_make_frame_visible);
989   /* XXX: at some points in past this was not needed, as the only place that
990      called this (frame.c:Fraise_frame ()) also called raise_lower;
991      if this ends up the case again, comment this out again. */
992   if (!FRAME_VISIBLE_P (f))
993     ns_raise_frame (f);
997 void
998 x_make_frame_invisible (struct frame *f)
999 /* --------------------------------------------------------------------------
1000      External: Hide the window (X11 semantics)
1001    -------------------------------------------------------------------------- */
1003   NSView * view = FRAME_NS_VIEW (f);
1004   NSTRACE (x_make_frame_invisible);
1005   check_ns ();
1006   [[view window] orderOut: NSApp];
1010 void
1011 x_iconify_frame (struct frame *f)
1012 /* --------------------------------------------------------------------------
1013      External: Iconify window
1014    -------------------------------------------------------------------------- */
1016   NSView * view = FRAME_NS_VIEW (f);
1017   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1018   NSTRACE (x_iconify_frame);
1019   check_ns ();
1021   if (dpyinfo->x_highlight_frame == f)
1022     dpyinfo->x_highlight_frame = 0;
1024   if ([[view window] windowNumber] <= 0)
1025     {
1026       /* the window is still deferred.  Make it very small, bring it
1027          on screen and order it out. */
1028       NSRect s = { { 100, 100}, {0, 0} };
1029       NSRect t;
1030       t = [[view window] frame];
1031       [[view window] setFrame: s display: NO];
1032       [[view window] orderBack: NSApp];
1033       [[view window] orderOut: NSApp];
1034       [[view window] setFrame: t display: NO];
1035     }
1036   [[view window] miniaturize: NSApp];
1040 void
1041 x_destroy_window (struct frame *f)
1042 /* --------------------------------------------------------------------------
1043      External: Delete the window
1044    -------------------------------------------------------------------------- */
1046   NSView *view = FRAME_NS_VIEW (f);
1047   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1048   NSTRACE (x_destroy_window);
1049   check_ns ();
1051   [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1053   BLOCK_INPUT;
1055   free_frame_menubar (f);
1057   if (FRAME_FACE_CACHE (f))
1058     free_frame_faces (f);
1060   if (f == dpyinfo->x_focus_frame)
1061     dpyinfo->x_focus_frame = 0;
1062   if (f == dpyinfo->x_highlight_frame)
1063     dpyinfo->x_highlight_frame = 0;
1064   if (f == dpyinfo->mouse_face_mouse_frame)
1065     {
1066       dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
1067       dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
1068       dpyinfo->mouse_face_window = Qnil;
1069       dpyinfo->mouse_face_deferred_gc = 0;
1070       dpyinfo->mouse_face_mouse_frame = 0;
1071     }
1073   xfree (f->output_data.ns);
1075   [[view window] close];
1076   [view release];
1078   ns_window_num--;
1079   UNBLOCK_INPUT;
1083 void
1084 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1085 /* --------------------------------------------------------------------------
1086      External: Position the window
1087    -------------------------------------------------------------------------- */
1089   NSScreen *screen;
1090   NSView *view = FRAME_NS_VIEW (f);
1092   NSTRACE (x_set_offset);
1094   BLOCK_INPUT;
1096   f->left_pos = xoff;
1097   f->top_pos = yoff;
1098 #ifdef NS_IMPL_GNUSTEP
1099   if (xoff < 100)
1100     f->left_pos = 100;  /* don't overlap menu */
1101 #endif
1102   if (view != nil && (screen = [[view window] screen]))
1103     [[view window] setFrameTopLeftPoint:
1104         NSMakePoint (SCREENMAXBOUND (f->left_pos),
1105                      SCREENMAXBOUND ([screen frame].size.height
1106                                      - NS_TOP_POS (f)))];
1107   UNBLOCK_INPUT;
1111 void
1112 x_set_window_size (struct frame *f, int change_grav, int cols, int rows)
1113 /* --------------------------------------------------------------------------
1114      Adjust window pixel size based on given character grid size
1115      Impl is a bit more complex than other terms, need to do some
1116      internal clipping and also pay attention to screen constraints.
1117    -------------------------------------------------------------------------- */
1119   EmacsView *view = FRAME_NS_VIEW (f);
1120   EmacsToolbar *toolbar = [view toolbar];
1121   NSWindow *window = [view window];
1122   NSScreen *screen = [window screen];
1123   NSRect wr = [window frame];
1124   int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1125   int pixelwidth, pixelheight;
1126   static int oldRows, oldCols, oldFontWidth, oldFontHeight;
1127   static int oldTB;
1128   static struct frame *oldF;
1130   NSTRACE (x_set_window_size);
1132   if (view == nil ||
1133       (f == oldF
1134        && rows == oldRows && cols == oldCols
1135        && oldFontWidth == FRAME_COLUMN_WIDTH (f)
1136        && oldFontHeight == FRAME_LINE_HEIGHT (f)
1137        && oldTB == tb))
1138     return;
1140 /*fprintf (stderr, "\tsetWindowSize: %d x %d, font size %d x %d\n", cols, rows, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f)); */
1142   BLOCK_INPUT;
1144   check_frame_size (f, &rows, &cols);
1145   oldF = f;
1146   oldRows = rows;
1147   oldCols = cols;
1148   oldFontWidth = FRAME_COLUMN_WIDTH (f);
1149   oldFontHeight = FRAME_LINE_HEIGHT (f);
1150   oldTB = tb;
1152   f->scroll_bar_actual_width = NS_SCROLL_BAR_WIDTH (f);
1153   compute_fringe_widths (f, 0);
1155   pixelwidth =  FRAME_TEXT_COLS_TO_PIXEL_WIDTH   (f, cols);
1156   pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
1158   /* If we have a change in toolbar display, calculate height */
1159   if (tb)
1160     /* XXX: GNUstep has not yet implemented the first method below, added
1161            in Panther, however the second is incorrect under Cocoa. */
1162 #ifdef NS_IMPL_GNUSTEP
1163     FRAME_NS_TOOLBAR_HEIGHT (f)
1164       = NSHeight ([NSWindow frameRectForContentRect: NSMakeRect (0, 0, 0, 0)
1165                             styleMask: [window styleMask]])
1166         - FRAME_NS_TITLEBAR_HEIGHT (f);
1167 #else
1168     FRAME_NS_TOOLBAR_HEIGHT (f) = 32;
1169       /* actually get wrong result here if toolbar not yet displayed
1170          NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1171          - FRAME_NS_TITLEBAR_HEIGHT (f); */
1172 #endif
1173   else
1174     FRAME_NS_TOOLBAR_HEIGHT (f) = 0;
1176   wr.size.width = pixelwidth + f->border_width;
1177   wr.size.height = pixelheight + FRAME_NS_TITLEBAR_HEIGHT (f) 
1178                   + FRAME_NS_TOOLBAR_HEIGHT (f);
1180   /* constrain to screen if we can */
1181   if (screen)
1182     {
1183       NSSize sz = [screen visibleFrame].size;
1184       NSSize ez = { wr.size.width - sz.width, wr.size.height - sz.height };
1185       if (ez.width > 0)
1186         {
1187           int cr = ez.width / FRAME_COLUMN_WIDTH (f) + 1;
1188           cols -= cr;
1189           oldCols = cols;
1190           wr.size.width -= cr * FRAME_COLUMN_WIDTH (f);
1191           pixelwidth -= cr * FRAME_COLUMN_WIDTH (f);
1192         }
1193       if (ez.height > 0)
1194         {
1195           int rr = ez.height / FRAME_LINE_HEIGHT (f) + 1;
1196           rows -= rr;
1197           oldRows = rows;
1198           wr.size.height -= rr * FRAME_LINE_HEIGHT (f);
1199           pixelheight -= rr * FRAME_LINE_HEIGHT (f);
1200         }
1201       wr.origin.x = f->left_pos;
1202       wr.origin.y = [screen frame].size.height - NS_TOP_POS (f)
1203         - wr.size.height;
1204     }
1206   [view setRows: rows andColumns: cols];
1207   [window setFrame: wr display: YES];
1209 /*fprintf (stderr, "\tx_set_window_size %d, %d\t%d, %d\n", cols, rows, pixelwidth, pixelheight); */
1211   /* This is a trick to compensate for Emacs' managing the scrollbar area
1212      as a fixed number of standard character columns.  Instead of leaving
1213      blank space for the extra, we chopped it off above.  Now for
1214      left-hand scrollbars, we shift all rendering to the left by the
1215      difference between the real width and Emacs' imagined one.  For
1216      right-hand bars, don't worry about it since the extra is never used.
1217      (Obviously doesn't work for vertically split windows tho..) */
1218   NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1219     ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1220                   - NS_SCROLL_BAR_WIDTH (f), 0)
1221     : NSMakePoint (0, 0);
1222   [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1223   [view setBoundsOrigin: origin];
1225   change_frame_size (f, rows, cols, 0, 1, 0); /* pretend, delay, safe */
1226   FRAME_PIXEL_WIDTH (f) = pixelwidth;
1227   FRAME_PIXEL_HEIGHT (f) = pixelheight;
1228 /*  SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */
1230   mark_window_cursors_off (XWINDOW (f->root_window));
1231   cancel_mouse_face (f);
1233   UNBLOCK_INPUT;
1238 /* ==========================================================================
1240     Color management
1242    ========================================================================== */
1245 NSColor *
1246 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1248   struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1249   return color_table->colors[idx];
1253 unsigned long
1254 ns_index_color (NSColor *color, struct frame *f)
1256   struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1257   int idx;
1258   NSNumber *index;
1260   if (!color_table->colors)
1261     {
1262       color_table->size = NS_COLOR_CAPACITY;
1263       color_table->avail = 1; /* skip idx=0 as marker */
1264       color_table->colors
1265         = (NSColor **)xmalloc (color_table->size * sizeof (NSColor *));
1266       color_table->empty_indices = [[NSMutableSet alloc] init];
1267     }
1269   /* do we already have this color ? */
1270   {
1271     int i;
1272     for (i = 1; i < color_table->avail; i++)
1273       {
1274         if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1275           {
1276             [color_table->colors[i] retain];
1277             return i;
1278           }
1279       }
1280   }
1282   if ([color_table->empty_indices count] > 0)
1283     {
1284       index = [color_table->empty_indices anyObject];
1285       [color_table->empty_indices removeObject: index];
1286       idx = [index unsignedIntValue];
1287     }
1288   else
1289     {
1290       if (color_table->avail == color_table->size)
1291         {
1292           color_table->size += NS_COLOR_CAPACITY;
1293           color_table->colors
1294             = (NSColor **)xrealloc (color_table->colors,
1295                                     color_table->size * sizeof (NSColor *));
1296         }
1297       idx = color_table->avail++;
1298     }
1300   color_table->colors[idx] = color;
1301   [color retain];
1302 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1303   return idx;
1307 void
1308 ns_free_indexed_color (unsigned long idx, struct frame *f)
1310   struct ns_color_table *color_table;
1311   NSColor *color;
1312   NSNumber *index;
1314   if (!f)
1315     return;
1317   color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1319   if (idx <= 0 || idx >= color_table->size) {
1320     message1("ns_free_indexed_color: Color index out of range.\n");
1321     return;
1322   }
1324   index = [NSNumber numberWithUnsignedInt: idx];
1325   if ([color_table->empty_indices containsObject: index]) {
1326     message1("ns_free_indexed_color: attempt to free already freed color.\n");
1327     return;
1328   }
1330   color = color_table->colors[idx];
1331   [color release];
1332   color_table->colors[idx] = nil;
1333   [color_table->empty_indices addObject: [NSNumber numberWithUnsignedInt: idx]];
1334 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1338 static int
1339 ns_get_color (const char *name, NSColor **col)
1340 /* --------------------------------------------------------------------------
1341      Parse a color name
1342 /* --------------------------------------------------------------------------
1343 /* On *Step, we recognize several color formats, in addition to a catalog
1344    of colors found in the file Emacs.clr. Color formats include:
1345    - #rrggbb or RGBrrggbb where rr, gg, bb specify red, green and blue in hex
1346    - ARGBaarrggbb is similar, with aa being the alpha channel (FF = opaque)
1347    - HSVhhssvv and AHSVaahhssvv (or HSB/AHSB) are similar for hue, saturation,
1348      value;
1349    - CMYKccmmyykk is similar for cyan, magenta, yellow, black. */
1351   NSColor * new = nil;
1352   const char *hex = NULL;
1353   enum { rgb, argb, hsv, ahsv, cmyk, gray } color_space;
1354   NSString *nsname = [NSString stringWithUTF8String: name];
1356 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1357   BLOCK_INPUT;
1359   if ([nsname isEqualToString: @"ns_selection_color"])
1360     {
1361       nsname = ns_selection_color;
1362       name = [ns_selection_color UTF8String];
1363     }
1365   if (name[0] == '0' || name[0] == '1' || name[0] == '.')
1366     {
1367       /* RGB decimal */
1368       NSScanner *scanner = [NSScanner scannerWithString: nsname];
1369       float r, g, b;
1370       [scanner scanFloat: &r];
1371       [scanner scanFloat: &g];
1372       [scanner scanFloat: &b];
1373       *col = [NSColor colorWithCalibratedRed: r green: g blue: b alpha: 1.0];
1374       UNBLOCK_INPUT;
1375       return 0;
1376     }
1378   /* 23: FIXME: emacs seems to downcase everything before passing it here,
1379       which we can work around, except for GRAY, since gray##, where ## is
1380       decimal between 0 and 99, is also an X11 colorname. */
1381   if (name[0] == '#')             /* X11 format */
1382     {
1383       hex = name + 1;
1384       color_space = rgb;
1385     }
1386   else if (!memcmp (name, "RGB", 3) || !memcmp (name, "rgb", 3))
1387     {
1388       hex = name + 3;
1389       color_space = rgb;
1390     }
1391   else if (!memcmp (name, "ARGB", 4) || !memcmp (name, "argb", 4))
1392     {
1393       hex = name + 4;
1394       color_space = argb;
1395     }
1396   else if (!memcmp (name, "HSV", 3) || !memcmp (name, "hsv", 3) || 
1397            !memcmp (name, "HSB", 3) || !memcmp (name, "hsb", 3))
1398     {
1399       hex = name + 3;
1400       color_space = hsv;
1401     }
1402   else if (!memcmp (name, "AHSV", 4) || !memcmp (name, "ahsv", 4) ||
1403            !memcmp (name, "AHSB", 4) || !memcmp (name, "ahsb", 4))
1404     {
1405       hex = name + 4;
1406       color_space = ahsv;
1407     }
1408   else if (!memcmp (name, "CMYK", 4) || !memcmp (name, "cmyk", 4))
1409     {
1410       hex = name + 4;
1411       color_space = cmyk;
1412     }
1413   else if (!memcmp (name, "GRAY", 4) /*|| !memcmp (name, "gray", 4)*/)
1414     {
1415       hex = name + 4;
1416       color_space = gray;
1417     }
1419   /* Direct colors (hex values) */
1420   if (hex)
1421     {
1422       unsigned long color = 0;
1423       if (sscanf (hex, "%x", &color))
1424         {
1425           float f1, f2, f3, f4;
1426           /* Assume it's either 1 byte or 2 per channel... */
1427           if (strlen(hex) > 8) {
1428             f1 = ((color >> 48) & 0xffff) / 65535.0;
1429             f2 = ((color >> 32) & 0xffff) / 65535.0;
1430             f3 = ((color >> 16) & 0xffff) / 65535.0;
1431             f4 = ((color      ) & 0xffff) / 65535.0;
1432           } else {
1433             f1 = ((color >> 24) & 0xff) / 255.0;
1434             f2 = ((color >> 16) & 0xff) / 255.0;
1435             f3 = ((color >>  8) & 0xff) / 255.0;
1436             f4 = ((color      ) & 0xff) / 255.0;
1437           }
1439           switch (color_space)
1440             {
1441             case rgb:
1442               *col = [NSColor colorWithCalibratedRed: f2
1443                                                green: f3
1444                                                 blue: f4
1445                                                alpha: 1.0];
1446               break;
1447             case argb:
1448               *col = [NSColor colorWithCalibratedRed: f2
1449                                                green: f3
1450                                                 blue: f4
1451                                                alpha: f1];
1452               break;
1453             case hsv:
1454               *col = [NSColor colorWithCalibratedHue: f2
1455                                           saturation: f3
1456                                           brightness: f4
1457                                                alpha: 1.0];
1458               break;
1459             case ahsv:
1460               *col = [NSColor colorWithCalibratedHue: f2
1461                                           saturation: f3
1462                                           brightness: f4
1463                                                alpha: f1];
1464               break;
1465             case gray:
1466               *col = [NSColor colorWithCalibratedWhite: f3 alpha: f4];
1467               break;
1468             case cmyk:
1469               *col = [NSColor colorWithDeviceCyan: f1
1470                                           magenta: f2
1471                                            yellow: f3
1472                                             black: f4
1473                                             alpha: 1.0];
1474               break;
1475             }
1476           *col = [*col colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1477           UNBLOCK_INPUT;
1478           return 0;
1479         }
1480     }
1482   /* Otherwise, color is expected to be from a list */
1483   {
1484     NSEnumerator *lenum, *cenum;
1485     NSString *name;
1486     NSColorList *clist;
1488 #ifdef NS_IMPL_GNUSTEP
1489     /* XXX: who is wrong, the requestor or the implementation? */
1490     if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1491         == NSOrderedSame)
1492       nsname = @"highlightColor";
1493 #endif
1495     lenum = [[NSColorList availableColorLists] objectEnumerator];
1496     while ( (clist = [lenum nextObject]) && new == nil)
1497       {
1498         cenum = [[clist allKeys] objectEnumerator];
1499         while ( (name = [cenum nextObject]) && new == nil )
1500           {
1501             if ([name compare: nsname
1502                       options: NSCaseInsensitiveSearch] == NSOrderedSame )
1503               new = [clist colorWithKey: name];
1504           }
1505       }
1506   }
1508   if ( new )
1509     *col = [new colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1510 /*     else
1511        NSLog (@"Failed to find color '%@'", nsname); */
1512   UNBLOCK_INPUT;
1513   return new ? 0 : 1;
1517 static NSColor *
1518 ns_get_color_default (const char *name, NSColor *dflt)
1519 /* --------------------------------------------------------------------------
1520      Parse a color or use a default value
1521    -------------------------------------------------------------------------- */
1523   NSColor * col;
1525   if (ns_get_color (name, &col))
1526     return dflt;
1527   else
1528     return col;
1533 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1534 /* --------------------------------------------------------------------------
1535      Convert a Lisp string object to a NS color
1536    -------------------------------------------------------------------------- */
1538   NSTRACE (ns_lisp_to_color);
1539   if (STRINGP (color))
1540     return ns_get_color (SDATA (color), col);
1541   else if (SYMBOLP (color))
1542     return ns_get_color (SDATA (SYMBOL_NAME (color)), col);
1543   return 1;
1547 Lisp_Object
1548 ns_color_to_lisp (NSColor *col)
1549 /* --------------------------------------------------------------------------
1550      Convert a color to a lisp string with the RGB equivalent
1551    -------------------------------------------------------------------------- */
1553   float red, green, blue, alpha, gray;
1554   char buf[1024];
1555   const char *str;
1556   NSTRACE (ns_color_to_lisp);
1558   BLOCK_INPUT;
1559   if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1561       if ((str =[[col colorNameComponent] UTF8String]))
1562         {
1563           UNBLOCK_INPUT;
1564           return build_string ((char *)str);
1565         }
1567     [[col colorUsingColorSpaceName: NSCalibratedRGBColorSpace]
1568         getRed: &red green: &green blue: &blue alpha: &alpha];
1569   if (red ==green && red ==blue)
1570     {
1571       [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1572             getWhite: &gray alpha: &alpha];
1573       snprintf (buf, sizeof (buf), "GRAY%02.2lx%02.2lx",
1574                lrint (gray * 0xff), lrint (alpha * 0xff));
1575       UNBLOCK_INPUT;
1576       return build_string (buf);
1577     }
1579   snprintf (buf, sizeof (buf), "ARGB%02.2lx%02.2lx%02.2lx%02.2lx",
1580             lrint (alpha*0xff),
1581             lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1583   UNBLOCK_INPUT;
1584   return build_string (buf);
1589 ns_defined_color (struct frame *f, char *name, XColor *color_def, int alloc,
1590                   char makeIndex)
1591 /* --------------------------------------------------------------------------
1592    23:   Return 1 if named color found, and set color_def rgb accordingly.
1593          If makeIndex and alloc are nonzero put the color in the color_table,
1594          and set color_def pixel to the resulting index.
1595          If makeIndex is zero, set color_def pixel to ARGB.
1596          Return 0 if not found
1597    -------------------------------------------------------------------------- */
1599   NSColor *temp;
1600   float r, g, b, a;
1601   int notFound = ns_get_color (name, &temp);
1603   NSTRACE (ns_defined_color);
1605   if (notFound)
1606     return 0;
1608   if (makeIndex && alloc)
1609       color_def->pixel = ns_index_color(temp, f); /* [temp retain]; */
1611   [temp getRed: &r green: &g blue: &b alpha: &a];
1612   color_def->red   = r * 256;
1613   color_def->green = g * 256;
1614   color_def->blue  = b * 256;
1616   if (!makeIndex)
1617     color_def->pixel
1618       = ARGB_TO_ULONG((int)(a*256),
1619                       color_def->red, color_def->green, color_def->blue);
1621   return 1;
1625 unsigned long
1626 ns_get_rgb_color (struct frame *f, float r, float g, float b, float a)
1627 /* --------------------------------------------------------------------------
1628     return an autoreleased RGB color
1629    -------------------------------------------------------------------------- */
1631 /*static int c = 1; fprintf (stderr, "color request %d\n", c++); */
1632   if (r < 0.0) r = 0.0;
1633   else if (r > 1.0) r = 1.0;
1634   if (g < 0.0) g = 0.0;
1635   else if (g > 1.0) g = 1.0;
1636   if (b < 0.0) b = 0.0;
1637   else if (b > 1.0) b = 1.0;
1638   if (a < 0.0) a = 0.0;
1639   else if (a > 1.0) a = 1.0;
1640   return (unsigned long) ns_index_color(
1641     [NSColor colorWithCalibratedRed: r green: g blue: b alpha: a], f);
1645 void
1646 x_set_frame_alpha (struct frame *f)
1647 /* --------------------------------------------------------------------------
1648      change the entire-frame transparency
1649    -------------------------------------------------------------------------- */
1651   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1652   EmacsView *view = FRAME_NS_VIEW (f);
1653   double alpha = 1.0;
1654   double alpha_min = 1.0;
1656   if (dpyinfo->x_highlight_frame == f)
1657     alpha = f->alpha[0];
1658   else
1659     alpha = f->alpha[1];
1661   if (FLOATP (Vframe_alpha_lower_limit))
1662     alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1663   else if (INTEGERP (Vframe_alpha_lower_limit))
1664     alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1666   if (alpha < 0.0)
1667     return;
1668   else if (1.0 < alpha)
1669     alpha = 1.0;
1670   else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1671     alpha = alpha_min;
1673 #ifdef NS_IMPL_COCOA
1674   [[view window] setAlphaValue: alpha];
1675 #endif
1679 /* ==========================================================================
1681     Mouse handling
1683    ========================================================================== */
1686 void
1687 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1688 /* --------------------------------------------------------------------------
1689      Programmatically reposition mouse pointer in pixel coordinates
1690    -------------------------------------------------------------------------- */
1692   NSTRACE (x_set_mouse_pixel_position);
1693   ns_raise_frame (f);
1694 #if 0
1695   /* FIXME: this does not work, and what about GNUstep? */
1696 #ifdef NS_IMPL_COCOA
1697   [FRAME_NS_VIEW (f) lockFocus];
1698   PSsetmouse ((float)pix_x, (float)pix_y);
1699   [FRAME_NS_VIEW (f) unlockFocus];
1700 #endif
1701 #endif
1705 void
1706 x_set_mouse_position (struct frame *f, int h, int v)
1707 /* --------------------------------------------------------------------------
1708      Programmatically reposition mouse pointer in character coordinates
1709    -------------------------------------------------------------------------- */
1711   int pix_x, pix_y;
1713   pix_x = FRAME_COL_TO_PIXEL_X (f, h) + FRAME_COLUMN_WIDTH (f) / 2;
1714   pix_y = FRAME_LINE_TO_PIXEL_Y (f, v) + FRAME_LINE_HEIGHT (f) / 2;
1716   if (pix_x < 0) pix_x = 0;
1717   if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
1719   if (pix_y < 0) pix_y = 0;
1720   if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
1722   x_set_mouse_pixel_position (f, pix_x, pix_y);
1726 static int
1727 note_mouse_movement (struct frame *frame, float x, float y)
1728 /*   ------------------------------------------------------------------------
1729      Called by EmacsView on mouseMovement events.  Passes on
1730      to emacs mainstream code if we moved off of a rect of interest
1731      known as last_mouse_glyph.
1732      ------------------------------------------------------------------------ */
1734 //  NSTRACE (note_mouse_movement);
1736   XSETFRAME (last_mouse_motion_frame, frame);
1738   /* Note, this doesn't get called for enter/leave, since we don't have a
1739      position.  Those are taken care of in the corresponding NSView methods. */
1741   /* has movement gone beyond last rect we were tracking? */
1742   if (x < last_mouse_glyph.origin.x ||
1743       x >= (last_mouse_glyph.origin.x + last_mouse_glyph.size.width) ||
1744       y < last_mouse_glyph.origin.y ||
1745       y >= (last_mouse_glyph.origin.y + last_mouse_glyph.size.height))
1746     {
1747       frame->mouse_moved = 1;
1748       note_mouse_highlight (frame, x, y);
1749       remember_mouse_glyph (frame, x, y, &last_mouse_glyph);
1750       return 1;
1751     }
1753   return 0;
1757 static void
1758 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1759                    enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1760                    unsigned long *time)
1761 /* --------------------------------------------------------------------------
1762     External (hook): inform emacs about mouse position and hit parts.
1763     If a scrollbar is being dragged, set bar_window, part, x, y, time.
1764     x & y should be position in the scrollbar (the whole bar, not the handle)
1765     and length of scrollbar respectively
1766    -------------------------------------------------------------------------- */
1768   id view;
1769   NSPoint position;
1770   int xchar, ychar;
1771   Lisp_Object frame, tail;
1772   struct frame *f;
1773   struct ns_display_info *dpyinfo;
1775   NSTRACE (ns_mouse_position);
1777   if (*fp == NULL)
1778     {
1779       fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1780       return;
1781     }
1783   dpyinfo = FRAME_NS_DISPLAY_INFO (*fp);
1785   BLOCK_INPUT;
1787   if (last_mouse_scroll_bar != nil && insist == 0)
1788     {
1789       /* TODO: we do not use this path at the moment because drag events will
1790            go directly to the EmacsScroller.  Leaving code in for now. */
1791       [last_mouse_scroll_bar getMouseMotionPart: (int *)part window: bar_window
1792                                               x: x y: y];
1793       if (time) *time = last_mouse_movement_time;
1794       last_mouse_scroll_bar = nil;
1795     }
1796   else
1797     {
1798       /* Clear the mouse-moved flag for every frame on this display.  */
1799       FOR_EACH_FRAME (tail, frame)
1800         if (FRAME_NS_P (XFRAME (frame))
1801             && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1802           XFRAME (frame)->mouse_moved = 0;
1804       last_mouse_scroll_bar = nil;
1805       if (last_mouse_frame && FRAME_LIVE_P (last_mouse_frame))
1806         f = last_mouse_frame;
1807       else
1808         f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame
1809                                     : SELECTED_FRAME ();
1811       if (f && f->output_data.ns)  /* TODO: 2nd check no longer needed? */
1812         {
1813           view = FRAME_NS_VIEW (*fp);
1815           position = [[view window] mouseLocationOutsideOfEventStream];
1816           position = [view convertPoint: position fromView: nil];
1817           remember_mouse_glyph (f, position.x, position.y, &last_mouse_glyph);
1818 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1820           if (bar_window) *bar_window = Qnil;
1821           if (part) *part = 0; /*scroll_bar_handle; */
1823           if (x) XSETINT (*x, lrint (position.x));
1824           if (y) XSETINT (*y, lrint (position.y));
1825           if (time) *time = last_mouse_movement_time;
1826           *fp = f;
1827         }
1828     }
1830   UNBLOCK_INPUT;
1834 static void
1835 ns_frame_up_to_date (struct frame *f)
1836 /* --------------------------------------------------------------------------
1837     External (hook): Fix up mouse highlighting right after a full update.
1838     Some highlighting was deferred if GC was happening during
1839     note_mouse_highlight (), while other highlighting was deferred for update.
1840    -------------------------------------------------------------------------- */
1842   NSTRACE (ns_frame_up_to_date);
1844   if (FRAME_NS_P (f))
1845     {
1846       struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1847       if ((dpyinfo->mouse_face_deferred_gc||f ==dpyinfo->mouse_face_mouse_frame)
1848       /*&& dpyinfo->mouse_face_mouse_frame*/)
1849         {
1850           BLOCK_INPUT;
1851           if (dpyinfo->mouse_face_mouse_frame)
1852             note_mouse_highlight (dpyinfo->mouse_face_mouse_frame,
1853                                   dpyinfo->mouse_face_mouse_x,
1854                                   dpyinfo->mouse_face_mouse_y);
1855           dpyinfo->mouse_face_deferred_gc = 0;
1856           UNBLOCK_INPUT;
1857         }
1858     }
1862 void
1863 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1864 /* --------------------------------------------------------------------------
1865     External (RIF): set frame mouse pointer type.
1866    -------------------------------------------------------------------------- */
1868   NSTRACE (ns_define_frame_cursor);
1869   if (FRAME_POINTER_TYPE (f) != cursor)
1870     {
1871       EmacsView *view = FRAME_NS_VIEW (f);
1872       FRAME_POINTER_TYPE (f) = cursor;
1873       [[view window] invalidateCursorRectsForView: view];
1874     }
1879 /* ==========================================================================
1881     Keyboard handling
1883    ========================================================================== */
1886 static unsigned
1887 ns_convert_key (unsigned code)
1888 /* --------------------------------------------------------------------------
1889     Internal call used by NSView-keyDown.
1890    -------------------------------------------------------------------------- */
1892   const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym)
1893                                 / sizeof (convert_ns_to_X_keysym[0]));
1894   unsigned keysym;
1895   /* An array would be faster, but less easy to read. */
1896   for (keysym = 0; keysym < last_keysym; keysym += 2)
1897     if (code == convert_ns_to_X_keysym[keysym])
1898       return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
1899   return 0;
1900 /* if decide to use keyCode and Carbon table, use this line:
1901      return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
1905 char *
1906 x_get_keysym_name (int keysym)
1907 /* --------------------------------------------------------------------------
1908     Called by keyboard.c.  Not sure if the return val is important, except
1909     that it be unique.
1910    -------------------------------------------------------------------------- */
1912   static char value[16];
1913   NSTRACE (x_get_keysym_name);
1914   sprintf (value, "%d", keysym);
1915   return value;
1920 /* ==========================================================================
1922     Block drawing operations
1924    ========================================================================== */
1927 static void
1928 ns_redraw_scroll_bars (struct frame *f)
1930   int i;
1931   id view;
1932   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
1933   NSTRACE (ns_judge_scroll_bars);
1934   for (i =[subviews count]-1; i >= 0; i--)
1935     {
1936       view = [subviews objectAtIndex: i];
1937       if (![view isKindOfClass: [EmacsScroller class]]) continue;
1938       [view display];
1939     }
1943 void
1944 ns_clear_frame (struct frame *f)
1945 /* --------------------------------------------------------------------------
1946       External (hook): Erase the entire frame
1947    -------------------------------------------------------------------------- */
1949   NSView *view = FRAME_NS_VIEW (f);
1950   NSRect r;
1952   NSTRACE (ns_clear_frame);
1953   if (ns_in_resize)
1954     return;
1956  /* comes on initial frame because we have
1957     after-make-frame-functions = select-frame */
1958  if (!FRAME_DEFAULT_FACE (f))
1959    return;
1961   mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
1963   output_cursor.hpos = output_cursor.vpos = 0;
1964   output_cursor.x = -1;
1966   r = [view bounds];
1968   BLOCK_INPUT;
1969   ns_focus (f, &r, 1);
1970   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
1971   NSRectFill (r);
1972   ns_unfocus (f);
1974 #ifdef NS_IMPL_COCOA
1975   [[view window] display];  /* redraw resize handle */
1976 #endif
1978   /* as of 2006/11 or so this is now needed */
1979   ns_redraw_scroll_bars (f);
1980   UNBLOCK_INPUT;
1984 void
1985 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
1986 /* --------------------------------------------------------------------------
1987    23: External (RIF):  Clear section of frame
1988    -------------------------------------------------------------------------- */
1990   NSRect r = NSMakeRect (x, y, width, height);
1991   NSView *view = FRAME_NS_VIEW (f);
1992   struct face *face = FRAME_DEFAULT_FACE (f);
1994   if (!view || !face)
1995     return;
1997   NSTRACE (ns_clear_frame_area);
1999   r = NSIntersectionRect (r, [view frame]);
2000   ns_focus (f, &r, 1);
2001   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2003 #ifdef NS_IMPL_COCOA
2004   {
2005     /* clip out the resize handle */
2006     NSWindow *window = [FRAME_NS_VIEW (f) window];
2007     NSRect ir
2008       = [view convertRect: ns_resize_handle_rect (window) fromView: nil];
2010     ir = NSIntersectionRect (r, ir);
2011     if (NSIsEmptyRect (ir))
2012       {
2013 #endif
2015   NSRectFill (r);
2017 #ifdef NS_IMPL_COCOA
2018       }
2019     else
2020       {
2021         NSRect r1 = r, r2 = r; /* upper and lower non-intersecting */
2022         r1.size.height -= ir.size.height;
2023         r2.origin.y += r1.size.height;
2024         r2.size.width -= ir.size.width;
2025         r2.size.height = ir.size.height;
2026         NSRectFill (r1);
2027         NSRectFill (r2);
2028       }
2029   }
2030 #endif
2032   ns_unfocus (f);
2033   return;
2037 static void
2038 ns_scroll_run (struct window *w, struct run *run)
2039 /* --------------------------------------------------------------------------
2040    23: External (RIF):  Insert or delete n lines at line vpos
2041    -------------------------------------------------------------------------- */
2043   struct frame *f = XFRAME (w->frame);
2044   int x, y, width, height, from_y, to_y, bottom_y;
2046   NSTRACE (ns_scroll_run);
2048   /* begin copy from other terms */
2049   /* Get frame-relative bounding box of the text display area of W,
2050      without mode lines.  Include in this box the left and right
2051      fringe of W.  */
2052   window_box (w, -1, &x, &y, &width, &height);
2054   from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2055   to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2056   bottom_y = y + height;
2058   if (to_y < from_y)
2059     {
2060       /* Scrolling up.  Make sure we don't copy part of the mode
2061          line at the bottom.  */
2062       if (from_y + run->height > bottom_y)
2063         height = bottom_y - from_y;
2064       else
2065         height = run->height;
2066     }
2067   else
2068     {
2069       /* Scolling down.  Make sure we don't copy over the mode line.
2070          at the bottom.  */
2071       if (to_y + run->height > bottom_y)
2072         height = bottom_y - to_y;
2073       else
2074         height = run->height;
2075     }
2076   /* end copy from other terms */
2078   if (height == 0)
2079       return;
2081   BLOCK_INPUT;
2083   updated_window = w;
2084   x_clear_cursor (w);
2086   {
2087     NSRect srcRect = NSMakeRect (x, from_y, width, height);
2088     NSRect dstRect = NSMakeRect (x, to_y, width, height);
2089     NSPoint dstOrigin = NSMakePoint (x, to_y);
2091     ns_focus (f, &dstRect, 1);
2092     NSCopyBits (0, srcRect , dstOrigin);
2093     ns_unfocus (f);
2094   }
2096   UNBLOCK_INPUT;
2100 static void
2101 ns_after_update_window_line (struct glyph_row *desired_row)
2102 /* --------------------------------------------------------------------------
2103    23: External (RIF): preparatory to fringe update after text was updated
2104    -------------------------------------------------------------------------- */
2106   struct window *w = updated_window;
2107   struct frame *f;
2108   int width, height;
2110   NSTRACE (ns_after_update_window_line);
2112   /* begin copy from other terms */
2113   xassert (w);
2115   if (!desired_row->mode_line_p && !w->pseudo_window_p)
2116     desired_row->redraw_fringe_bitmaps_p = 1;
2118   /* When a window has disappeared, make sure that no rest of
2119      full-width rows stays visible in the internal border.
2120      Under NS this is drawn inside the fringes. */
2121   if (windows_or_buffers_changed
2122       && (f = XFRAME (w->frame),
2123           width = FRAME_INTERNAL_BORDER_WIDTH (f),
2124           width != 0)
2125       && (height = desired_row->visible_height,
2126           height > 0))
2127     {
2128       int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2130       /* Internal border is drawn below the tool bar.  */
2131       if (WINDOWP (f->tool_bar_window)
2132           && w == XWINDOW (f->tool_bar_window))
2133         y -= width;
2134       /* end copy from other terms */
2136       BLOCK_INPUT;
2137       if (!desired_row->full_width_p)
2138         {
2139           int x1 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2140             + WINDOW_LEFT_FRINGE_WIDTH (w);
2141           int x2 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2142             + FRAME_PIXEL_WIDTH (f) - NS_SCROLL_BAR_WIDTH (f)
2143             - WINDOW_RIGHT_FRINGE_WIDTH (w)
2144             - FRAME_INTERNAL_BORDER_WIDTH (f);
2145           ns_clear_frame_area (f, x1, y, width, height);
2146           ns_clear_frame_area (f, x2, y, width, height);
2147         }
2148       UNBLOCK_INPUT;
2149     }
2153 static void
2154 ns_shift_glyphs_for_insert (struct frame *f,
2155                            int x, int y, int width, int height,
2156                            int shift_by)
2157 /* --------------------------------------------------------------------------
2158    23: External (RIF): copy an area horizontally, don't worry about clearing src
2159    -------------------------------------------------------------------------- */
2161   NSRect srcRect = NSMakeRect (x, y, width, height);
2162   NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2163   NSPoint dstOrigin = dstRect.origin;
2165   NSTRACE (ns_shift_glyphs_for_insert);
2167   ns_focus (f, &dstRect, 1);
2168   NSCopyBits (0, srcRect, dstOrigin);
2169   ns_unfocus (f);
2174 /* ==========================================================================
2176     Character encoding and metrics
2178    ========================================================================== */
2181 static inline void
2182 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2183 /* --------------------------------------------------------------------------
2184    23:  External (RIF); compute left/right overhang of whole string and set in s
2185    -------------------------------------------------------------------------- */
2187   struct face *face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2188   struct font *font = s->font; /*face->font; */
2190   if (s->char2b)
2191     {
2192       struct font_metrics metrics;
2193       unsigned int codes[2];
2194       codes[0] = *(s->char2b);
2195       codes[1] = *(s->char2b + s->nchars - 1);
2197       font->driver->text_extents (font, codes, 2, &metrics);
2198       s->left_overhang = -metrics.lbearing;
2199       s->right_overhang
2200         = metrics.rbearing > metrics.width
2201         ? metrics.rbearing - metrics.width : 0;
2202     }
2203   else
2204     {
2205       s->left_overhang = 0;
2206       s->right_overhang = ((struct nsfont_info *)font)->ital ?
2207         FONT_HEIGHT (font) * 0.2 : 0;
2208     }
2213 /* ==========================================================================
2215     Fringe and cursor drawing
2217    ========================================================================== */
2220 extern int max_used_fringe_bitmap;
2221 static void
2222 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2223                       struct draw_fringe_bitmap_params *p)
2224 /* --------------------------------------------------------------------------
2225    23: External (RIF); fringe-related
2226    -------------------------------------------------------------------------- */
2228   struct frame *f = XFRAME (WINDOW_FRAME (w));
2229   struct face *face = p->face;
2230   int rowY;
2231   static EmacsImage **bimgs = NULL;
2232   static int nBimgs = 0;
2233   /* NS-specific: move internal border inside fringe */
2234   int x = p->bx < 0 ? p->x : p->bx;
2235   int wd = p->bx < 0 ? p->wd : p->nx;
2236   BOOL fringeOnVeryLeft
2237     = x - WINDOW_LEFT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w)
2238       - FRAME_INTERNAL_BORDER_WIDTH (f) < 10;
2239   BOOL fringeOnVeryRight
2240     = FRAME_PIXEL_WIDTH (f) - x - wd - FRAME_INTERNAL_BORDER_WIDTH (f)
2241       - WINDOW_RIGHT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w) < 10;
2242   int xAdjust = FRAME_INTERNAL_BORDER_WIDTH (f) *
2243     (fringeOnVeryLeft ? -1 : (fringeOnVeryRight ? 1 : 0));
2245   /* grow bimgs if needed */
2246   if (nBimgs < max_used_fringe_bitmap)
2247     {
2248       EmacsImage **newBimgs
2249         = xmalloc (max_used_fringe_bitmap * sizeof (EmacsImage *));
2250       bzero (newBimgs, max_used_fringe_bitmap * sizeof (EmacsImage *));
2252       if (nBimgs)
2253         {
2254           bcopy (bimgs, newBimgs, nBimgs * sizeof (EmacsImage *));
2255           xfree (bimgs);
2256         }
2258       bimgs = newBimgs;
2259       nBimgs = max_used_fringe_bitmap;
2260     }
2262   /* Must clip because of partially visible lines.  */
2263   rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
2264   if (p->y < rowY)
2265     {
2266       /* Adjust position of "bottom aligned" bitmap on partially
2267          visible last row.  */
2268       int oldY = row->y;
2269       int oldVH = row->visible_height;
2270       row->visible_height = p->h;
2271       row->y -= rowY - p->y;
2272       ns_clip_to_row (w, row, -1, NO);
2273       row->y = oldY;
2274       row->visible_height = oldVH;
2275     }
2276   else
2277     ns_clip_to_row (w, row, -1, YES);
2279   if (p->bx >= 0 && !p->overlay_p)
2280     {
2281       int yAdjust = rowY - FRAME_INTERNAL_BORDER_WIDTH (f) < 5 ?
2282         -FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2283       int yIncr = FRAME_PIXEL_HEIGHT (f) - (p->by+yAdjust + p->ny) < 5 ?
2284         FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2285       if (yAdjust)
2286         yIncr += FRAME_INTERNAL_BORDER_WIDTH (f);
2287       NSRect r = NSMakeRect (p->bx+xAdjust, p->by+yAdjust, p->nx, p->ny+yIncr);
2288       NSRectClip (r);
2289       [ns_lookup_indexed_color(face->background, f) set];
2290       NSRectFill (r);
2291     }
2293   if (p->which)
2294     {
2295       NSRect r = NSMakeRect (p->x+xAdjust, p->y, p->wd, p->h);
2296       NSPoint pt = r.origin;
2297       EmacsImage *img = bimgs[p->which - 1];
2299       if (!img)
2300         {
2301           unsigned short *bits = p->bits + p->dh;
2302           int len = 8 * p->h/8;
2303           int i;
2304           unsigned char *cbits = xmalloc (len);
2306           for (i =0; i<len; i++)
2307             cbits[i] = ~(bits[i] & 0xff);
2308           img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2309                                            flip: NO];
2310           bimgs[p->which - 1] = img;
2311           xfree (cbits);
2312         }
2314       NSRectClip (r);
2315       /* Since we composite the bitmap instead of just blitting it, we need
2316          to erase the whole background. */
2317       [ns_lookup_indexed_color(face->background, f) set];
2318       NSRectFill (r);
2319       pt.y += p->h;
2320       [img setXBMColor: ns_lookup_indexed_color(face->foreground, f)];
2321       [img compositeToPoint: pt operation: NSCompositeSourceOver];
2322     }
2323   ns_unfocus (f);
2327 void
2328 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2329                        int x, int y, int cursor_type, int cursor_width,
2330                        int on_p, int active_p)
2331 /* --------------------------------------------------------------------------
2332      External call (RIF): draw cursor
2333      (modeled after x_draw_window_cursor
2334      FIXME: cursor_width is effectively bogus -- it sometimes gets set
2335      in xdisp.c set_frame_cursor_types, sometimes left uninitialized;
2336      DON'T USE IT (no other terms do)
2337    -------------------------------------------------------------------------- */
2339   NSRect r, s;
2340   int fx, fy, h;
2341   struct frame *f = WINDOW_XFRAME (w);
2342   struct glyph *phys_cursor_glyph;
2343   int overspill, cursorToDraw;
2345   NSTRACE (dumpcursor);
2346 //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);
2348   if (!on_p)
2349         return;
2351   w->phys_cursor_type = cursor_type;
2352   w->phys_cursor_on_p = on_p;
2354   if (cursor_type == NO_CURSOR)
2355     {
2356       w->phys_cursor_width = 0;
2357       return;
2358     }
2360   if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2361     {
2362       if (glyph_row->exact_window_width_line_p
2363           && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2364         {
2365           glyph_row->cursor_in_fringe_p = 1;
2366           draw_fringe_bitmap (w, glyph_row, 0);
2367         }
2368       return;
2369     }
2371   get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2373   r.origin.x = fx, r.origin.y = fy;
2374   r.size.height = h;
2375   r.size.width = w->phys_cursor_width;
2377   /* FIXME: if we overwrite the internal border area, it does not get erased;
2378      fix by truncating cursor, but better would be to erase properly */
2379   overspill = r.origin.x + r.size.width -
2380     WINDOW_TEXT_TO_FRAME_PIXEL_X (w, WINDOW_BOX_RIGHT_EDGE_X (w) 
2381       - WINDOW_TOTAL_FRINGE_WIDTH (w) - FRAME_INTERNAL_BORDER_WIDTH (f));
2382   if (overspill > 0)
2383     r.size.width -= overspill;
2385   /* TODO: only needed in rare cases with last-resort font in HELLO..
2386      should we do this more efficiently? */
2387   ns_clip_to_row (w, glyph_row, -1, NO); /* do ns_focus(f, &r, 1); if remove */
2388   [FRAME_CURSOR_COLOR (f) set];
2390 #ifdef NS_IMPL_COCOA
2391   /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2392            atomic.  Cleaner ways of doing this should be investigated.
2393            One way would be to set a global variable DRAWING_CURSOR
2394            when making the call to draw_phys..(), don't focus in that
2395            case, then move the ns_unfocus() here after that call. */
2396   NSDisableScreenUpdates ();
2397 #endif
2399   cursorToDraw = active_p ? cursor_type : HOLLOW_BOX_CURSOR;
2400   switch (cursorToDraw)
2401     {
2402     case NO_CURSOR:
2403       break;
2404     case FILLED_BOX_CURSOR:
2405       NSRectFill (r);
2406       break;
2407     case HOLLOW_BOX_CURSOR:
2408       NSRectFill (r);
2409       [FRAME_BACKGROUND_COLOR (f) set];
2410       NSRectFill (NSInsetRect (r, 1, 1));
2411       [FRAME_CURSOR_COLOR (f) set];
2412       break;
2413     case HBAR_CURSOR:
2414       s = r;
2415       s.origin.y += lrint (0.75 * s.size.height);
2416       s.size.width = min (FRAME_COLUMN_WIDTH (f), s.size.width);
2417       s.size.height = lrint (s.size.height * 0.25);
2418       NSRectFill (s);
2419       break;
2420     case BAR_CURSOR:
2421       s = r;
2422       s.size.width = min (cursor_width, 2); //FIXME(see above)
2423       NSRectFill (s);
2424       break;
2425     }
2426   ns_unfocus (f);
2428   /* draw the character under the cursor */
2429   if (cursorToDraw != NO_CURSOR)
2430     draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2432 #ifdef NS_IMPL_COCOA
2433   NSEnableScreenUpdates ();
2434 #endif
2439 static void
2440 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2441 /* --------------------------------------------------------------------------
2442      External (RIF): Draw a vertical line.
2443    -------------------------------------------------------------------------- */
2445   struct frame *f = XFRAME (WINDOW_FRAME (w));
2446   struct face *face;
2447   NSRect r = NSMakeRect (x, y0, 2, y1-y0);
2449   NSTRACE (ns_draw_vertical_window_border);
2451   face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2452   if (face)
2453       [ns_lookup_indexed_color(face->foreground, f) set];
2455   ns_focus (f, &r, 1);
2456   NSDrawGroove (r, r);
2457   ns_unfocus (f);
2461 void
2462 show_hourglass (struct atimer *timer)
2464   if (hourglass_shown_p)
2465     return;
2467   BLOCK_INPUT;
2469   /* TODO: add NSProgressIndicator to selected frame (see macfns.c) */
2471   hourglass_shown_p = 1;
2472   UNBLOCK_INPUT;
2476 void
2477 hide_hourglass ()
2479   if (!hourglass_shown_p)
2480     return;
2482   BLOCK_INPUT;
2484   /* TODO: remove NSProgressIndicator from all frames */
2486   hourglass_shown_p = 0;
2487   UNBLOCK_INPUT;
2492 /* ==========================================================================
2494     Glyph drawing operations
2496    ========================================================================== */
2499 static inline NSRect
2500 ns_fix_rect_ibw (NSRect r, int fibw, int frame_pixel_width)
2501 /* --------------------------------------------------------------------------
2502     Under NS we draw internal borders inside fringes, and want full-width
2503     rendering to go all the way to edge.  This function makes that correction.
2504    -------------------------------------------------------------------------- */
2506   if (r.origin.y <= fibw+1)
2507     {
2508       r.size.height += r.origin.y;
2509       r.origin.y = 0;
2510     }
2511   if (r.origin.x <= fibw+1)
2512     {
2513       r.size.width += r.origin.x;
2514       r.origin.x = 0;
2515     }
2516   if (frame_pixel_width - (r.origin.x+r.size.width) <= fibw+1)
2517     r.size.width += fibw;
2519   return r;
2523 static int
2524 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2525 /* --------------------------------------------------------------------------
2526     Wrapper utility to account for internal border width on full-width lines,
2527     and allow top full-width rows to hit the frame top.  nr should be pointer
2528     to two successive NSRects.  Number of rects actually used is returned.
2529    -------------------------------------------------------------------------- */
2531   int n = get_glyph_string_clip_rects (s, nr, 2);
2532   if (s->row->full_width_p)
2533     {
2534       *nr = ns_fix_rect_ibw (*nr, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2535                             FRAME_PIXEL_WIDTH (s->f));
2536       if (n == 2)
2537         *nr = ns_fix_rect_ibw (*(nr+1), FRAME_INTERNAL_BORDER_WIDTH (s->f),
2538                               FRAME_PIXEL_WIDTH (s->f));
2539     }
2540   return n;
2544 static void
2545 ns_draw_box (NSRect r, float thickness, NSColor *col, char left_p, char right_p)
2546 /* --------------------------------------------------------------------------
2547     Draw an unfilled rect inside r, optionally leaving left and/or right open.
2548     Note we can't just use an NSDrawRect command, because of the possibility
2549     of some sides not being drawn, and because the rect will be filled.
2550    -------------------------------------------------------------------------- */
2552   NSRect s = r;
2553   [col set];
2555   /* top, bottom */
2556   s.size.height = thickness;
2557   NSRectFill (s);
2558   s.origin.y += r.size.height - thickness;
2559   NSRectFill (s);
2561   s.size.height = r.size.height;
2562   s.origin.y = r.origin.y;
2564   /* left, right (optional) */
2565   s.size.width = thickness;
2566   if (left_p)
2567     NSRectFill (s);
2568   if (right_p)
2569     {
2570       s.origin.x += r.size.width - thickness;
2571       NSRectFill (s);
2572     }
2576 static void
2577 ns_draw_relief (NSRect r, int thickness, char raised_p,
2578                char top_p, char bottom_p, char left_p, char right_p,
2579                struct glyph_string *s)
2580 /* --------------------------------------------------------------------------
2581     Draw a relief rect inside r, optionally leaving some sides open.
2582     Note we can't just use an NSDrawBezel command, because of the possibility
2583     of some sides not being drawn, and because the rect will be filled.
2584    -------------------------------------------------------------------------- */
2586   static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2587   NSColor *newBaseCol = nil;
2588   NSRect sr = r;
2590   NSTRACE (ns_draw_relief);
2592   /* set up colors */
2594   if (s->face->use_box_color_for_shadows_p)
2595     {
2596       newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2597     }
2598 /*     else if (s->first_glyph->type == IMAGE_GLYPH
2599            && s->img->pixmap
2600            && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2601        {
2602          newBaseCol = IMAGE_BACKGROUND  (s->img, s->f, 0);
2603        } */
2604   else
2605     {
2606       newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2607     }
2609   if (newBaseCol == nil)
2610     newBaseCol = [NSColor grayColor];
2612   if (newBaseCol != baseCol)  /* TODO: better check */
2613     {
2614       [baseCol release];
2615       baseCol = [newBaseCol retain];
2616       [lightCol release];
2617       lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2618       [darkCol release];
2619       darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2620     }
2622   [(raised_p ? lightCol : darkCol) set];
2624   /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2626   /* top */
2627   sr.size.height = thickness;
2628   if (top_p) NSRectFill (sr);
2630   /* left */
2631   sr.size.height = r.size.height;
2632   sr.size.width = thickness;
2633   if (left_p) NSRectFill (sr);
2635   [(raised_p ? darkCol : lightCol) set];
2637   /* bottom */
2638   sr.size.width = r.size.width;
2639   sr.size.height = thickness;
2640   sr.origin.y += r.size.height - thickness;
2641   if (bottom_p) NSRectFill (sr);
2643   /* right */
2644   sr.size.height = r.size.height;
2645   sr.origin.y = r.origin.y;
2646   sr.size.width = thickness;
2647   sr.origin.x += r.size.width - thickness;
2648   if (right_p) NSRectFill (sr);
2652 static void
2653 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2654 /* --------------------------------------------------------------------------
2655       Function modeled after x_draw_glyph_string_box ().
2656       Sets up parameters for drawing.
2657    -------------------------------------------------------------------------- */
2659   int right_x, last_x;
2660   char left_p, right_p;
2661   struct glyph *last_glyph;
2662   NSRect r;
2663   int thickness;
2664   struct face *face;
2666   if (s->hl == DRAW_MOUSE_FACE)
2667     {
2668       face = FACE_FROM_ID
2669         (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2670       if (!face)
2671         face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2672     }
2673   else
2674     face = s->face;
2676   thickness = face->box_line_width;
2678   NSTRACE (ns_dumpglyphs_box_or_relief);
2680   last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2681             ? WINDOW_RIGHT_EDGE_X (s->w)
2682             : window_box_right (s->w, s->area));
2683   last_glyph = (s->cmp || s->img
2684                 ? s->first_glyph : s->first_glyph + s->nchars-1);
2686   right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2687               ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2689   left_p = (s->first_glyph->left_box_line_p
2690             || (s->hl == DRAW_MOUSE_FACE
2691                 && (s->prev == NULL || s->prev->hl != s->hl)));
2692   right_p = (last_glyph->right_box_line_p
2693              || (s->hl == DRAW_MOUSE_FACE
2694                  && (s->next == NULL || s->next->hl != s->hl)));
2696   r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2698   /* expand full-width row over internal borders */
2699   if (s->row->full_width_p)
2700     r = ns_fix_rect_ibw (r, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2701                         FRAME_PIXEL_WIDTH (s->f));
2703   if (s->face->box == FACE_SIMPLE_BOX)
2704     {
2705       xassert (s->face->box_color != nil);
2706       ns_draw_box (r, abs (thickness),
2707                    ns_lookup_indexed_color (face->box_color, s->f),
2708                   left_p, right_p);
2709     }
2710   else
2711     {
2712       ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2713                      1, 1, left_p, right_p, s);
2714     }
2718 static void
2719 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2720 /* --------------------------------------------------------------------------
2721       Modeled after x_draw_glyph_string_background, which draws BG in
2722       certain cases.  Others are left to the text rendering routine.
2723    -------------------------------------------------------------------------- */
2725   NSTRACE (ns_maybe_dumpglyphs_background);
2727   if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2728     {
2729       int box_line_width = max (s->face->box_line_width, 0);
2730       if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2731           || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2732         {
2733           struct face *face;
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);
2743           if (!face->stipple)
2744             [(NS_FACE_BACKGROUND (face) != 0
2745               ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2746               : FRAME_BACKGROUND_COLOR (s->f)) set];
2747           else
2748             {
2749               struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (s->f);
2750               [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2751             }
2753           if (s->hl != DRAW_CURSOR)
2754             {
2755               NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2756                                     s->background_width,
2757                                     s->height-2*box_line_width);
2759               /* expand full-width row over internal borders */
2760               if (s->row->full_width_p)
2761                 {
2762                   int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2763                   if (r.origin.y <= fibw+1 + box_line_width)
2764                     {
2765                       r.size.height += r.origin.y;
2766                       r.origin.y = 0;
2767                     }
2768                   if (r.origin.x <= fibw+1)
2769                     {
2770                       r.size.width += 2*r.origin.x;
2771                       r.origin.x = 0;
2772                     }
2773                   if (FRAME_PIXEL_WIDTH (s->f) - (r.origin.x + r.size.width)
2774                       <= fibw+1)
2775                     r.size.width += fibw;
2776                 }
2778               NSRectFill (r);
2779             }
2781           s->background_filled_p = 1;
2782         }
2783     }
2787 static void
2788 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2789 /* --------------------------------------------------------------------------
2790       Renders an image and associated borders.
2791    -------------------------------------------------------------------------- */
2793   EmacsImage *img = s->img->pixmap;
2794   int box_line_vwidth = max (s->face->box_line_width, 0);
2795   int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2796   int bg_x, bg_y, bg_height;
2797   int th;
2798   char raised_p;
2799   NSRect br;
2801   NSTRACE (ns_dumpglyphs_image);
2803   if (s->face->box != FACE_NO_BOX
2804       && s->first_glyph->left_box_line_p && s->slice.x == 0)
2805     x += abs (s->face->box_line_width);
2807   bg_x = x;
2808   bg_y =  s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2809   bg_height = s->height;
2810   /* other terms have this, but was causing problems w/tabbar mode */
2811   /* - 2 * box_line_vwidth; */
2813   if (s->slice.x == 0) x += s->img->hmargin;
2814   if (s->slice.y == 0) y += s->img->vmargin;
2816   /* Draw BG: if we need larger area than image itself cleared, do that,
2817      otherwise, since we composite the image under NS (instead of mucking
2818      with its background color), we must clear just the image area. */
2819   [ns_lookup_indexed_color (NS_FACE_BACKGROUND
2820             (FACE_FROM_ID (s->f, s->first_glyph->face_id)), s->f) set];
2822   if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
2823       || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
2824     {
2825       br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
2826       s->background_filled_p = 1;
2827     }
2828   else
2829     {
2830       br = NSMakeRect (x, y, s->slice.width, s->slice.height);
2831     }
2833   /* expand full-width row over internal borders */
2834   if (s->row->full_width_p)
2835     {
2836       int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2837       if (br.origin.y <= fibw+1 + box_line_vwidth)
2838         {
2839           br.size.height += br.origin.y;
2840           br.origin.y = 0;
2841         }
2842       if (br.origin.x <= fibw+1 + box_line_vwidth)
2843         {
2844           br.size.width += br.origin.x;
2845           br.origin.x = 0;
2846         }
2847       if (FRAME_PIXEL_WIDTH (s->f) - (br.origin.x + br.size.width) <= fibw+1)
2848         br.size.width += fibw;
2849     }
2851   NSRectFill (br);
2853   /* Draw the image.. do we need to draw placeholder if img ==nil? */
2854   if (img != nil)
2855     [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
2856                 operation: NSCompositeSourceOver];
2858   /* Draw relief, if requested */
2859   if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
2860     {
2861       if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
2862         {
2863           th = tool_bar_button_relief >= 0 ?
2864             tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2865           raised_p = (s->hl == DRAW_IMAGE_RAISED);
2866         }
2867       else
2868         {
2869           th = abs (s->img->relief);
2870           raised_p = (s->img->relief > 0);
2871         }
2873       r.origin.x = x - th;
2874       r.origin.y = y - th;
2875       r.size.width = s->slice.width + 2*th-1;
2876       r.size.height = s->slice.height + 2*th-1;
2877       ns_draw_relief (r, th, raised_p,
2878                      s->slice.y == 0,
2879                      s->slice.y + s->slice.height == s->img->height,
2880                      s->slice.x == 0,
2881                      s->slice.x + s->slice.width == s->img->width, s);
2882     }
2886 static void
2887 ns_draw_glyph_string (struct glyph_string *s)
2888 /* --------------------------------------------------------------------------
2889       External (RIF): Main draw-text call.
2890    -------------------------------------------------------------------------- */
2892   /* TODO (optimize): focus for box and contents draw */
2893   NSRect r[2];
2894   int n;
2895   char box_drawn_p = 0;
2897   NSTRACE (ns_draw_glyph_string);
2899   if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
2900     {
2901       int width;
2902       struct glyph_string *next;
2904       for (width = 0, next = s->next;
2905            next && width < s->right_overhang;
2906            width += next->width, next = next->next)
2907         if (next->first_glyph->type != IMAGE_GLYPH)
2908           {
2909             n = ns_get_glyph_string_clip_rect (s->next, r);
2910             ns_focus (s->f, r, n);
2911             ns_maybe_dumpglyphs_background (s->next, 1);
2912             ns_unfocus (s->f);
2913             next->num_clips = 0;
2914           }
2915     }
2917   if (!s->for_overlaps && s->face->box != FACE_NO_BOX
2918         && (s->first_glyph->type == CHAR_GLYPH
2919             || s->first_glyph->type == COMPOSITE_GLYPH))
2920     {
2921       n = ns_get_glyph_string_clip_rect (s, r);
2922       ns_focus (s->f, r, n);
2923       ns_maybe_dumpglyphs_background (s, 1);
2924       ns_dumpglyphs_box_or_relief (s);
2925       ns_unfocus (s->f);
2926       box_drawn_p = 1;
2927     }
2929   switch (s->first_glyph->type)
2930     {
2932     case IMAGE_GLYPH:
2933       n = ns_get_glyph_string_clip_rect (s, r);
2934       ns_focus (s->f, r, n);
2935       ns_dumpglyphs_image (s, r[0]);
2936       ns_unfocus (s->f);
2937       break;
2939     case STRETCH_GLYPH:
2940       if (!s->background_filled_p)
2941         {
2942           *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
2944           if (!s->row->full_width_p)
2945             {
2946               /* truncate to avoid overwriting fringe and/or scrollbar */
2947               int overrun = max (0, (s->x + s->background_width)
2948                                  - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
2949                                     - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
2950               r[0].size.width -= overrun;
2952               /* XXX: Try to work between problem where a stretch glyph on
2953                   a partially-visible bottom row will clear part of the
2954                   modeline, and another where list-buffers headers and similar
2955                   rows erroneously have visible_height set to 0.  Not sure
2956                   where this is coming from as other terms seem not to show. */
2957               r[0].size.height = min (s->height, s->row->visible_height);
2958             }
2960           /* expand full-width rows over internal borders */
2961           else
2962             {
2963               r[0] = ns_fix_rect_ibw (r[0], FRAME_INTERNAL_BORDER_WIDTH (s->f),
2964                                      FRAME_PIXEL_WIDTH (s->f));
2965             }
2967           /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
2968              overwriting cursor (usually when cursor on a tab) */
2969           if (s->hl == DRAW_CURSOR)
2970             {
2971               r[0].origin.x += s->width;
2972               r[0].size.width -= s->width;
2973             }
2975           ns_focus (s->f, r, 1);
2976           [ns_lookup_indexed_color (NS_FACE_BACKGROUND
2977                (FACE_FROM_ID (s->f, s->first_glyph->face_id)), s->f) set];
2978           NSRectFill (r[0]);
2979           ns_unfocus (s->f);
2980           s->background_filled_p = 1;
2981         }
2982       break;
2984     case CHAR_GLYPH:
2985     case COMPOSITE_GLYPH:
2986       n = ns_get_glyph_string_clip_rect (s, r);
2987       ns_focus (s->f, r, n);
2989       if (s->for_overlaps || (s->cmp_from > 0
2990                               && ! s->first_glyph->u.cmp.automatic))
2991         s->background_filled_p = 1;
2992       else      /* 1 */
2993         ns_maybe_dumpglyphs_background
2994           (s, s->first_glyph->type == COMPOSITE_GLYPH);
2996       ns_tmp_flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
2997                     (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
2998                      (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
2999                       NS_DUMPGLYPH_NORMAL));
3000       ns_tmp_font = (struct nsfont_info *)s->face->font;
3001       if (ns_tmp_font == NULL)
3002           ns_tmp_font = (struct nsfont_info *)FRAME_FONT (s->f);
3004       ns_tmp_font->font.driver->draw
3005         (s, 0, s->nchars, s->x, s->y,
3006          (ns_tmp_flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3007          || ns_tmp_flags == NS_DUMPGLYPH_MOUSEFACE);
3009       ns_unfocus (s->f);
3010       break;
3012     default:
3013       abort ();
3014     }
3016   /* Draw box if not done already. */
3017   if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3018     {
3019       n = ns_get_glyph_string_clip_rect (s, r);
3020       ns_focus (s->f, r, n);
3021       ns_dumpglyphs_box_or_relief (s);
3022       ns_unfocus (s->f);
3023     }
3025   s->num_clips = 0;
3030 /* ==========================================================================
3032     Event loop
3034    ========================================================================== */
3037 static void
3038 ns_send_appdefined (int value)
3039 /* --------------------------------------------------------------------------
3040     Internal: post an appdefined event which EmacsApp-sendEvent will
3041               recognize and take as a command to halt the event loop.
3042    -------------------------------------------------------------------------- */
3044   /*NSTRACE (ns_send_appdefined); */
3046   /* Only post this event if we haven't already posted one.  This will end
3047        the [NXApp run] main loop after having processed all events queued at
3048        this moment.  */
3049   if (send_appdefined)
3050     {
3051       NSEvent *nxev;
3053       /* We only need one NX_APPDEFINED event to stop NXApp from running.  */
3054       send_appdefined = NO;
3056       /* Don't need wakeup timer any more */
3057       if (timed_entry)
3058         {
3059           [timed_entry invalidate];
3060           [timed_entry release];
3061           timed_entry = nil;
3062         }
3064       /* Ditto for file descriptor poller */
3065       if (fd_entry)
3066         {
3067           [fd_entry invalidate];
3068           [fd_entry release];
3069           fd_entry = nil;
3070         }
3072       nxev = [NSEvent otherEventWithType: NSApplicationDefined
3073                                 location: NSMakePoint (0, 0)
3074                            modifierFlags: 0
3075                                timestamp: 0
3076                             windowNumber: [[NSApp mainWindow] windowNumber]
3077                                  context: [NSApp context]
3078                                  subtype: 0
3079                                    data1: value
3080                                    data2: 0];
3082       /* Post an application defined event on the event queue.  When this is
3083          received the [NXApp run] will return, thus having processed all
3084          events which are currently queued.  */
3085       [NSApp postEvent: nxev atStart: NO];
3086     }
3090 static int
3091 ns_read_socket (struct terminal *terminal, int expected,
3092                 struct input_event *hold_quit)
3093 /* --------------------------------------------------------------------------
3094      External (hook): Post an event to ourself and keep reading events until
3095      we read it back again.  In effect process all events which were waiting.
3096    23: Now we have to manage the event buffer ourselves.
3097    -------------------------------------------------------------------------- */
3099   struct input_event ev;
3100   int nevents;
3101   static NSDate *lastCheck = nil;
3102 /*  NSTRACE (ns_read_socket); */
3104   if (interrupt_input_blocked)
3105     {
3106       interrupt_input_pending = 1;
3107       return -1;
3108     }
3110   interrupt_input_pending = 0;
3111   BLOCK_INPUT;
3113 #ifdef COCOA_EXPERIMENTAL_CTRL_G
3114   /* causes Feval to abort; unclear on why this isn't in calling code */
3115   ++handling_signal;
3116 #endif
3118   n_emacs_events_pending = 0;
3119   EVENT_INIT (ev);
3120   emacs_event = &ev;
3121   q_event_ptr = hold_quit;
3123   /* we manage autorelease pools by allocate/reallocate each time around
3124      the loop; strict nesting is occasionally violated but seems not to
3125      matter.. earlier methods using full nesting caused major memory leaks */
3126   [outerpool release];
3127   outerpool = [[NSAutoreleasePool alloc] init];
3129   /* If have pending open-file requests, attend to the next one of those. */
3130   if (ns_pending_files && [ns_pending_files count] != 0
3131       && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3132     {
3133       [ns_pending_files removeObjectAtIndex: 0];
3134     }
3135   /* Deal with pending service requests. */
3136   else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3137     && [(EmacsApp *)
3138          NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3139                       withArg: [ns_pending_service_args objectAtIndex: 0]])
3140     {
3141       [ns_pending_service_names removeObjectAtIndex: 0];
3142       [ns_pending_service_args removeObjectAtIndex: 0];
3143     }
3144   else
3145     {
3146       /* Run and wait for events.  We must always send one NX_APPDEFINED event
3147          to ourself, otherwise [NXApp run] will never exit.  */
3148       send_appdefined = YES;
3150       /* TODO: from termhooks.h: */
3151       /* XXX Please note that a non-zero value of EXPECTED only means that
3152      there is available input on at least one of the currently opened
3153      terminal devices -- but not necessarily on this device.
3154      Therefore, in most cases EXPECTED should be simply ignored. */
3155       /* However, if in ns_select, this is called from gobble_input, which
3156          appears to set it correctly for our purposes, and always assuming
3157          !expected causes 100% CPU usage. */
3158       if (!inNsSelect || !expected)
3159         {
3160           /* Post an application defined event on the event queue.  When this is
3161              received the [NXApp run] will return, thus having processed all
3162              events which are currently queued, if any.  */
3163           ns_send_appdefined (-1);
3164         }
3166       [NSApp run];
3167     }
3169   nevents = n_emacs_events_pending;
3170   n_emacs_events_pending = 0;
3171   emacs_event = q_event_ptr = NULL;
3173 #ifdef COCOA_EXPERIMENTAL_CTRL_G
3174   --handling_signal;
3175 #endif
3176   UNBLOCK_INPUT;
3177   return nevents;
3182 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3183            fd_set *exceptfds, struct timeval *timeout)
3184 /* --------------------------------------------------------------------------
3185      Replacement for select, checking for events
3186    -------------------------------------------------------------------------- */
3188   int result;
3189   double time;
3190   NSEvent *ev;
3191 /*  NSTRACE (ns_select); */
3193   if (NSApp == nil /* || ([NSApp isActive] == NO &&
3194                       [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
3195  inMode:NSDefaultRunLoopMode dequeue:NO] == nil) */)
3196     return select (nfds, readfds, writefds, exceptfds, timeout);
3198   /* Save file descriptor set, which gets overwritten in calls to select ()
3199      Note, this is called from process.c, and only readfds is ever set */
3200   if (readfds)
3201     {
3202       memcpy (&select_readfds, readfds, sizeof (fd_set));
3203       select_nfds = nfds;
3204     }
3205   else
3206     select_nfds = 0;
3208     /* Try an initial select for pending data on input files */
3209   select_timeout.tv_sec = select_timeout.tv_usec = 0;
3210   result = select (nfds, readfds, writefds, exceptfds, &select_timeout);
3211   if (result)
3212     return result;
3214   /* if (!timeout || timed_entry || fd_entry)
3215        fprintf (stderr, "assertion failed: timeout null or timed_entry/fd_entry non-null in ns_select\n"); */
3217     /* set a timeout and run the main AppKit event loop while continuing
3218        to monitor the files */
3219   time = ((double) timeout->tv_sec) + ((double) timeout->tv_usec)/1000000.0;
3220   timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3221                                            target: NSApp
3222                                          selector: @selector (timeout_handler:)
3223                                          userInfo: 0
3224                                           repeats: YES] /* for safe removal */
3225                                                          retain];
3227   /* set a periodic task to try the select () again */
3228   fd_entry = [[NSTimer scheduledTimerWithTimeInterval: 0.1
3229                                                target: NSApp
3230                                              selector: @selector (fd_handler:)
3231                                              userInfo: 0
3232                                               repeats: YES]
3233                retain];
3235   /* Let Application dispatch events until it receives an event of the type
3236        NX_APPDEFINED, which should only be sent by timeout_handler.  */
3237   inNsSelect = 1;
3238   gobble_input (timeout ? 1 : 0);
3239   ev = last_appdefined_event;
3240   inNsSelect = 0;
3242   if (ev)
3243     {
3244       int t;
3245       if ([ev type] != NSApplicationDefined)
3246         abort ();
3248       t = [ev data1];
3249       last_appdefined_event = 0;
3251       if (t == -2)
3252         {
3253           /* The NX_APPDEFINED event we received was a timeout. */
3254           return 0;
3255         }
3256       else if (t == -1)
3257         {
3258           /* The NX_APPDEFINED event we received was the result of
3259              at least one real input event arriving.  */
3260           errno = EINTR;
3261           return -1;
3262         }
3263       else
3264         {
3265           /* Received back from select () in fd_handler; copy the results */
3266           if (readfds)
3267             memcpy (readfds, &select_readfds, sizeof (fd_set));
3268           return t;
3269         }
3270     }
3271   /* never reached, shut compiler up */
3272   return 0;
3277 /* ==========================================================================
3279     Scrollbar handling
3281    ========================================================================== */
3284 static void
3285 ns_set_vertical_scroll_bar (struct window *window,
3286                            int portion, int whole, int position)
3287 /* --------------------------------------------------------------------------
3288       External (hook): Update or add scrollbar
3289    -------------------------------------------------------------------------- */
3291   Lisp_Object win;
3292   NSRect r, v;
3293   struct frame *f = XFRAME (WINDOW_FRAME (window));
3294   EmacsView *view = FRAME_NS_VIEW (f);
3295   int window_y, window_height;
3296   BOOL barOnVeryLeft, barOnVeryRight;
3297   int top, left, height, width, sb_width, sb_left;
3298   EmacsScroller *bar;
3299 static int count = 0;
3301   /* optimization; display engine sends WAY too many of these.. */
3302   if (!NILP (window->vertical_scroll_bar))
3303     {
3304       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3305       if ([bar checkSamePosition: position portion: portion whole: whole])
3306         {
3307           if (view->scrollbarsNeedingUpdate == 0)
3308             {
3309               if (!windows_or_buffers_changed)
3310                   return;
3311             }
3312           else
3313             view->scrollbarsNeedingUpdate--;
3314         }
3315     }
3317   NSTRACE (ns_set_vertical_scroll_bar);
3319   /* Get dimensions.  */
3320   window_box (window, -1, 0, &window_y, 0, &window_height);
3321   top = window_y;
3322   height = window_height;
3323   width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3324   left = WINDOW_SCROLL_BAR_AREA_X (window);
3326   if (top < 5) /* top scrollbar adjustment */
3327     {
3328       top -= FRAME_INTERNAL_BORDER_WIDTH (f);
3329       height += FRAME_INTERNAL_BORDER_WIDTH (f);
3330     }
3332   /* allow for displaying a skinnier scrollbar than char area allotted */
3333   sb_width = (WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) > 0) ?
3334     WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) : width;
3336   barOnVeryLeft = left < 5;
3337   barOnVeryRight = FRAME_PIXEL_WIDTH (f) - left - width < 5;
3338   sb_left = left + FRAME_INTERNAL_BORDER_WIDTH (f)
3339       * (barOnVeryLeft ? -1 : (barOnVeryRight ? 1 : 0));
3341   r = NSMakeRect (sb_left, top, sb_width, height);
3342   /* the parent view is flipped, so we need to flip y value */
3343   v = [view frame];
3344   r.origin.y = (v.size.height - r.size.height - r.origin.y);
3346   XSETWINDOW (win, window);
3347   BLOCK_INPUT;
3349   /* we want at least 5 lines to display a scrollbar */
3350   if (WINDOW_TOTAL_LINES (window) < 5)
3351     {
3352       if (!NILP (window->vertical_scroll_bar))
3353         {
3354           bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3355           [bar removeFromSuperview];
3356           window->vertical_scroll_bar = Qnil;
3357         }
3358       ns_clear_frame_area (f, sb_left, top, width, height);
3359       UNBLOCK_INPUT;
3360       return;
3361     }
3363   if (NILP (window->vertical_scroll_bar))
3364     {
3365       ns_clear_frame_area (f, sb_left, top, width, height);
3366       bar = [[EmacsScroller alloc] initFrame: r window: win];
3367       window->vertical_scroll_bar = make_save_value (bar, 0);
3368     }
3369   else
3370     {
3371       NSRect oldRect;
3372       bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3373       oldRect = [bar frame];
3374       r.size.width = oldRect.size.width;
3375       if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3376         {
3377           if (oldRect.origin.x != r.origin.x)
3378               ns_clear_frame_area (f, sb_left, top, width, height);
3379           [bar setFrame: r];
3380         }
3381     }
3383   [bar setPosition: position portion: portion whole: whole];
3384   UNBLOCK_INPUT;
3388 static void
3389 ns_condemn_scroll_bars (struct frame *f)
3390 /* --------------------------------------------------------------------------
3391      External (hook): arrange for all frame's scrollbars to be removed
3392      at next call to judge_scroll_bars, except for those redeemed.
3393    -------------------------------------------------------------------------- */
3395   int i;
3396   id view;
3397   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3399   NSTRACE (ns_condemn_scroll_bars);
3401   for (i =[subviews count]-1; i >= 0; i--)
3402     {
3403       view = [subviews objectAtIndex: i];
3404       if ([view isKindOfClass: [EmacsScroller class]])
3405         [view condemn];
3406     }
3410 static void
3411 ns_redeem_scroll_bar (struct window *window)
3412 /* --------------------------------------------------------------------------
3413      External (hook): arrange to spare this window's scrollbar
3414      at next call to judge_scroll_bars.
3415    -------------------------------------------------------------------------- */
3417   id bar;
3418   NSTRACE (ns_redeem_scroll_bar);
3419   if (!NILP (window->vertical_scroll_bar))
3420     {
3421       bar =XNS_SCROLL_BAR (window->vertical_scroll_bar);
3422       [bar reprieve];
3423     }
3427 static void
3428 ns_judge_scroll_bars (struct frame *f)
3429 /* --------------------------------------------------------------------------
3430      External (hook): destroy all scrollbars on frame that weren't
3431      redeemed after call to condemn_scroll_bars.
3432    -------------------------------------------------------------------------- */
3434   int i;
3435   id view;
3436   NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3437   NSTRACE (ns_judge_scroll_bars);
3438   for (i =[subviews count]-1; i >= 0; i--)
3439     {
3440       view = [subviews objectAtIndex: i];
3441       if (![view isKindOfClass: [EmacsScroller class]]) continue;
3442       [view judge];
3443     }
3448 /* ==========================================================================
3450     Miscellaneous, mainly stubbed-out functions added in 23
3452    ========================================================================== */
3455 void
3456 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
3462 /* ==========================================================================
3464     Initialization
3466    ========================================================================== */
3469 x_display_pixel_height (dpyinfo)
3470      struct ns_display_info *dpyinfo;
3472   NSScreen *screen = [NSScreen mainScreen];
3473   return [screen frame].size.height;
3477 x_display_pixel_width (dpyinfo)
3478      struct ns_display_info *dpyinfo;
3480   NSScreen *screen = [NSScreen mainScreen];
3481   return [screen frame].size.width;
3485 static Lisp_Object ns_string_to_lispmod (const char *s)
3486 /* --------------------------------------------------------------------------
3487      Convert modifier name to lisp symbol
3488    -------------------------------------------------------------------------- */
3490   if (!strncmp (SDATA (SYMBOL_NAME (Qmeta)), s, 10))
3491     return Qmeta;
3492   else if (!strncmp (SDATA (SYMBOL_NAME (Qsuper)), s, 10))
3493     return Qsuper;
3494   else if (!strncmp (SDATA (SYMBOL_NAME (Qcontrol)), s, 10))
3495     return Qcontrol;
3496   else if (!strncmp (SDATA (SYMBOL_NAME (Qalt)), s, 10))
3497     return Qalt;
3498   else if (!strncmp (SDATA (SYMBOL_NAME (Qhyper)), s, 10))
3499     return Qhyper;
3500   else if (!strncmp (SDATA (SYMBOL_NAME (Qnone)), s, 10))
3501     return Qnone;
3502   else
3503     return Qnil;
3507 static Lisp_Object ns_mod_to_lisp (int m)
3508 /* --------------------------------------------------------------------------
3509      Convert modifier code (see lisp.h) to lisp symbol
3510    -------------------------------------------------------------------------- */
3512   if (m == CHAR_META)
3513     return Qmeta;
3514   else if (m == CHAR_SUPER)
3515     return Qsuper;
3516   else if (m == CHAR_CTL)
3517     return Qcontrol;
3518   else if (m == CHAR_ALT)
3519     return Qalt;
3520   else if (m == CHAR_HYPER)
3521     return Qhyper;
3522   else /* if (m == 0) */
3523     return Qnone;
3527 static void
3528 ns_set_default_prefs ()
3529 /* --------------------------------------------------------------------------
3530       Initialize preference variables to defaults
3531    -------------------------------------------------------------------------- */
3533   ns_alternate_modifier = Qmeta;
3534   ns_command_modifier = Qsuper;
3535   ns_control_modifier = Qcontrol;
3536   ns_function_modifier = Qnone;
3537   ns_expand_space = make_float (0.0);
3538   ns_antialias_text = Qt;
3539   ns_antialias_threshold = 10.0; /* not exposed to lisp side */
3540   ns_use_qd_smoothing = Qnil;
3541   ns_use_system_highlight_color = Qt;
3545 static void
3546 ns_default (const char *parameter, Lisp_Object *result,
3547            Lisp_Object yesval, Lisp_Object noval,
3548            BOOL is_float, BOOL is_modstring)
3549 /* --------------------------------------------------------------------------
3550       Check a parameter value in user's preferences
3551    -------------------------------------------------------------------------- */
3553   const char *value;
3555   if ( (value =[[[NSUserDefaults standardUserDefaults]
3556                    stringForKey: [NSString stringWithUTF8String: parameter]]
3557                 UTF8String]) )
3558     {
3559       double f;
3560       char *pos;
3561       if (strcasecmp (value, "YES") == 0)
3562         *result = yesval;
3563       else if (strcasecmp (value, "NO") == 0)
3564         *result = noval;
3565       else if (is_float && (f = strtod (value, &pos), pos != value))
3566         *result = make_float (f);
3567       else if (is_modstring && value)
3568         *result = ns_string_to_lispmod (value);
3569       else fprintf (stderr,
3570                    "Bad value for default \"%s\": \"%s\"\n", parameter, value);
3571     }
3575 void
3576 ns_initialize_display_info (struct ns_display_info *dpyinfo)
3577 /* --------------------------------------------------------------------------
3578       Initialize global info and storage for display.
3579    -------------------------------------------------------------------------- */
3581     NSScreen *screen = [NSScreen mainScreen];
3582     NSWindowDepth depth = [screen depth];
3584     dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
3585     dpyinfo->resy = 72.27;
3586     dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
3587                                                   NSColorSpaceFromDepth (depth)]
3588                 && ![NSCalibratedWhiteColorSpace isEqualToString:
3589                                                  NSColorSpaceFromDepth (depth)];
3590     dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
3591     dpyinfo->image_cache = make_image_cache ();
3592     dpyinfo->color_table
3593       = (struct ns_color_table *)xmalloc (sizeof (struct ns_color_table));
3594     dpyinfo->color_table->colors = NULL;
3595     dpyinfo->root_window = 42; /* a placeholder.. */
3597     dpyinfo->mouse_face_mouse_frame = NULL;
3598     dpyinfo->mouse_face_deferred_gc = 0;
3599     dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
3600     dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
3601     dpyinfo->mouse_face_face_id = DEFAULT_FACE_ID;
3602     dpyinfo->mouse_face_window = dpyinfo->mouse_face_overlay = Qnil;
3603     dpyinfo->mouse_face_hidden = 0;
3605     dpyinfo->mouse_face_mouse_x = dpyinfo->mouse_face_mouse_y = 0;
3606     dpyinfo->mouse_face_defer = 0;
3608     dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
3610     dpyinfo->n_fonts = 0;
3611     dpyinfo->smallest_font_height = 1;
3612     dpyinfo->smallest_char_width = 1;
3616 /* 23: Needed as new part of display engine; this and next define public
3617       functions in this file (well, many of them, anyway). */
3618 /* x_... are generic versions in xdisp.c that we, and other terms, get away
3619          with using despite presence in the "system dependent" redisplay
3620          interface.  In addition, many of the ns_ methods have code that is
3621          shared with all terms, indicating need for further refactoring. */
3622 extern frame_parm_handler ns_frame_parm_handlers[];
3623 static struct redisplay_interface ns_redisplay_interface =
3625   ns_frame_parm_handlers,
3626   x_produce_glyphs, /*generic OK */
3627   x_write_glyphs, /*generic OK */
3628   x_insert_glyphs, /*generic OK */
3629   x_clear_end_of_line, /*generic OK */
3630   ns_scroll_run, /*23 */
3631   ns_after_update_window_line, /*23: added */
3632   ns_update_window_begin, /*23: split from update_begin */
3633   ns_update_window_end, /*23: split from update_end */
3634   x_cursor_to, /*generic OK */
3635   ns_flush,
3636   0, /* flush_display_optional */
3637   x_clear_window_mouse_face, /*generic OK */
3638   x_get_glyph_overhangs, /*23: generic OK */
3639   x_fix_overlapping_area, /*generic OK */
3640   ns_draw_fringe_bitmap, /*23 */
3641   0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
3642   0, /* destroy_fringe_bitmap */
3643   ns_compute_glyph_string_overhangs, /*23 */
3644   ns_draw_glyph_string, /*23: interface to nsfont.m */
3645   ns_define_frame_cursor, /*23 */
3646   ns_clear_frame_area, /*23 */
3647   ns_draw_window_cursor, /*23: revamped ns_dumpcursor */
3648   ns_draw_vertical_window_border,
3649   ns_shift_glyphs_for_insert
3653 static void
3654 ns_delete_display (struct ns_display_info *dpyinfo)
3656   /* TODO... */
3660 /* This function is called when the last frame on a display is deleted. */
3661 static void
3662 ns_delete_terminal (struct terminal *terminal)
3664   struct ns_display_info *dpyinfo = terminal->display_info.ns;
3665   int i;
3667   /* Protect against recursive calls.  delete_frame in
3668      delete_terminal calls us back when it deletes our last frame.  */
3669   if (!terminal->name)
3670     return;
3672   BLOCK_INPUT;
3674   x_destroy_all_bitmaps (dpyinfo);
3675   ns_delete_display (dpyinfo);
3676   UNBLOCK_INPUT;
3680 static struct terminal *
3681 ns_create_terminal (struct ns_display_info *dpyinfo)
3682 /* --------------------------------------------------------------------------
3683       Set up use of NS before we make the first connection.
3684    -------------------------------------------------------------------------- */
3686   struct terminal *terminal;
3688   NSTRACE (ns_create_terminal);
3690   terminal = create_terminal ();
3692   terminal->type = output_ns;
3693   terminal->display_info.ns = dpyinfo;
3694   dpyinfo->terminal = terminal;
3696   terminal->rif = &ns_redisplay_interface;
3698   terminal->clear_frame_hook = ns_clear_frame;
3699   terminal->ins_del_lines_hook = 0; /* 23: vestigial? */
3700   terminal->delete_glyphs_hook = 0; /* 23: vestigial? */
3701   terminal->ring_bell_hook = ns_ring_bell;
3702   terminal->reset_terminal_modes_hook = ns_reset_terminal_modes;
3703   terminal->set_terminal_modes_hook = ns_set_terminal_modes;
3704   terminal->update_begin_hook = ns_update_begin;
3705   terminal->update_end_hook = ns_update_end;
3706   terminal->set_terminal_window_hook = NULL; /* 23: vestigial? */
3707   terminal->read_socket_hook = ns_read_socket;
3708   terminal->frame_up_to_date_hook = ns_frame_up_to_date;
3709   terminal->mouse_position_hook = ns_mouse_position;
3710   terminal->frame_rehighlight_hook = ns_frame_rehighlight;
3711   terminal->frame_raise_lower_hook = ns_frame_raise_lower;
3713   terminal->fullscreen_hook = 0; /*XTfullscreen_hook;//23.50 */
3715   terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
3716   terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
3717   terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
3718   terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
3720   terminal->delete_frame_hook = x_destroy_window;
3721   terminal->delete_terminal_hook = ns_delete_terminal;
3723   terminal->scroll_region_ok = 1;
3724   terminal->char_ins_del_ok = 1;
3725   terminal->line_ins_del_ok = 1;
3726   terminal->fast_clear_end_of_line = 1;
3727   terminal->memory_below_frame = 0;
3729   return terminal;
3733 void
3734 ns_initialize ()
3735 /* --------------------------------------------------------------------------
3736    Mainly vestigial under NS now that ns_create_terminal () does most things.
3737    -------------------------------------------------------------------------- */
3739   baud_rate = 38400;
3740   Fset_input_interrupt_mode (Qt);
3744 struct ns_display_info *
3745 ns_term_init (Lisp_Object display_name)
3746 /* --------------------------------------------------------------------------
3747      Start the Application and get things rolling.
3748    -------------------------------------------------------------------------- */
3750   extern Lisp_Object Fset_input_mode (Lisp_Object, Lisp_Object,
3751                                      Lisp_Object, Lisp_Object);
3752   struct terminal *terminal;
3753   struct ns_display_info *dpyinfo;
3754   static int ns_initialized = 0;
3755   Lisp_Object tmp;
3757   NSTRACE (ns_term_init);
3759   /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
3760   /*GSDebugAllocationActive (YES); */
3761   BLOCK_INPUT;
3762   handling_signal = 0;
3764   if (!ns_initialized)
3765     {
3766       ns_initialize ();
3767       ns_initialized = 1;
3768     }
3770   ns_pending_files = [[NSMutableArray alloc] init];
3771   ns_pending_service_names = [[NSMutableArray alloc] init];
3772   ns_pending_service_args = [[NSMutableArray alloc] init];
3774   /* Start app and create the main menu, window, view.
3775      Needs to be here because ns_initialize_display_info () uses AppKit classes.
3776      The view will then ask the NSApp to stop and return to Emacs. */
3777   [EmacsApp sharedApplication];
3778   if (NSApp == nil)
3779     return NULL;
3780   [NSApp setDelegate: NSApp];
3782   /* debugging: log all notifications */
3783   /*   [[NSNotificationCenter defaultCenter] addObserver: NSApp
3784                                          selector: @selector (logNotification:)
3785                                              name: nil object: nil]; */
3787   dpyinfo = (struct ns_display_info *)xmalloc (sizeof (struct ns_display_info));
3788   bzero (dpyinfo, sizeof (struct ns_display_info));
3790   ns_initialize_display_info (dpyinfo);
3791   terminal = ns_create_terminal (dpyinfo);
3793   terminal->kboard = (KBOARD *) xmalloc (sizeof (KBOARD));
3794   init_kboard (terminal->kboard);
3795   terminal->kboard->Vwindow_system = Qns;
3796   terminal->kboard->next_kboard = all_kboards;
3797   all_kboards = terminal->kboard;
3798   /* Don't let the initial kboard remain current longer than necessary.
3799      That would cause problems if a file loaded on startup tries to
3800      prompt in the mini-buffer.  */
3801   if (current_kboard == initial_kboard)
3802     current_kboard = terminal->kboard;
3803   terminal->kboard->reference_count++;
3805   dpyinfo->next = x_display_list;
3806   x_display_list = dpyinfo;
3808   /* Put it on ns_display_name_list */
3809   ns_display_name_list = Fcons (Fcons (display_name, Qnil),
3810                                 ns_display_name_list);
3811 /*      ns_display_name_list = Fcons (Fcons (display_name,
3812                                            Fcons (Qnil, dpyinfo->xrdb)),
3813                                     ns_display_name_list); */
3814   dpyinfo->name_list_element = XCAR (ns_display_name_list);
3816   /* Set the name of the terminal. */
3817   terminal->name = (char *) xmalloc (SBYTES (display_name) + 1);
3818   strncpy (terminal->name, SDATA (display_name), SBYTES (display_name));
3819   terminal->name[SBYTES (display_name)] = 0;
3821   UNBLOCK_INPUT; 
3823   /* Read various user defaults. */
3824   ns_set_default_prefs ();
3825   ns_default ("AlternateModifier", &ns_alternate_modifier,
3826              Qnil, Qnil, NO, YES);
3827   if (NILP (ns_alternate_modifier))
3828     ns_alternate_modifier = Qmeta;
3829   ns_default ("CommandModifier", &ns_command_modifier,
3830              Qnil, Qnil, NO, YES);
3831   if (NILP (ns_command_modifier))
3832     ns_command_modifier = Qsuper;
3833   ns_default ("ControlModifier", &ns_control_modifier,
3834              Qnil, Qnil, NO, YES);
3835   if (NILP (ns_control_modifier))
3836     ns_control_modifier = Qcontrol;
3837   ns_default ("FunctionModifier", &ns_function_modifier,
3838              Qnil, Qnil, NO, YES);
3839   if (NILP (ns_function_modifier))
3840     ns_function_modifier = Qnone;
3841   ns_default ("ExpandSpace", &ns_expand_space,
3842              make_float (0.5), make_float (0.0), YES, NO);
3843   ns_default ("GSFontAntiAlias", &ns_antialias_text,
3844              Qt, Qnil, NO, NO);
3845   tmp = Qnil;
3846   ns_default ("AppleAntiAliasingThreshold", &tmp,
3847              make_float (10.0), make_float (6.0), YES, NO);
3848   ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
3849   ns_default ("UseQuickdrawSmoothing", &ns_use_qd_smoothing,
3850              Qt, Qnil, NO, NO);
3851   ns_default ("UseSystemHighlightColor", &ns_use_system_highlight_color,
3852              Qt, Qnil, NO, NO);
3853   if (EQ (ns_use_system_highlight_color, Qt))
3854     {
3855       ns_selection_color = [[NSUserDefaults standardUserDefaults]
3856                                stringForKey: @"AppleHighlightColor"];
3857       if (ns_selection_color == nil)
3858         ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
3859     }
3860   else
3861     ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
3863   {
3864     NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
3866     if ( cl == nil )
3867       {
3868         Lisp_Object color_file, color_map, color;
3869         int r,g,b;
3870         unsigned long c;
3871         char *name;
3873         color_file = Fexpand_file_name (build_string ("rgb.txt"),
3874                          Fsymbol_value (intern ("data-directory")));
3875         if (NILP (Ffile_readable_p (color_file)))
3876           fatal ("Could not find %s.\n", SDATA (color_file));
3878         color_map = Fx_load_color_file (color_file);
3879         if (NILP (color_map))
3880           fatal ("Could not read %s.\n", SDATA (color_file));
3882         cl = [[NSColorList alloc] initWithName: @"Emacs"];
3883         for ( ; CONSP (color_map); color_map = XCDR (color_map))
3884           {
3885             color = XCAR (color_map);
3886             name = SDATA (XCAR (color));
3887             c = XINT (XCDR (color));
3888             [cl setColor:
3889                   [NSColor colorWithCalibratedRed: RED_FROM_ULONG (c) / 255.0
3890                                             green: GREEN_FROM_ULONG (c) / 255.0
3891                                              blue: BLUE_FROM_ULONG (c) / 255.0
3892                                             alpha: 1.0]
3893                   forKey: [NSString stringWithUTF8String: name]];
3894           }
3895         [cl writeToFile: nil];
3896       }
3897   }
3899   {
3900     char c[128];
3901 #ifdef NS_IMPL_GNUSTEP
3902     strncpy (c, gnustep_base_version, sizeof (c));
3903 #else
3904     /*PSnextrelease (128, c); */
3905     snprintf (c, sizeof (c), "%g", NSAppKitVersionNumber);
3906 #endif
3907     Vwindow_system_version = build_string (c);
3908   }
3910   delete_keyboard_wait_descriptor (0);
3912 /* Set up OS X app menu */
3913 #ifdef NS_IMPL_COCOA
3914   {
3915     NSMenu *appMenu;
3916     NSMenuItem *item;
3917     /* set up the application menu */
3918     svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
3919     [svcsMenu setAutoenablesItems: NO];
3920     appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
3921     [appMenu setAutoenablesItems: NO];
3922     mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
3923     dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
3925     [appMenu insertItemWithTitle: @"About Emacs"
3926                           action: @selector (orderFrontStandardAboutPanel:)
3927                    keyEquivalent: @""
3928                          atIndex: 0];
3929     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
3930     [appMenu insertItemWithTitle: @"Preferences..."
3931                           action: @selector (showPreferencesWindow:)
3932                    keyEquivalent: @","
3933                          atIndex: 2];
3934     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
3935     item = [appMenu insertItemWithTitle: @"Services"
3936                                  action: @selector (menuDown:)
3937                           keyEquivalent: @""
3938                                 atIndex: 4];
3939     [appMenu setSubmenu: svcsMenu forItem: item];
3940 /*    [svcsMenu setSupercell: item]; */
3941     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
3942     [appMenu insertItemWithTitle: @"Hide Emacs"
3943                           action: @selector (hide:)
3944                    keyEquivalent: @"h"
3945                          atIndex: 6];
3946     item =  [appMenu insertItemWithTitle: @"Hide Others"
3947                           action: @selector (hideOtherApplications:)
3948                    keyEquivalent: @"h"
3949                          atIndex: 7];
3950     [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
3951     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
3952     [appMenu insertItemWithTitle: @"Quit Emacs"
3953                           action: @selector (terminate:)
3954                    keyEquivalent: @"q"
3955                          atIndex: 9];
3957     item = [mainMenu insertItemWithTitle: @"Emacs"
3958                                   action: @selector (menuDown:)
3959                            keyEquivalent: @""
3960                                  atIndex: 0];
3961     [mainMenu setSubmenu: appMenu forItem: item];
3962     [dockMenu insertItemWithTitle: @"New Frame"
3963                            action: @selector (newFrame:)
3964                     keyEquivalent: @""
3965                           atIndex: 0];
3967     [NSApp setMainMenu: mainMenu];
3968     [NSApp setAppleMenu: appMenu];
3969     [NSApp setServicesMenu: svcsMenu];
3970     /* Needed at least on Cocoa, to get dock menu to show windows */
3971     [NSApp setWindowsMenu: [[NSMenu alloc] init]];
3972   }
3973 #endif /* MAC OS X menu setup */
3975   [NSApp run];
3977   return dpyinfo;
3981 extern Lisp_Object Vauto_save_list_file_name;
3982 void
3983 ns_term_shutdown (int sig)
3985   /* code not reached in emacs.c after this is called by shut_down_emacs: */
3986   if (STRINGP (Vauto_save_list_file_name))
3987     unlink (SDATA (Vauto_save_list_file_name));
3989   ns_shutdown_properly = YES;
3990   [NSApp terminate: NSApp];
3994 /* ==========================================================================
3996     EmacsApp implementation
3998    ========================================================================== */
4001 @implementation EmacsApp
4003 - (void)logNotification: (NSNotification *)notification
4005   const char *name = [[notification name] UTF8String];
4006   if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4007       && !strstr (name, "WindowNumber"))
4008     NSLog (@"notification: '%@'", [notification name]);
4012 - (void)sendEvent: (NSEvent *)theEvent
4013 /* --------------------------------------------------------------------------
4014      Events posted by ns_send_appdefined interrupt the run loop here
4015    -------------------------------------------------------------------------- */
4017   int type = [theEvent type];
4018   NSWindow *window = [theEvent window];
4019 /*  NSTRACE (sendEvent); */
4020 /*fprintf (stderr, "received event of type %d\n", [theEvent type]); */
4022   if (type == NSCursorUpdate && window == nil)
4023     {
4024       fprintf (stderr, "Dropping external cursor update event.\n");
4025       return;
4026     }
4028 #ifdef NS_IMPL_COCOA
4029   /* pass mouse down in resize handle and subsequent drags directly to
4030      EmacsWindow so we can generate continuous redisplays */
4031   if (ns_in_resize)
4032     {
4033       if (type == NSLeftMouseDragged)
4034         {
4035           [window mouseDragged: theEvent];
4036           return;
4037         }
4038       else if (type == NSLeftMouseUp)
4039         {
4040           [window mouseUp: theEvent];
4041           return;
4042         }
4043     }
4044   else if (type == NSLeftMouseDown)
4045     {
4046       NSRect r = ns_resize_handle_rect (window);
4047       if (NSPointInRect ([theEvent locationInWindow], r))
4048         {
4049           ns_in_resize = YES;
4050           [window mouseDown: theEvent];
4051           return;
4052         }
4053     }
4054 #endif
4056   if (type == NSApplicationDefined)
4057     {
4058       last_appdefined_event = theEvent;
4059       [self stop: self];
4060     }
4062   [super sendEvent: theEvent];
4066 - (void)showPreferencesWindow: (id)sender
4068   if (prefsController == nil)
4069     prefsController = [[EmacsPrefsController alloc] init];
4070   [prefsController showForFrame: SELECTED_FRAME ()];
4074 - (void)newFrame: (id)sender
4076   struct frame *emacsframe = SELECTED_FRAME ();
4077   NSEvent *theEvent = [NSApp currentEvent];
4079   if (!emacs_event)
4080     return;
4081   emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4082   emacs_event->code = KEY_NS_NEW_FRAME;
4083   emacs_event->modifiers = 0;
4084   EV_TRAILER (theEvent);
4088 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4089 - (BOOL) openFile: (NSString *)fileName
4091   struct frame *emacsframe = SELECTED_FRAME ();
4092   NSEvent *theEvent = [NSApp currentEvent];
4094   if (!emacs_event)
4095     return NO;
4097   emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4098   emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4099   ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4100   ns_input_line = Qnil; /* can be start or cons start,end */
4101   emacs_event->modifiers =0;
4102   EV_TRAILER (theEvent);
4104   return YES;
4108 /* **************************************************************************
4110       EmacsApp delegate implementation
4112    ************************************************************************** */
4114 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4115 /* --------------------------------------------------------------------------
4116      When application is loaded, terminate event loop in ns_term_init
4117    -------------------------------------------------------------------------- */
4119   NSTRACE (applicationDidFinishLaunching);
4120   [NSApp setServicesProvider: NSApp];
4121   ns_send_appdefined (-2);
4125 - (void) terminate: (id)sender
4127   BLOCK_INPUT;
4128   if (ns_shutdown_properly)
4129     [super terminate: sender];
4130   else
4131     {
4132 /*    Fkill_emacs (Qnil); */
4133       ns_shutdown_properly = YES;
4134       Feval (Fcons (intern ("save-buffers-kill-emacs"), Qnil));
4135     }
4136   UNBLOCK_INPUT;
4140 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4142   if (ns_shutdown_properly)
4143     return NSTerminateNow;
4145   Lisp_Object contents = list3 (build_string ("Exit requested.  Would you like to Save Buffers and Exit, or Cancel the request?"),
4146       Fcons (build_string ("Cancel"), Qnil),
4147       Fcons (build_string ("Save and Exit"), Qt));
4148   Lisp_Object res = ns_popup_dialog (Qt, contents, Qnil);
4149 fprintf (stderr, "res = %d\n", EQ (res, Qt)); /* FIXME */
4150   if (EQ (res, Qt))
4151     {
4152       Feval (Fcons (intern ("save-buffers-kill-emacs"), Qnil));
4153       return NSTerminateNow;
4154     }
4155   return NSTerminateCancel;
4159 /*   Notification from the Workspace to open a file */
4160 - (BOOL)application: sender openFile: (NSString *)file
4162   [ns_pending_files addObject: file];
4163   return YES;
4167 /*   Open a file as a temporary file */
4168 - (BOOL)application: sender openTempFile: (NSString *)file
4170   [ns_pending_files addObject: file];
4171   return YES;
4175 /*   Notification from the Workspace to open a file noninteractively (?) */
4176 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4178   [ns_pending_files addObject: file];
4179   return YES;
4183 /*   Notification from the Workspace to open multiple files */
4184 - (void)application: sender openFiles: (NSArray *)fileList
4186   NSEnumerator *files = [fileList objectEnumerator];
4187   NSString *file;
4188   while ((file = [files nextObject]) != nil)
4189     [ns_pending_files addObject: file];
4191 /* TODO: when GNUstep implements this (and we require that version of
4192          GNUstep), remove. */
4193 #ifndef NS_IMPL_GNUSTEP
4194   [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4195 #endif /* !NS_IMPL_GNUSTEP */
4200 /* Handle dock menu requests.  */
4201 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4203   return dockMenu;
4207 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4208 - (void)applicationDidBecomeActive: (NSNotification *)notification
4211 - (void)applicationDidResignActive: (NSNotification *)notification
4213   ns_send_appdefined (-1);
4218 /* ==========================================================================
4220     EmacsApp aux handlers for managing event loop
4222    ========================================================================== */
4225 - (void)timeout_handler: (NSTimer *)timedEntry
4226 /* --------------------------------------------------------------------------
4227      The timeout specified to ns_select has passed.
4228    -------------------------------------------------------------------------- */
4230   /*NSTRACE (timeout_handler); */
4231   ns_send_appdefined (-2);
4234 extern void update_window_cursor (struct window *w, int on);
4236 - (void)fd_handler: (NSTimer *) fdEntry
4237 /* --------------------------------------------------------------------------
4238      Check data waiting on file descriptors and terminate if so
4239    -------------------------------------------------------------------------- */
4241   int result;
4242   /* NSTRACE (fd_handler); */
4244   if (select_nfds == 0)
4245     return;
4247   memcpy (&t_readfds, &select_readfds, sizeof (fd_set));
4249   select_timeout.tv_sec = select_timeout.tv_usec = 0;
4250   result = select (select_nfds, &t_readfds, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
4251                   &select_timeout);
4252   if (result)
4253     {
4254       memcpy (&select_readfds, &t_readfds, sizeof (fd_set));
4255       ns_send_appdefined (result);
4256     }
4261 /* ==========================================================================
4263     Service provision
4265    ========================================================================== */
4267 /* called from system: queue for next pass through event loop */
4268 - (void)requestService: (NSPasteboard *)pboard
4269               userData: (NSString *)userData
4270                  error: (NSString **)error
4272   [ns_pending_service_names addObject: userData];
4273   [ns_pending_service_args addObject: [NSString stringWithUTF8String:
4274       SDATA (ns_string_from_pasteboard (pboard))]];
4278 /* called from ns_read_socket to clear queue */
4279 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
4281   struct frame *emacsframe = SELECTED_FRAME ();
4282   NSEvent *theEvent = [NSApp currentEvent];
4284   if (!emacs_event)
4285     return NO;
4287   emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4288   emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
4289   ns_input_spi_name = build_string ([name UTF8String]);
4290   ns_input_spi_arg = build_string ([arg UTF8String]);
4291   emacs_event->modifiers = EV_MODIFIERS (theEvent);
4292   EV_TRAILER (theEvent);
4294   return YES;
4298 @end  /* EmacsApp */
4302 /* ==========================================================================
4304     EmacsView implementation
4306    ========================================================================== */
4309 @implementation EmacsView
4311 /* needed to inform when window closed from LISP */
4312 - (void) setWindowClosing: (BOOL)closing
4314   windowClosing = closing;
4318 - (void)dealloc
4320   NSTRACE (EmacsView_dealloc);
4321   [toolbar release];
4322   [super dealloc];
4326 /* called on font panel selection */
4327 - (void)changeFont: (id)sender
4329   NSEvent *e =[[self window] currentEvent];
4330   struct face *face =FRAME_DEFAULT_FACE (emacsframe);
4331   id newFont;
4332   float size;
4334   NSTRACE (changeFont);
4335   if (!emacs_event)
4336     return;
4338   if (newFont = [sender convertFont:
4339                            ((struct nsfont_info *)face->font)->nsfont])
4340     {
4341       SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
4343       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4344       emacs_event->modifiers = 0;
4345       emacs_event->code = KEY_NS_CHANGE_FONT;
4347       size = [newFont pointSize];
4348       ns_input_fontsize = make_number (lrint (size));
4349       ns_input_font = build_string ([[newFont familyName] UTF8String]);
4350       EV_TRAILER (e);
4351     }
4355 - (BOOL)acceptsFirstResponder
4357   NSTRACE (acceptsFirstResponder);
4358   return YES;
4362 - (void)resetCursorRects
4364   NSRect visible = [self visibleRect];
4365   NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
4366   NSTRACE (resetCursorRects);
4368   if (currentCursor == nil)
4369     currentCursor = [NSCursor arrowCursor];
4371   if (!NSIsEmptyRect (visible))
4372     [self addCursorRect: visible cursor: currentCursor];
4373   [currentCursor setOnMouseEntered: YES];
4377 /*****************************************************************************/
4378 /* Keyboard handling. */
4379 #define NS_KEYLOG 0
4381 - (void)keyDown: (NSEvent *)theEvent
4383   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4384   int code;
4385   unsigned fnKeysym = 0;
4386   int flags;
4387   static NSMutableArray *nsEvArray;
4388   static BOOL firstTime = YES;
4390   NSTRACE (keyDown);
4392   /* Rhapsody and OS X give up and down events for the arrow keys */
4393   if ([theEvent type] != NSKeyDown)
4394     return;
4396   if (!emacs_event)
4397     return;
4399  if (![[self window] isKeyWindow])
4400    {
4401      /* XXX: Using NO_SOCK_SIGIO like Carbon causes a condition in which,
4402          when Emacs display updates a different frame from the current one,
4403          and temporarily selects it, then processes some interrupt-driven
4404          input (dispnew.c:3878), OS will send the event to the correct NSWindow,
4405          but for some reason that window has its first responder set to the
4406          NSView most recently updated (I guess), which is not the correct one.
4407          UPDATE: After multi-TTY merge this happens even w/o NO_SOCK_SIGIO */
4408      if ([[theEvent window] isKindOfClass: [EmacsWindow class]])
4409          [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
4410      return;
4411    }
4413   if (nsEvArray == nil)
4414     nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
4416   [NSCursor setHiddenUntilMouseMoves: YES];
4418   if (dpyinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
4419     {
4420       clear_mouse_face (dpyinfo);
4421       dpyinfo->mouse_face_hidden = 1;
4422     }
4424   if (!processingCompose)
4425     {
4426       code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
4427         0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
4428       /* (Carbon way: [theEvent keyCode]) */
4430       /* is it a "function key"? */
4431       fnKeysym = ns_convert_key (code);
4432       if (fnKeysym)
4433         {
4434           /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
4435              because Emacs treats Delete and KP-Delete same (in simple.el). */
4436           if (fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
4437             code = 0xFF08; /* backspace */
4438           else
4439             code = fnKeysym;
4440         }
4442       /* are there modifiers? */
4443       emacs_event->modifiers = 0;
4444       flags = [theEvent modifierFlags];
4446       if (flags & NSHelpKeyMask)
4447           emacs_event->modifiers |= hyper_modifier;
4449       if (flags & NSShiftKeyMask)
4450         emacs_event->modifiers |= shift_modifier;
4452       if (flags & NSCommandKeyMask)
4453         {
4454           emacs_event->modifiers |= parse_solitary_modifier (ns_command_modifier);
4455           /* if super (default), take input manager's word so things like
4456              dvorak / qwerty layout work */
4457           if (EQ (ns_command_modifier, Qsuper)
4458               && !fnKeysym
4459               && [[theEvent characters] length] != 0)
4460             {
4461               /* XXX: the code we get will be unshifted, so if we have
4462                  a shift modifier, must convert ourselves */
4463               if (!(flags & NSShiftKeyMask))
4464                 code = [[theEvent characters] characterAtIndex: 0];
4465 #if 0
4466               /* this is ugly and also requires linking w/Carbon framework
4467                  (for LMGetKbdType) so for now leave this rare (?) case
4468                  undealt with.. in future look into CGEvent methods */
4469               else
4470                 {
4471                   long smv = GetScriptManagerVariable (smKeyScript);
4472                   Handle uchrHandle = GetResource
4473                     ('uchr', GetScriptVariable (smv, smScriptKeys));
4474                   UInt32 dummy = 0;
4475                   UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
4476                                  [[theEvent characters] characterAtIndex: 0],
4477                                  kUCKeyActionDisplay,
4478                                  (flags & ~NSCommandKeyMask) >> 8,
4479                                  LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
4480                                  &dummy, 1, &dummy, &code);
4481                   code &= 0xFF;
4482                 }
4483 #endif
4484             }
4485         }
4487       if (flags & NSControlKeyMask)
4488           emacs_event->modifiers |= parse_solitary_modifier (ns_control_modifier);
4490       if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
4491           emacs_event->modifiers |= parse_solitary_modifier (ns_function_modifier);
4493       if (flags & NSAlternateKeyMask) /* default = meta */
4494         {
4495           if (EQ (ns_alternate_modifier, Qnone) && !fnKeysym)
4496             {   /* accept pre-interp alt comb */
4497               if ([[theEvent characters] length] > 0)
4498                 code = [[theEvent characters] characterAtIndex: 0];
4499               /*HACK: clear lone shift modifier to stop next if from firing */
4500               if (emacs_event->modifiers == shift_modifier)
4501                 emacs_event->modifiers = 0;
4502             }
4503           else
4504               emacs_event->modifiers |= parse_solitary_modifier (ns_alternate_modifier);
4505         }
4507 /*fprintf (stderr,"code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",code,fnKeysym,flags,emacs_event->modifiers); */
4509       /* if it was a function key or had modifiers, pass it directly to emacs */
4510       if (fnKeysym || (emacs_event->modifiers
4511                        && [[theEvent charactersIgnoringModifiers] length] > 0))
4512 /*[[theEvent characters] length] */
4513         {
4514           emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4515           if (code < 0x20)
4516             code |= (1<<28)|(3<<16);
4517           else if (code == 0x7f)
4518             code |= (1<<28)|(3<<16);
4519           else if (!fnKeysym)
4520             emacs_event->kind = code > 0xFF
4521               ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4523           emacs_event->code = code;
4524           EV_TRAILER (theEvent);
4525           return;
4526         }
4527     }
4529   /* if we get here we should send the key for input manager processing */
4530   if (firstTime && [[NSInputManager currentInputManager]
4531                      wantsToDelayTextChangeNotifications] == NO)
4532     fprintf (stderr,
4533           "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
4534   firstTime = NO;
4536   if (NS_KEYLOG && !processingCompose)
4537     fprintf (stderr, "Begin compose sequence.\n");
4539   processingCompose = YES;
4540   [nsEvArray addObject: theEvent];
4541   [self interpretKeyEvents: nsEvArray];
4542   [nsEvArray removeObject: theEvent];
4546 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
4549 /* <NSTextInput>: called through when done composing */
4550 - (void)insertText: (id)aString
4552   int code;
4553   int len = [(NSString *)aString length];
4554   int i;
4556 if (NS_KEYLOG) NSLog (@"insertText '%@'\tlen = %d", aString, len);
4557   processingCompose = NO;
4559   if (!emacs_event)
4560     return;
4562   /* first, clear any working text */
4563   if (workingText != nil)
4564     [self deleteWorkingText];
4566   /* now insert the string as keystrokes */
4567   for (i =0; i<len; i++)
4568     {
4569       code = [aString characterAtIndex: i];
4570       /* TODO: still need this? */
4571       if (code == 0x2DC)
4572         code = '~'; /* 0x7E */
4573       emacs_event->modifiers = 0;
4574       emacs_event->kind
4575         = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4576       emacs_event->code = code;
4577       EV_TRAILER ((id)nil);
4578     }
4582 /* <NSTextInput>: inserts display of composing characters */
4583 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
4585   NSString *str = [aString respondsToSelector: @selector (string)] ?
4586     [aString string] : aString;
4587   if (NS_KEYLOG)
4588     NSLog (@"setMarkedText '%@' len =%d range %d from %d", str, [str length],
4589            selRange.length, selRange.location);
4591   if (workingText != nil)
4592     [self deleteWorkingText];
4593   if ([str length] == 0)
4594     return;
4596   if (!emacs_event)
4597     return;
4599   processingCompose = YES;
4600   workingText = [str copy];
4601   ns_working_text = build_string ([workingText UTF8String]);
4603   /* if in "echo area", not true minibuffer, can't show chars in interactive
4604      mode, so call using eval; otherwise we send a key event, which was the
4605      original way this was done */
4606   if (!EQ (Feval (Fcons (intern ("ns-in-echo-area"), Qnil)), Qnil))
4607     {
4608       Feval (Fcons (intern ("ns-echo-working-text"), Qnil));
4609       ns_send_appdefined (-1);
4610     }
4611   else
4612     {
4613       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4614       emacs_event->code = KEY_NS_INSERT_WORKING_TEXT;
4615       EV_TRAILER ((id)nil);
4616     }
4620 /* delete display of composing characters [not in <NSTextInput>] */
4621 - (void)deleteWorkingText
4623   if (workingText == nil)
4624     return;
4625   if (NS_KEYLOG)
4626     fprintf (stderr, "deleteWorkingText len =%d\n", [workingText length]);
4627   [workingText release];
4628   workingText = nil;
4629   processingCompose = NO;
4631   if (!emacs_event)
4632     return;
4634   if (!EQ (Feval (Fcons (intern ("ns-in-echo-area"), Qnil)), Qnil))
4635     {
4636       Feval (Fcons (intern ("ns-unecho-working-text"), Qnil));
4637       ns_send_appdefined (-1);
4638     }
4639   else
4640     {
4641       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4642       emacs_event->code = KEY_NS_DELETE_WORKING_TEXT;
4643       EV_TRAILER ((id)nil);
4644     }
4648 - (BOOL)hasMarkedText
4650   return workingText != nil;
4653 - (NSRange)markedRange
4655   NSRange rng = workingText != nil
4656     ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
4657 if (NS_KEYLOG) NSLog (@"markedRange request");
4658   return rng;
4661 - (void)unmarkText
4663 if (NS_KEYLOG) NSLog (@"unmark (accept) text");
4664   [self deleteWorkingText];
4665   processingCompose = NO;
4668 /* used to position char selection windows, etc. */
4669 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
4671   NSRect rect;
4672   NSPoint pt;
4673   struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
4674 if (NS_KEYLOG) NSLog (@"firstRectForCharRange request");
4676   rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
4677   rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
4678   pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
4679   pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
4680                                        +FRAME_LINE_HEIGHT (emacsframe));
4682   pt = [self convertPoint: pt toView: nil];
4683   pt = [[self window] convertBaseToScreen: pt];
4684   rect.origin = pt;
4685   return rect;
4688 - (NSInteger)conversationIdentifier
4690   return (NSInteger)self;
4693 /* TODO: below here not yet implemented correctly, but may not be needed */
4695 - (void)doCommandBySelector: (SEL)aSelector
4697   if (NS_KEYLOG) NSLog (@"Do command by selector: %@",
4698                        NSStringFromSelector (aSelector));
4700   if (aSelector == @selector (deleteBackward:))
4701     {
4702       /* happens when user backspaces over an ongoing composition:
4703          throw a 'delete' into the event queue */
4704       if (!emacs_event)
4705         return;
4706       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4707       emacs_event->code = 0xFF08;
4708       EV_TRAILER ((id)nil);
4709     }
4712 - (NSArray *)validAttributesForMarkedText
4714   static NSArray *arr = nil;
4715   if (arr == nil) arr = [NSArray new];
4716  /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
4717   return arr;
4720 - (NSRange)selectedRange
4722 if (NS_KEYLOG) NSLog (@"selectedRange request");
4723   return NSMakeRange (NSNotFound, 0);
4726 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
4728 if (NS_KEYLOG) NSLog (@"characterIndexForPoint request");
4729   return 0;
4732 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
4734   static NSAttributedString *str = nil;
4735   if (str == nil) str = [NSAttributedString new];
4736 if (NS_KEYLOG) NSLog (@"attributedSubstringFromRange request");
4737   return str;
4740 /* End <NSTextInput> impl. */
4741 /*****************************************************************************/
4744 /* This is what happens when the user presses a mouse button.  */
4745 - (void)mouseDown: (NSEvent *)theEvent
4747   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
4748   Lisp_Object window;
4750   NSTRACE (mouseDown);
4752   [self deleteWorkingText];
4754   if (!emacs_event)
4755     return;
4757   last_mouse_frame = emacsframe;
4758   /* appears to be needed to prevent spurious movement events generated on
4759      button clicks */
4760   last_mouse_frame->mouse_moved = 0;
4762   if ([theEvent type] == NSScrollWheel)
4763     {
4764       float delta = [theEvent deltaY];
4765       /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
4766       if (delta == 0)
4767         return;
4768       emacs_event->kind = WHEEL_EVENT;
4769       emacs_event->code = 0;
4770       emacs_event->modifiers = EV_MODIFIERS (theEvent) |
4771         ((delta > 0) ? up_modifier : down_modifier);
4772     }
4773   else
4774     {
4775       emacs_event->kind = MOUSE_CLICK_EVENT;
4776       emacs_event->code = EV_BUTTON (theEvent);
4777       emacs_event->modifiers = EV_MODIFIERS (theEvent)
4778                              | EV_UDMODIFIERS (theEvent);
4779     }
4780   XSETINT (emacs_event->x, lrint (p.x));
4781   XSETINT (emacs_event->y, lrint (p.y));
4782   EV_TRAILER (theEvent);
4786 - (void)rightMouseDown: (NSEvent *)theEvent
4788   NSTRACE (rightMouseDown);
4789   [self mouseDown: theEvent];
4793 - (void)otherMouseDown: (NSEvent *)theEvent
4795   NSTRACE (otherMouseDown);
4796   [self mouseDown: theEvent];
4800 - (void)mouseUp: (NSEvent *)theEvent
4802   NSTRACE (mouseUp);
4803   [self mouseDown: theEvent];
4807 - (void)rightMouseUp: (NSEvent *)theEvent
4809   NSTRACE (rightMouseUp);
4810   [self mouseDown: theEvent];
4814 - (void)otherMouseUp: (NSEvent *)theEvent
4816   NSTRACE (otherMouseUp);
4817   [self mouseDown: theEvent];
4821 - (void) scrollWheel: (NSEvent *)theEvent
4823   NSTRACE (scrollWheel);
4824   [self mouseDown: theEvent];
4828 /* Tell emacs the mouse has moved. */
4829 - (void)mouseMoved: (NSEvent *)e
4831   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4832   Lisp_Object frame;
4834 //  NSTRACE (mouseMoved);
4836   last_mouse_movement_time = EV_TIMESTAMP (e);
4837   last_mouse_motion_position
4838     = [self convertPoint: [e locationInWindow] fromView: nil];
4840   /* update any mouse face */
4841   if (dpyinfo->mouse_face_hidden)
4842     {
4843       dpyinfo->mouse_face_hidden = 0;
4844       clear_mouse_face (dpyinfo);
4845     }
4847   /* tooltip handling */
4848   previous_help_echo_string = help_echo_string;
4849   help_echo_string = Qnil;
4851   if (!note_mouse_movement (emacsframe, last_mouse_motion_position.x,
4852                             last_mouse_motion_position.y))
4853     help_echo_string = previous_help_echo_string;
4855   XSETFRAME (frame, emacsframe);
4856   if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
4857     {
4858       /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
4859          (note_mouse_highlight), which is called through the
4860          note_mouse_movement () call above */
4861       gen_help_event (help_echo_string, frame, help_echo_window,
4862                       help_echo_object, help_echo_pos);
4863     }
4864   else
4865     {
4866       help_echo_string = Qnil;
4867       gen_help_event (Qnil, frame, Qnil, Qnil, 0);
4868     }
4870   if (emacsframe->mouse_moved && send_appdefined)
4871     ns_send_appdefined (-1);
4875 - (void)mouseDragged: (NSEvent *)e
4877   NSTRACE (mouseDragged);
4878   [self mouseMoved: e];
4882 - (void)rightMouseDragged: (NSEvent *)e
4884   NSTRACE (rightMouseDragged);
4885   [self mouseMoved: e];
4889 - (void)otherMouseDragged: (NSEvent *)e
4891   NSTRACE (otherMouseDragged);
4892   [self mouseMoved: e];
4896 - (BOOL)windowShouldClose: (id)sender
4898   NSEvent *e =[[self window] currentEvent];
4900   NSTRACE (windowShouldClose);
4901   windowClosing = YES;
4902   if (!emacs_event)
4903     return NO;
4904   emacs_event->kind = DELETE_WINDOW_EVENT;
4905   emacs_event->modifiers = 0;
4906   emacs_event->code = 0;
4907   EV_TRAILER (e);
4908   /* Don't close this window, let this be done from lisp code.  */
4909   return NO;
4913 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
4914 /* normalize frame to gridded text size */
4916   NSTRACE (windowWillResize);
4917 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
4919   cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe,
4920 #ifdef NS_IMPL_GNUSTEP
4921                                         frameSize.width + 3);
4922 #else
4923                                         frameSize.width);
4924 #endif
4925   if (cols < MINWIDTH)
4926     cols = MINWIDTH;
4927   frameSize.width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (emacsframe, cols);
4929   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, frameSize.height
4930 #ifdef NS_IMPL_GNUSTEP
4931       - FRAME_NS_TITLEBAR_HEIGHT (emacsframe) + 3
4932         - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
4933 #else
4934       - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
4935         - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
4936 #endif
4937   if (rows < MINHEIGHT)
4938     rows = MINHEIGHT;
4939   frameSize.height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows)
4940                        + FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
4941                        + FRAME_NS_TOOLBAR_HEIGHT (emacsframe);
4942 #ifdef NS_IMPL_COCOA
4943   {
4944     /* this sets window title to have size in it; the wm does this under GS */
4945     NSRect r = [[self window] frame];
4946     if (r.size.height == frameSize.height && r.size.width == frameSize.width)
4947       {
4948         if (old_title != 0)
4949           {
4950             xfree (old_title);
4951             old_title = 0;
4952           }
4953       }
4954     else
4955       {
4956         char *size_title;
4957         NSWindow *window = [self window];
4958         if (old_title == 0)
4959           {
4960             const char *t = [[[self window] title] UTF8String];
4961             char *pos = strstr (t, "  â€”  ");
4962             if (pos)
4963               *pos = '\0';
4964             old_title = (char *) xmalloc (strlen (t) + 1);
4965             strcpy (old_title, t);
4966           }
4967         size_title = xmalloc (strlen (old_title) + 40);
4968         sprintf (size_title, "%s  â€”  (%d x %d)", old_title, cols, rows);
4969         [window setTitle: [NSString stringWithUTF8String: size_title]];
4970         [window display];
4971         xfree (size_title);
4972       }
4973   }
4974 #endif /* NS_IMPL_COCOA */
4975 /*fprintf (stderr,"    ...size became %.0f x %.0f  (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
4977   return frameSize;
4981 - (void)windowDidResize: (NSNotification *)notification
4983   NSWindow *theWindow = [notification object];
4985 #ifdef NS_IMPL_GNUSTEP
4986    /* in GNUstep, at least currently, it's possible to get a didResize
4987       without getting a willResize.. therefore we need to act as if we got
4988       the willResize now */
4989   NSSize sz = [theWindow frame].size;
4990   sz = [self windowWillResize: theWindow toSize: sz];
4991 #endif /* NS_IMPL_GNUSTEP */
4993   NSTRACE (windowDidResize);
4994 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
4996 #ifdef NS_IMPL_COCOA
4997   if (old_title != 0)
4998     {
4999       xfree (old_title);
5000       old_title = 0;
5001     }
5002 #endif /* NS_IMPL_COCOA */
5004   if (cols > 0 && rows > 0)
5005     x_set_window_size (emacsframe, 0, cols, rows);
5007   ns_send_appdefined (-1);
5009   /* The following line causes a crash on GNUstep.  Adrian Robert
5010      says he doesn't remember why he added this line, but removing it
5011      doesn't seem to cause problems on OSX, either.  */
5012 #if 0
5013   [NSApp stopModal];
5014 #endif
5018 - (void)windowDidBecomeKey: (NSNotification *)notification
5019 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5021   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5022   struct frame *old_focus = dpyinfo->x_focus_frame;
5024   NSTRACE (windowDidBecomeKey);
5026   if (emacsframe != old_focus)
5027     dpyinfo->x_focus_frame = emacsframe;
5029   ns_frame_rehighlight (emacsframe);
5031   if (emacs_event)
5032     {
5033       emacs_event->kind = FOCUS_IN_EVENT;
5034       EV_TRAILER ((id)nil);
5035     }
5039 - (void)windowDidResignKey: (NSNotification *)notification
5040 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5042   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5043   NSTRACE (windowDidResignKey);
5045   if (dpyinfo->x_focus_frame == emacsframe)
5046     dpyinfo->x_focus_frame = 0;
5048   ns_frame_rehighlight (emacsframe);
5050   /* FIXME: for some reason needed on second and subsequent clicks away
5051             from sole-frame Emacs to get hollow box to show */
5052   if (!windowClosing && [[self window] isVisible] == YES)
5053     {
5054       x_update_cursor (emacsframe, 1);
5055       x_set_frame_alpha (emacsframe);
5056     }
5058   if (emacs_event)
5059     {
5060       [self deleteWorkingText];
5061       emacs_event->kind = FOCUS_IN_EVENT;
5062       EV_TRAILER ((id)nil);
5063     }
5067 - (void)windowWillMiniaturize: sender
5069   NSTRACE (windowWillMiniaturize);
5073 - (BOOL)isFlipped
5075   return YES;
5079 - (BOOL)isOpaque
5081   return NO;
5085 - initFrameFromEmacs: (struct frame *)f
5087   NSRect r, wr;
5088   Lisp_Object tem;
5089   NSWindow *win;
5090   NSButton *toggleButton;
5091   int vbextra = NS_SCROLL_BAR_WIDTH (f);
5092   NSSize sz;
5093   NSColor *col;
5094   NSString *name;
5096   NSTRACE (initFrameFromEmacs);
5098   windowClosing = NO;
5099   processingCompose = NO;
5100   scrollbarsNeedingUpdate = 0;
5102 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
5104   r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
5105                  FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
5106   [self initWithFrame: r];
5108   FRAME_NS_VIEW (f) = self;
5109   emacsframe = f;
5110   old_title = 0;
5112   win = [[EmacsWindow alloc]
5113             initWithContentRect: r
5114                       styleMask: (NSResizableWindowMask |
5115                                   NSMiniaturizableWindowMask |
5116                                   NSClosableWindowMask)
5117                         backing: NSBackingStoreBuffered
5118                           defer: YES];
5120   wr = [win frame];
5121   f->border_width = wr.size.width - r.size.width;
5122   FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
5124   [win setAcceptsMouseMovedEvents: YES];
5125   [win setDelegate: self];
5126   [win useOptimizedDrawing: YES];
5128   sz.width = FRAME_COLUMN_WIDTH (f);
5129   sz.height = FRAME_LINE_HEIGHT (f);
5130   [win setResizeIncrements: sz];
5132   [[win contentView] addSubview: self];
5134   if (ns_drag_types)
5135     [self registerForDraggedTypes: ns_drag_types];
5137   tem = f->name;
5138   name = [NSString stringWithUTF8String:
5139                    NILP (tem) ? (unsigned char *)"Emacs" : SDATA (tem)];
5140   [win setTitle: name];
5142   /* toolbar support */
5143   toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
5144                          [NSString stringWithFormat: @"Emacs Frame %d",
5145                                    ns_window_num]];
5146   [win setToolbar: toolbar];
5147   [toolbar setVisible: NO];
5148 #ifdef NS_IMPL_COCOA
5149   toggleButton = [win standardWindowButton: NSWindowToolbarButton];
5150   [toggleButton setTarget: self];
5151   [toggleButton setAction: @selector (toggleToolbar: )];
5152 #endif
5153   FRAME_NS_TOOLBAR_HEIGHT (f) = 0;
5155   tem = f->icon_name;
5156   if (!NILP (tem))
5157     [win setMiniwindowTitle:
5158            [NSString stringWithUTF8String: SDATA (tem)]];
5160   {
5161     NSScreen *screen = [win screen];
5163     if (screen != 0)
5164       [win setFrameTopLeftPoint: NSMakePoint
5165            (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
5166             IN_BOUND (-SCREENMAX,
5167                      [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
5168   }
5170   [win makeFirstResponder: self];
5172   col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5173                                   (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
5174   [win setBackgroundColor: col];
5175   if ([col alphaComponent] != 1.0)
5176     [win setOpaque: NO];
5178   [self allocateGState];
5180   ns_window_num++;
5181   return self;
5185 - (void)windowDidMove: sender
5187   NSWindow *win = [self window];
5188   NSRect r = [win frame];
5189   NSScreen *screen = [win screen];
5190   NSRect sr = [screen frame];
5192   NSTRACE (windowDidMove);
5194   if (!emacsframe->output_data.ns)
5195     return;
5196   if (screen != nil)
5197     {
5198       emacsframe->left_pos = r.origin.x; /* - sr.origin.x; */
5199       emacsframe->top_pos = sr.size.height -
5200         (r.origin.y + r.size.height); /* + sr.origin.y; */
5201     }
5204 #ifdef NS_IMPL_COCOA
5205 /* if we don't do this manually, the window will resize but not move */
5206 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
5208   [[self window] setFrame: newFrame display: NO];
5209   return YES;
5211 #endif
5213 /* Implement this to control size of frame on zoom.
5214 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
5215                         defaultFrame:(NSRect)defaultFrame; */
5218 - (void)windowDidDeminiaturize: sender
5220   NSTRACE (windowDidDeminiaturize);
5221   if (!emacsframe->output_data.ns)
5222     return;
5223   emacsframe->async_visible   = 1;
5224   emacsframe->async_iconified = 0;
5225   windows_or_buffers_changed++;
5227   if (emacs_event)
5228     {
5229       emacs_event->kind = ICONIFY_EVENT;
5230       EV_TRAILER ((id)nil);
5231     }
5235 - (void)windowDidExpose: sender
5237   NSTRACE (windowDidExpose);
5238   if (!emacsframe->output_data.ns)
5239     return;
5240   emacsframe->async_visible = 1;
5241   SET_FRAME_GARBAGED (emacsframe);
5243   if (send_appdefined)
5244     ns_send_appdefined (-1);
5248 - (void)windowDidMiniaturize: sender
5250   NSTRACE (windowDidMiniaturize);
5251   if (!emacsframe->output_data.ns)
5252     return;
5254   emacsframe->async_iconified = 1;
5256   if (emacs_event)
5257     {
5258       emacs_event->kind = ICONIFY_EVENT;
5259       EV_TRAILER ((id)nil);
5260     }
5264 - (void)mouseEntered: (NSEvent *)theEvent
5266   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5267   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5268   NSTRACE (mouseEntered);
5270   last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5274 - (void)mouseExited: (NSEvent *)theEvent
5276   NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5277   NSRect r;
5278   struct ns_display_info *dpyinfo
5279     = emacsframe ? FRAME_NS_DISPLAY_INFO (emacsframe) : NULL;
5281   NSTRACE (mouseExited);
5283   if (dpyinfo || !emacsframe)
5284     return;
5286   last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5288   if (emacsframe == dpyinfo->mouse_face_mouse_frame)
5289     {
5290       clear_mouse_face (dpyinfo);
5291       dpyinfo->mouse_face_mouse_frame = 0;
5292     }
5296 - menuDown: sender
5298   NSTRACE (menuDown);
5299   if (context_menu_value == -1)
5300     context_menu_value = [sender tag];
5301   else
5302     find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
5303                                   emacsframe->menu_bar_vector,
5304                                   (void *)[sender tag]);
5305   ns_send_appdefined (-1);
5306   return self;
5310 - (EmacsToolbar *)toolbar
5312   return toolbar;
5316 /* this gets called on toolbar button click */
5317 - toolbarClicked: (id)item
5319   NSEvent *theEvent;
5320   int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
5322   NSTRACE (toolbarClicked);
5324   if (!emacs_event)
5325     return self;
5327   /* send first event (for some reason two needed) */
5328   theEvent =[[self window] currentEvent];
5329   emacs_event->kind = TOOL_BAR_EVENT;
5330   XSETFRAME (emacs_event->arg, emacsframe);
5331   EV_TRAILER (theEvent);
5333   emacs_event->kind = TOOL_BAR_EVENT;
5334 /*   XSETINT (emacs_event->code, 0); */
5335   emacs_event->arg = AREF (emacsframe->tool_bar_items,
5336                           idx + TOOL_BAR_ITEM_KEY);
5337   emacs_event->modifiers = EV_MODIFIERS (theEvent);
5338   EV_TRAILER (theEvent);
5339   return self;
5343 - toggleToolbar: (id)sender
5345   Lisp_Object lispFrame;
5346   XSETFRAME (lispFrame, emacsframe);
5347   Feval (Fcons (intern ("ns-toggle-toolbar"), Fcons (lispFrame, Qnil)));
5348   SET_FRAME_GARBAGED (emacsframe);
5349   ns_send_appdefined (-1);
5353 - (void)drawRect: (NSRect)rect
5355   int x = NSMinX (rect), y = NSMinY (rect);
5356   int width = NSWidth (rect), height = NSHeight (rect);
5358   NSTRACE (drawRect);
5360   if (!emacsframe || !emacsframe->output_data.ns)
5361     return;
5363   if (!ns_in_resize)
5364     ns_clear_frame_area (emacsframe, x, y, width, height);
5365   expose_frame (emacsframe, x, y, width, height);
5367   emacsframe->async_visible = 1;
5368   emacsframe->async_iconified = 0;
5370 /*    SET_FRAME_GARBAGED (emacsframe);
5371       ns_send_appdefined (-1); */
5375 /* NSDraggingDestination protocol methods.  Actually this is not really a
5376    protocol, but a category of Object.  O well...  */
5378 -(unsigned int) draggingEntered: (id <NSDraggingInfo>) sender
5380   NSTRACE (draggingEntered);
5381   return NSDragOperationGeneric;
5385 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
5387   return YES;
5391 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
5393   id pb;
5394   int x, y;
5395   NSString *type;
5396   NSEvent *theEvent = [[self window] currentEvent];
5397   NSPoint position;
5399   NSTRACE (performDragOperation);
5401   if (!emacs_event)
5402     return;
5404   position = [self convertPoint: [sender draggingLocation] fromView: nil];
5405   x = lrint (position.x);  y = lrint (position.y);
5407   pb = [sender draggingPasteboard];
5408   type = [pb availableTypeFromArray: ns_drag_types];
5409   if (type == 0)
5410     {
5411       return NO;
5412     }
5413   else if ([type isEqualToString: NSFilenamesPboardType])
5414     {
5415       NSArray *files;
5416       NSEnumerator *fenum;
5417       NSString *file;
5419       if (!(files = [pb propertyListForType: type]))
5420         return NO;
5422       fenum = [files objectEnumerator];
5423       while ( (file = [fenum nextObject]) )
5424         {
5425           emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5426           emacs_event->code = KEY_NS_DRAG_FILE;
5427           XSETINT (emacs_event->x, x);
5428           XSETINT (emacs_event->y, y);
5429           ns_input_file = append2 (ns_input_file,
5430                                    build_string ([file UTF8String]));
5431           emacs_event->modifiers = EV_MODIFIERS (theEvent);
5432           EV_TRAILER (theEvent);
5433         }
5434       return YES;
5435     }
5436   else if ([type isEqualToString: NSURLPboardType])
5437     {
5438       NSString *file;
5439       NSURL *fileURL;
5441       if (!(fileURL = [NSURL URLFromPasteboard: pb]) ||
5442           [fileURL isFileURL] == NO)
5443         return NO;
5445       file = [fileURL path];
5446       emacs_event->kind = NON_ASCII_KEYSTROKE_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, build_string ([file UTF8String]));
5451       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5452       EV_TRAILER (theEvent);
5453       return YES;
5454     }
5455   else if ([type isEqualToString: NSStringPboardType]
5456            || [type isEqualToString: NSTabularTextPboardType])
5457     {
5458       NSString *data;
5460       if (! (data = [pb stringForType: type]))
5461         return NO;
5463       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5464       emacs_event->code = KEY_NS_DRAG_TEXT;
5465       XSETINT (emacs_event->x, x);
5466       XSETINT (emacs_event->y, y);
5467       ns_input_text = build_string ([data UTF8String]);
5468       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5469       EV_TRAILER (theEvent);
5470       return YES;
5471     }
5472   else if ([type isEqualToString: NSColorPboardType])
5473     {
5474       NSColor *c = [NSColor colorFromPasteboard: pb];
5475       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5476       emacs_event->code = KEY_NS_DRAG_COLOR;
5477       XSETINT (emacs_event->x, x);
5478       XSETINT (emacs_event->y, y);
5479       ns_input_color = ns_color_to_lisp (c);
5480       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5481       EV_TRAILER (theEvent);
5482       return YES;
5483     }
5484   else if ([type isEqualToString: NSFontPboardType])
5485     {
5486       /* impl based on GNUstep NSTextView.m */
5487       NSData *data = [pb dataForType: NSFontPboardType];
5488       NSDictionary *dict = [NSUnarchiver unarchiveObjectWithData: data];
5489       NSFont *font = [dict objectForKey: NSFontAttributeName];
5490       char fontSize[10];
5492       if (font == nil)
5493         return NO;
5495       emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5496       emacs_event->code = KEY_NS_CHANGE_FONT;
5497       XSETINT (emacs_event->x, x);
5498       XSETINT (emacs_event->y, y);
5499       ns_input_font = build_string ([[font fontName] UTF8String]);
5500       snprintf (fontSize, 10, "%f", [font pointSize]);
5501       ns_input_fontsize = build_string (fontSize);
5502       emacs_event->modifiers = EV_MODIFIERS (theEvent);
5503       EV_TRAILER (theEvent);
5504       return YES;
5505     }
5506   else
5507     {
5508       error ("Invalid data type in dragging pasteboard.");
5509       return NO;
5510     }
5514 - validRequestorForSendType: (NSString *)typeSent
5515                  returnType: (NSString *)typeReturned
5517   NSTRACE (validRequestorForSendType);
5518   if ([ns_send_types indexOfObjectIdenticalTo: typeSent] != NSNotFound &&
5519       [ns_return_types indexOfObjectIdenticalTo: typeSent] != NSNotFound)
5520     return self;
5522   return [super validRequestorForSendType: typeSent
5523                                returnType: typeReturned];
5527 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
5528    (gives a miniaturized version of the window); currently we use the latter for
5529    frames whose active buffer doesn't correspond to any file
5530    (e.g., '*scratch*') */
5531 - setMiniwindowImage: (BOOL) setMini
5533   id image = [[self window] miniwindowImage];
5534   NSTRACE (setMiniwindowImage);
5536   /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
5537      about "AppleDockIconEnabled" notwithstanding, however the set message
5538      below has its effect nonetheless. */
5539   if (image != emacsframe->output_data.ns->miniimage)
5540     {
5541       if (image && [image isKindOfClass: [EmacsImage class]])
5542         [image release];
5543       [[self window] setMiniwindowImage:
5544                        setMini ? emacsframe->output_data.ns->miniimage : nil];
5545     }
5547   return self;
5551 - (void) setRows: (int) r andColumns: (int) c
5553   rows = r;
5554   cols = c;
5557 @end  /* EmacsView */
5561 /* ==========================================================================
5563     EmacsWindow implementation
5565    ========================================================================== */
5567 @implementation EmacsWindow
5569 /* called only on resize clicks by special case in EmacsApp-sendEvent */
5570 - (void)mouseDown: (NSEvent *)theEvent
5572   if (ns_in_resize)
5573     {
5574       NSSize size = [[theEvent window] frame].size;
5575       grabOffset = [theEvent locationInWindow];
5576       grabOffset.x = size.width - grabOffset.x;
5577     }
5578   else
5579     [super mouseDown: theEvent];
5583 /* stop resizing */
5584 - (void)mouseUp: (NSEvent *)theEvent
5586   if (ns_in_resize)
5587     {
5588       struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
5589       ns_in_resize = NO;
5590       ns_set_name_as_filename (f);
5591       [self display];
5592       ns_send_appdefined (-1);
5593     }
5594   else
5595     [super mouseUp: theEvent];
5599 /* send resize events */
5600 - (void)mouseDragged: (NSEvent *)theEvent
5602   if (ns_in_resize)
5603     {
5604       NSPoint p = [theEvent locationInWindow];
5605       NSSize size, vettedSize, origSize = [self frame].size;
5607       size.width = p.x + grabOffset.x;
5608       size.height = origSize.height - p.y + grabOffset.y;
5610       if (size.width == origSize.width && size.height == origSize.height)
5611         return;
5613       vettedSize = [[self delegate] windowWillResize: self toSize: size];
5614       if (vettedSize.width != size.width || vettedSize.height != size.height)
5615         {
5616           [[NSNotificationCenter defaultCenter]
5617             postNotificationName: NSWindowDidResizeNotification
5618                           object: self];
5619         }
5620     }
5621   else
5622     [super mouseDragged: theEvent];
5625 @end /* EmacsWindow */
5628 /* ==========================================================================
5630     EmacsScroller implementation
5632    ========================================================================== */
5635 @implementation EmacsScroller
5637 /* for repeat button push */
5638 #define SCROLL_BAR_FIRST_DELAY 0.5
5639 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
5641 + (float) scrollerWidth
5643   /* TODO: if we want to allow variable widths, this is the place to do it,
5644            however neither GNUstep nor Cocoa support it very well */
5645   return [NSScroller scrollerWidth];
5649 - initFrame: (NSRect )r window: (Lisp_Object)nwin
5651   NSTRACE (EmacsScroller_initFrame);
5653   r.size.width = [EmacsScroller scrollerWidth];
5654   [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
5655   [self setContinuous: YES];
5656   [self setEnabled: YES];
5658   /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
5659      locked against the right, top and bottom edges. */
5660   [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
5662   win = nwin;
5663   condemned = NO;
5664   pixel_height = NSHeight (r);
5665   min_portion = 20 / pixel_height;
5667   frame = XFRAME (XWINDOW (win)->frame);
5668   if (FRAME_LIVE_P (frame))
5669     {
5670       int i;
5671       EmacsView *view = FRAME_NS_VIEW (frame);
5672       NSView *sview = [[view window] contentView];
5673       NSArray *subs = [sview subviews];
5675       /* disable optimization stopping redraw of other scrollbars */
5676       view->scrollbarsNeedingUpdate = 0;
5677       for (i =[subs count]-1; i >= 0; i--)
5678         if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
5679           view->scrollbarsNeedingUpdate++;
5680       [sview addSubview: self];
5681     }
5683 /*  [self setFrame: r]; */
5685   return self;
5689 - (void)setFrame: (NSRect)newRect
5691   NSTRACE (EmacsScroller_setFrame);
5692 /*  BLOCK_INPUT; */
5693   pixel_height = NSHeight (newRect);
5694   min_portion = 20 / pixel_height;
5695   [super setFrame: newRect];
5696   [self display];
5697 /*  UNBLOCK_INPUT; */
5701 - (void)dealloc
5703   NSTRACE (EmacsScroller_dealloc);
5704   if (!NILP (win))
5705     XWINDOW (win)->vertical_scroll_bar = Qnil;
5706   [super dealloc];
5710 - condemn
5712   NSTRACE (condemn);
5713   condemned =YES;
5714   return self;
5718 - reprieve
5720   NSTRACE (reprieve);
5721   condemned =NO;
5722   return self;
5726 - judge
5728   NSTRACE (judge);
5729   if (condemned)
5730     {
5731       BLOCK_INPUT;
5732       /* ensure other scrollbar updates after deletion */
5733       EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
5734       if (view != nil)
5735         view->scrollbarsNeedingUpdate++;
5736       [self removeFromSuperview];
5737       [self release];
5738       UNBLOCK_INPUT;
5739     }
5740   return self;
5744 - (void)resetCursorRects
5746   NSRect visible = [self visibleRect];
5747   NSTRACE (resetCursorRects);
5749   if (!NSIsEmptyRect (visible))
5750     [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
5751   [[NSCursor arrowCursor] setOnMouseEntered: YES];
5755 - (int) checkSamePosition: (int) position portion: (int) portion
5756                     whole: (int) whole
5758   return em_position ==position && em_portion ==portion && em_whole ==whole
5759     && portion != whole; /* needed for resize empty buf */
5763 - setPosition: (int)position portion: (int)portion whole: (int)whole
5765   NSTRACE (setPosition);
5767   em_position = position;
5768   em_portion = portion;
5769   em_whole = whole;
5771   if (portion >= whole)
5772     [self setFloatValue: 0.0 knobProportion: 1.0];
5773   else
5774     {
5775       float pos, por;
5776       portion = max ((float)whole*min_portion/pixel_height, portion);
5777       pos = (float)position / (whole - portion);
5778       por = (float)portion/whole;
5779       [self setFloatValue: pos knobProportion: por];
5780     }
5781 #ifdef NS_IMPL_GNUSTEP
5782   [self display];
5783 #endif
5784   return self;
5787 /* FIXME: unused at moment (see ns_mouse_position) at the moment because
5788      drag events will go directly to the EmacsScroller.  Leaving in for now. */
5789 -(void)getMouseMotionPart: (int *)part window: (Lisp_Object *)window
5790                         x: (Lisp_Object *)x y: ( Lisp_Object *)y
5792   *part = last_hit_part;
5793   *window = win;
5794   XSETINT (*y, pixel_height);
5795   if ([self floatValue] > 0.999)
5796     XSETINT (*x, pixel_height);
5797   else
5798     XSETINT (*x, pixel_height * [self floatValue]);
5802 /* set up emacs_event */
5803 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
5805   if (!emacs_event)
5806     return;
5808   emacs_event->part = last_hit_part;
5809   emacs_event->code = 0;
5810   emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
5811   emacs_event->frame_or_window = win;
5812   emacs_event->timestamp = EV_TIMESTAMP (e);
5813   emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
5814   emacs_event->arg = Qnil;
5815   XSETINT (emacs_event->x, loc * pixel_height);
5816   XSETINT (emacs_event->y, pixel_height-20);
5818   n_emacs_events_pending++;
5819   kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
5820   EVENT_INIT (*emacs_event);
5821   ns_send_appdefined (-1);
5825 /* called manually thru timer to implement repeated button action w/hold-down */
5826 - repeatScroll: (NSTimer *)scrollEntry
5828   NSEvent *e = [[self window] currentEvent];
5829   NSPoint p =  [[self window] mouseLocationOutsideOfEventStream];
5830   BOOL inKnob = [self testPart: p] == NSScrollerKnob;
5832   /* clear timer if need be */
5833   if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
5834     {
5835         [scroll_repeat_entry invalidate];
5836         [scroll_repeat_entry release];
5837         scroll_repeat_entry = nil;
5839         if (inKnob)
5840           return self;
5842         scroll_repeat_entry
5843           = [[NSTimer scheduledTimerWithTimeInterval:
5844                         SCROLL_BAR_CONTINUOUS_DELAY
5845                                             target: self
5846                                           selector: @selector (repeatScroll:)
5847                                           userInfo: 0
5848                                            repeats: YES]
5849               retain];
5850     }
5852   [self sendScrollEventAtLoc: 0 fromEvent: e];
5853   return self;
5857 /* Asynchronous mouse tracking for scroller.  This allows us to dispatch
5858    mouseDragged events without going into a modal loop. */
5859 - (void)mouseDown: (NSEvent *)e
5861   NSRect sr, kr;
5862   /* hitPart is only updated AFTER event is passed on */
5863   NSScrollerPart part = [self testPart: [e locationInWindow]];
5864   double inc = 0.0, loc, kloc, pos;
5865   int edge = 0;
5867   NSTRACE (EmacsScroller_mouseDown);
5869   switch (part)
5870     {
5871     case NSScrollerDecrementPage:
5872         last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
5873     case NSScrollerIncrementPage:
5874         last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
5875     case NSScrollerDecrementLine:
5876       last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
5877     case NSScrollerIncrementLine:
5878       last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
5879     case NSScrollerKnob:
5880       last_hit_part = scroll_bar_handle; break;
5881     case NSScrollerKnobSlot:  /* GNUstep-only */
5882       last_hit_part = scroll_bar_move_ratio; break;
5883     default:  /* NSScrollerNoPart? */
5884       fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %d\n", part);
5885       return;
5886     }
5888   if (inc != 0.0)
5889     {
5890       pos = 0;      /* ignored */
5892       /* set a timer to repeat, as we can't let superclass do this modally */
5893       scroll_repeat_entry
5894         = [[NSTimer scheduledTimerWithTimeInterval: 0.5
5895                                             target: self
5896                                           selector: @selector (repeatScroll:)
5897                                           userInfo: 0
5898                                            repeats: YES]
5899             retain];
5900     }
5901   else
5902     {
5903       /* handle, or on GNUstep possibly slot */
5904       NSEvent *fake_event;
5906       /* compute float loc in slot and mouse offset on knob */
5907       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
5908                       toView: nil];
5909       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
5910       if (loc <= 0.0)
5911         {
5912           loc = 0.0;
5913           edge = -1;
5914         }
5915       else if (loc >= NSHeight (sr))
5916         {
5917           loc = NSHeight (sr);
5918           edge = 1;
5919         }
5921       if (edge)
5922         kloc = 0.5 * edge;
5923       else
5924         {
5925           kr = [self convertRect: [self rectForPart: NSScrollerKnob]
5926                           toView: nil];
5927           kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
5928         }
5929       last_mouse_offset = kloc;
5931       /* if knob, tell emacs a location offset by knob pos
5932          (to indicate top of handle) */
5933       if (part == NSScrollerKnob)
5934           pos = (loc - last_mouse_offset) / NSHeight (sr);
5935       else
5936         /* else this is a slot click on GNUstep: go straight there */
5937         pos = loc / NSHeight (sr);
5939       /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
5940       fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
5941                                       location: [e locationInWindow]
5942                                  modifierFlags: [e modifierFlags]
5943                                      timestamp: [e timestamp]
5944                                   windowNumber: [e windowNumber]
5945                                        context: [e context]
5946                                    eventNumber: [e eventNumber]
5947                                     clickCount: [e clickCount]
5948                                       pressure: [e pressure]];
5949       [super mouseUp: fake_event];
5950     }
5952   if (part != NSScrollerKnob)
5953     [self sendScrollEventAtLoc: pos fromEvent: e];
5957 /* Called as we manually track scroller drags, rather than superclass. */
5958 - (void)mouseDragged: (NSEvent *)e
5960     NSRect sr;
5961     double loc, pos;
5962     int edge = 0;
5964     NSTRACE (EmacsScroller_mouseDragged);
5966       sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
5967                       toView: nil];
5968       loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
5970       if (loc <= 0.0)
5971         {
5972           loc = 0.0;
5973           edge = -1;
5974         }
5975       else if (loc >= NSHeight (sr) + last_mouse_offset)
5976         {
5977           loc = NSHeight (sr) + last_mouse_offset;
5978           edge = 1;
5979         }
5981       pos = /*(edge ? loc :*/ (loc - last_mouse_offset) / NSHeight (sr);
5982       [self sendScrollEventAtLoc: pos fromEvent: e];
5986 - (void)mouseUp: (NSEvent *)e
5988   if (scroll_repeat_entry)
5989     {
5990       [scroll_repeat_entry invalidate];
5991       [scroll_repeat_entry release];
5992       scroll_repeat_entry = nil;
5993     }
5994   last_hit_part = 0;
5998 /* treat scrollwheel events in the bar as though they were in the main window */
5999 - (void) scrollWheel: (NSEvent *)theEvent
6001   EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
6002   [view mouseDown: theEvent];
6005 @end  /* EmacsScroller */
6009 /* ==========================================================================
6011     EmacsPrefsController implementation
6013    ========================================================================== */
6016 @implementation EmacsPrefsController
6018 /* in Tiger+, can just do [popup selectItemWithTag: tag]; */
6019 static void selectItemWithTag (NSPopUpButton *popup, int tag)
6021   NSEnumerator *items = [[popup itemArray] objectEnumerator];
6022   NSMenuItem *item;
6023   while (item = [items nextObject])
6024     {
6025       if ([item tag] == tag)
6026         {
6027           [popup selectItem: item];
6028           return;
6029         }
6030     }
6033 - init
6035   [NSBundle loadNibNamed: @"preferences" owner: self];
6036   return self;
6040 - (void) showForFrame: (struct frame *)f
6042   frame = f;
6043   [self setPanelFromValues];
6044   [prefsWindow makeKeyAndOrderFront: self];
6045   [prefsWindow display];
6049 - (void) setPanelFromValues
6051   int cursorType
6052     = ns_lisp_to_cursor_type (get_frame_param (frame, Qcursor_type));
6053   prevExpandSpace = XFLOATINT (ns_expand_space);
6055 #ifdef NS_IMPL_COCOA
6056   prevUseHighlightColor = ns_use_system_highlight_color;
6057 #endif
6059   [expandSpaceSlider setFloatValue: prevExpandSpace];
6060   [cursorTypeMatrix selectCellWithTag: (cursorType == FILLED_BOX_CURSOR ? 1 :
6061                                         (cursorType == BAR_CURSOR ? 2 :
6062                                          (cursorType == HBAR_CURSOR ? 3 : 4)))];
6063   selectItemWithTag (alternateModMenu,
6064                      parse_solitary_modifier (ns_alternate_modifier));
6065   selectItemWithTag (commandModMenu,
6066                      parse_solitary_modifier (ns_command_modifier));
6067 #ifdef NS_IMPL_COCOA
6068   selectItemWithTag (controlModMenu,
6069                      parse_solitary_modifier (ns_control_modifier));
6070   selectItemWithTag (functionModMenu,
6071                      parse_solitary_modifier (ns_function_modifier));
6072   [smoothFontsCheck setState: (NILP (ns_antialias_text) ? NO : YES)];
6073   [useQuickdrawCheck setState: (NILP (ns_use_qd_smoothing) ? NO : YES)];
6074   [useSysHiliteCheck setState: (NILP (prevUseHighlightColor) ? NO : YES)];
6075 #endif
6079 - (void) setValuesFromPanel
6081   int altTag = [[alternateModMenu selectedItem] tag];
6082   int cmdTag = [[commandModMenu selectedItem] tag];
6083 #ifdef NS_IMPL_COCOA
6084   int ctrlTag = [[controlModMenu selectedItem] tag];
6085   int fnTag = [[functionModMenu selectedItem] tag];
6086 #endif
6087   float expandSpace = [expandSpaceSlider floatValue];
6088   int cursorTag = [[cursorTypeMatrix selectedCell] tag];
6089   Lisp_Object cursor_type = ns_cursor_type_to_lisp
6090        ( cursorTag == 1 ? FILLED_BOX_CURSOR
6091        : cursorTag == 2 ? BAR_CURSOR
6092        : cursorTag == 3 ? HBAR_CURSOR : HOLLOW_BOX_CURSOR);
6094   if (expandSpace != prevExpandSpace)
6095     {
6096       ns_expand_space = make_float (expandSpace);
6097       /* TODO: more needed: store needed metrics in nsfont_info, update
6098          frame default font max_bounds and fontp, recompute faces */
6099 /*         FRAME_LINE_HEIGHT (frame) *= (expandSpace / prevExpandSpace);
6100            x_set_window_size (frame, 0, frame->text_cols, frame->text_lines); */
6101       prevExpandSpace = expandSpace;
6102     }
6104   store_frame_param (frame, Qcursor_type, cursor_type);
6105   x_set_cursor_type (frame, cursor_type, Qnil);  /* FIXME: do only if changed */
6107   ns_alternate_modifier = ns_mod_to_lisp (altTag);
6108   ns_command_modifier = ns_mod_to_lisp (cmdTag);
6109 #ifdef NS_IMPL_COCOA
6110   ns_control_modifier = ns_mod_to_lisp (ctrlTag);
6111   ns_function_modifier = ns_mod_to_lisp (fnTag);
6112   ns_antialias_text = [smoothFontsCheck state] ? Qt : Qnil;
6113   ns_use_qd_smoothing = [useQuickdrawCheck state] ? Qt : Qnil;
6114   ns_use_system_highlight_color = [useSysHiliteCheck state] ? Qt : Qnil;
6115   if (! EQ (ns_use_system_highlight_color, prevUseHighlightColor))
6116     {
6117       prevUseHighlightColor = ns_use_system_highlight_color;
6118       if (EQ (ns_use_system_highlight_color, Qt))
6119         {
6120           ns_selection_color = [[NSUserDefaults standardUserDefaults]
6121                                  stringForKey: @"AppleHighlightColor"];
6122           if (ns_selection_color == nil)
6123             ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
6124         }
6125       else
6126         ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
6127     }
6128 #endif /* NS_IMPL_COCOA */
6129   Fcall_interactively (intern ("ns-save-preferences"), Qnil, Qnil);
6133 /* buttons */
6134 - (IBAction)cancel: (id)sender
6136   [prefsWindow close];
6140 - (IBAction)ok: (id)sender
6142   [self setValuesFromPanel];
6143   [prefsWindow close];
6147 - (IBAction)resetToDefaults: (id)sender
6149   ns_set_default_prefs ();
6150   [self setPanelFromValues];
6154 - (IBAction)runHelp: (id)sender
6156   Feval (Fcons (intern ("info"),
6157               Fcons (build_string ("(ns-emacs)Preferences Panel"), Qnil)));
6158   SET_FRAME_GARBAGED (frame);
6159   ns_send_appdefined (-1);
6163 - (IBAction)setColors: (id)sender
6165   Lisp_Object lispFrame;
6166   XSETFRAME (lispFrame, frame);
6167   Fns_popup_color_panel (lispFrame);
6171 - (IBAction)setDefaultFont: (id)sender
6173   Lisp_Object lispFrame;
6174   XSETFRAME (lispFrame, frame);
6175   Fns_popup_font_panel (lispFrame);
6178 @end  /* EmacsPrefsController */
6183 /* ==========================================================================
6185    Font-related functions; these used to be in nsfaces.m
6186    The XLFD functions (115 lines) are an abomination that should be removed.
6188    ========================================================================== */
6191 Lisp_Object
6192 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
6194   struct font *font = XFONT_OBJECT (font_object);
6196   if (fontset < 0)
6197     fontset = fontset_from_font (font_object);
6198   FRAME_FONTSET (f) = fontset;
6200   if (FRAME_FONT (f) == font)
6201     /* This font is already set in frame F.  There's nothing more to
6202        do.  */
6203     return font_object;
6205   FRAME_FONT (f) = font;
6207   FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
6208   FRAME_COLUMN_WIDTH (f) = font->average_width;
6209   FRAME_SPACE_WIDTH (f) = font->space_width;
6210   FRAME_LINE_HEIGHT (f) = font->height;
6212   compute_fringe_widths (f, 1);
6214   /* Compute the scroll bar width in character columns.  */
6215   if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
6216     {
6217       int wid = FRAME_COLUMN_WIDTH (f);
6218       FRAME_CONFIG_SCROLL_BAR_COLS (f)
6219         = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
6220     }
6221   else
6222     {
6223       int wid = FRAME_COLUMN_WIDTH (f);
6224       FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
6225     }
6227   /* Now make the frame display the given font.  */
6228   if (FRAME_NS_WINDOW (f) != 0)
6229         x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
6231   return font_object;
6235 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
6237 static const char *
6238 ns_font_to_xlfd (NSFont *nsfont)
6239 /* --------------------------------------------------------------------------
6240     Convert an NS font name to an X font name (XLFD).
6241     The string returned is temporarily allocated.
6242    -------------------------------------------------------------------------- */
6244   NSFontManager *mgr = [NSFontManager sharedFontManager];
6245   NSString *sname = [nsfont /*familyName*/fontName];
6246   char *famName = (char *)[sname UTF8String];
6247   char *weightStr = [mgr fontNamed: sname hasTraits: NSBoldFontMask] ?
6248       "bold" : "medium";
6249   char *slantStr = [mgr fontNamed: sname hasTraits: NSItalicFontMask] ?
6250       "i" : "r";
6251   int size = [nsfont pointSize];
6252   int aWidth = lrint (10.0 * [nsfont widthOfString: @"a"]);
6253   const char *xlfd;
6254   int i, len;
6256   /* change '-' to '$' to avoid messing w/XLFD separator */
6257   for (len = strlen (famName), i =0; i<len; i++)
6258     if (famName[i] == '-')
6259       {
6260         famName[i] = '\0';
6261         break;
6262       }
6264   xlfd = [[NSString stringWithFormat:
6265                        @"-apple-%s-%s-%s-normal--%d-%d-75-75-m-%d-iso10646-1",
6266                        famName, weightStr, slantStr, size, 10*size, aWidth]
6267                   UTF8String];
6268 /*fprintf (stderr, "converted '%s' to '%s'\n",name,xlfd); */
6269   return xlfd;
6272 static const char *
6273 ns_fontname_to_xlfd (const char *name)
6274 /* --------------------------------------------------------------------------
6275     Convert an NS font name to an X font name (XLFD).
6276     Sizes are set to 0.
6277     The string returned is temporarily allocated.
6278    -------------------------------------------------------------------------- */
6280   char famName[180];
6281   char *weightStr = strcasestr (name, "bold") ? "bold" : "medium";
6282   char *slantStr = strcasestr (name, "italic") || strcasestr (name, "oblique")
6283     || strcasestr (name, "synthital") ? "i" : "r";
6284   int i, len;
6285   const char *xlfd;
6287   /* change '-' to '$' to avoid messing w/XLFD separator, and ' ' to '_' */
6288   bzero (famName, 180);
6289   bcopy (name, famName, max (strlen (name), 179));
6290   for (len =strlen (famName), i =0; i<len; i++)
6291     {
6292       if (famName[i] == '-')
6293         famName[i] = '$';
6294       else if (famName[i] == ' ')
6295         famName[i] = '_';
6296     }
6298   xlfd = [[NSString stringWithFormat:
6299                            @"-apple-%s-%s-%s-normal--0-0-75-75-m-0-iso10646-1",
6300                            famName, weightStr, slantStr]
6301                   UTF8String];
6302 /*fprintf (stderr, "converted '%s' to '%s'\n",name,xlfd); */
6303   return xlfd;
6307 const char *
6308 ns_xlfd_to_fontname (const char *xlfd)
6309 /* --------------------------------------------------------------------------
6310     Convert an X font name (XLFD) to an NS font name.
6311     Only family is used.
6312     The string returned is temporarily allocated.
6313    -------------------------------------------------------------------------- */
6315   char *name = xmalloc (180);
6316   int i, len;
6317   const char *ret;
6319   if (!strncmp (xlfd, "--", 2))
6320     sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
6321   else
6322     sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
6324   /* stopgap for malformed XLFD input */
6325   if (strlen (name) == 0)
6326     strcpy (name, "Monaco");
6328   /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
6329      also uppercase after '-' or ' ' */
6330   name[0] = toupper (name[0]);
6331   for (len =strlen (name), i =0; i<len; i++)
6332     {
6333       if (name[i] == '$')
6334         {
6335           name[i] = '-';
6336           if (i+1<len)
6337             name[i+1] = toupper (name[i+1]);
6338         }
6339       else if (name[i] == '_')
6340         {
6341           name[i] = ' ';
6342           if (i+1<len)
6343             name[i+1] = toupper (name[i+1]);
6344         }
6345     }
6346 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name);  */
6347   ret = [[NSString stringWithUTF8String: name] UTF8String];
6348   xfree (name);
6349   return ret;
6353 void
6354 syms_of_nsterm ()
6356   NSTRACE (syms_of_nsterm);
6357   DEFVAR_LISP ("ns-input-file", &ns_input_file,
6358               "The file specified in the last NS event.");
6359   ns_input_file =Qnil;
6361   DEFVAR_LISP ("ns-input-text", &ns_input_text,
6362               "The data received in the last NS text drag event.");
6363   ns_input_text =Qnil;
6365   DEFVAR_LISP ("ns-working-text", &ns_working_text,
6366               "String for visualizing working composition sequence.");
6367   ns_working_text =Qnil;
6369   DEFVAR_LISP ("ns-input-font", &ns_input_font,
6370               "The font specified in the last NS event.");
6371   ns_input_font =Qnil;
6373   DEFVAR_LISP ("ns-input-fontsize", &ns_input_fontsize,
6374               "The fontsize specified in the last NS event.");
6375   ns_input_fontsize =Qnil;
6377   DEFVAR_LISP ("ns-input-line", &ns_input_line,
6378                "The line specified in the last NS event.");
6379   ns_input_line =Qnil;
6381   DEFVAR_LISP ("ns-input-color", &ns_input_color,
6382                "The color specified in the last NS event.");
6383   ns_input_color =Qnil;
6385   DEFVAR_LISP ("ns-input-spi-name", &ns_input_spi_name,
6386                "The service name specified in the last NS event.");
6387   ns_input_spi_name =Qnil;
6389   DEFVAR_LISP ("ns-input-spi-arg", &ns_input_spi_arg,
6390                "The service argument specified in the last NS event.");
6391   ns_input_spi_arg =Qnil;
6393   DEFVAR_LISP ("ns-alternate-modifier", &ns_alternate_modifier,
6394                "This variable describes the behavior of the alternate or option key.\n\
6395 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6396 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6397 at all, allowing it to be used at a lower level for accented character entry.");
6399   DEFVAR_LISP ("ns-command-modifier", &ns_command_modifier,
6400                "This variable describes the behavior of the command key.\n\
6401 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6403   DEFVAR_LISP ("ns-control-modifier", &ns_control_modifier,
6404                "This variable describes the behavior of the control key.\n\
6405 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6407   DEFVAR_LISP ("ns-function-modifier", &ns_function_modifier,
6408                "This variable describes the behavior of the function key (on laptops).\n\
6409 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6410 Set to none means that the function key is not interpreted by Emacs at all,\n\
6411 allowing it to be used at a lower level for accented character entry.");
6413   DEFVAR_LISP ("ns-expand-space", &ns_expand_space,
6414                "Amount by which spacing between lines is expanded (positive)\n\
6415 or shrunk (negative).  Zero (the default) means standard line height.\n\
6416 (This variable should only be read, never set.)");
6418   DEFVAR_LISP ("ns-antialias-text", &ns_antialias_text,
6419                "Non-nil (the default) means to render text antialiased. Only has an effect on OS X Panther and above.");
6421   DEFVAR_LISP ("ns-use-qd-smoothing", &ns_use_qd_smoothing,
6422                "Whether to render text using QuickDraw (less heavy) antialiasing. Only has an effect on OS X Panther and above.  Default is nil (use Quartz smoothing).");
6424   DEFVAR_LISP ("ns-use-system-highlight-color",
6425                &ns_use_system_highlight_color,
6426                "Whether to use the system default (on OS X only) for the highlight color.  Nil means to use standard emacs (prior to version 21) 'grey'.");
6428   staticpro (&ns_display_name_list);
6429   ns_display_name_list = Qnil;
6431   staticpro (&last_mouse_motion_frame);
6432   last_mouse_motion_frame = Qnil;
6434   /*23: now apparently we need to tell emacs what modifiers there are.. */
6435   Qmodifier_value = intern ("modifier-value");
6436   Qalt = intern ("alt");
6437   Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
6438   Qhyper = intern ("hyper");
6439   Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
6440   Qmeta = intern ("meta");
6441   Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
6442   Qsuper = intern ("super");
6443   Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
6444   Qcontrol = intern ("control");
6445   Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
6447   /* TODO: move to common code */
6448   DEFVAR_LISP ("x-toolkit-scroll-bars", &Vx_toolkit_scroll_bars,
6449                doc: /* If not nil, Emacs uses toolkit scroll bars.  */);
6450 #ifdef USE_TOOLKIT_SCROLL_BARS
6451   Vx_toolkit_scroll_bars = Qt;
6452 #else
6453   Vx_toolkit_scroll_bars = Qnil;
6454 #endif
6456   /* these are unsupported but we need the declarations to avoid whining
6457      messages from cus-start.el */
6458   DEFVAR_BOOL ("x-use-underline-position-properties",
6459                &x_use_underline_position_properties,
6460      doc: /* NOT SUPPORTED UNDER NS.
6461 *Non-nil means make use of UNDERLINE_POSITION font properties.
6462 A value of nil means ignore them.  If you encounter fonts with bogus
6463 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
6464 to 4.1, set this to nil.
6466 NOTE: Not supported on Mac yet.  */);
6467   x_use_underline_position_properties = 0;
6469   DEFVAR_BOOL ("x-underline-at-descent-line",
6470                &x_underline_at_descent_line,
6471      doc: /* NOT SUPPORTED UNDER NS.
6472 *Non-nil means to draw the underline at the same place as the descent line.
6473 A value of nil means to draw the underline according to the value of the
6474 variable `x-use-underline-position-properties', which is usually at the
6475 baseline level.  The default value is nil.  */);
6476   x_underline_at_descent_line = 0;
6478   /* Tell emacs about this window system. */
6479   Fprovide (intern ("ns"), Qnil);
6483 // arch-tag: 6eaa8f7d-a69b-4e1c-b43d-ab31defbe0d2