1 /* NeXT/Open/GNUstep / MacOSX communication module.
2 Copyright (C) 1989, 1993, 1994, 2005, 2006, 2008
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)
29 #include <sys/types.h>
35 #include "blockinput.h"
36 #include "sysselect.h"
39 #include "character.h"
41 #include "composite.h"
44 #include "termhooks.h"
55 int term_trace_num = 0;
56 #define NSTRACE(x) fprintf (stderr, "%s:%d: [%d] " #x "\n", \
57 __FILE__, __LINE__, ++term_trace_num)
63 /* ==========================================================================
67 ========================================================================== */
69 /* Special keycodes that we pass down the event chain */
70 #define KEY_NS_POWER_OFF ((1<<28)|(0<<16)|1)
71 #define KEY_NS_OPEN_FILE ((1<<28)|(0<<16)|2)
72 #define KEY_NS_OPEN_TEMP_FILE ((1<<28)|(0<<16)|3)
73 #define KEY_NS_DRAG_FILE ((1<<28)|(0<<16)|4)
74 #define KEY_NS_DRAG_COLOR ((1<<28)|(0<<16)|5)
75 #define KEY_NS_DRAG_TEXT ((1<<28)|(0<<16)|6)
76 #define KEY_NS_CHANGE_FONT ((1<<28)|(0<<16)|7)
77 #define KEY_NS_OPEN_FILE_LINE ((1<<28)|(0<<16)|8)
78 #define KEY_NS_INSERT_WORKING_TEXT ((1<<28)|(0<<16)|9)
79 #define KEY_NS_DELETE_WORKING_TEXT ((1<<28)|(0<<16)|10)
80 #define KEY_NS_SPI_SERVICE_CALL ((1<<28)|(0<<16)|11)
81 #define KEY_NS_NEW_FRAME ((1<<28)|(0<<16)|12)
83 /* Convert a symbol indexed with an NSxxx value to a value as defined
84 in keyboard.c (lispy_function_key). I hope this is a correct way
86 static unsigned convert_ns_to_X_keysym[] =
88 NSHomeFunctionKey, 0x50,
89 NSLeftArrowFunctionKey, 0x51,
90 NSUpArrowFunctionKey, 0x52,
91 NSRightArrowFunctionKey, 0x53,
92 NSDownArrowFunctionKey, 0x54,
93 NSPageUpFunctionKey, 0x55,
94 NSPageDownFunctionKey, 0x56,
95 NSEndFunctionKey, 0x57,
96 NSBeginFunctionKey, 0x58,
97 NSSelectFunctionKey, 0x60,
98 NSPrintFunctionKey, 0x61,
99 NSExecuteFunctionKey, 0x62,
100 NSInsertFunctionKey, 0x63,
101 NSUndoFunctionKey, 0x65,
102 NSRedoFunctionKey, 0x66,
103 NSMenuFunctionKey, 0x67,
104 NSFindFunctionKey, 0x68,
105 NSHelpFunctionKey, 0x6A,
106 NSBreakFunctionKey, 0x6B,
108 NSF1FunctionKey, 0xBE,
109 NSF2FunctionKey, 0xBF,
110 NSF3FunctionKey, 0xC0,
111 NSF4FunctionKey, 0xC1,
112 NSF5FunctionKey, 0xC2,
113 NSF6FunctionKey, 0xC3,
114 NSF7FunctionKey, 0xC4,
115 NSF8FunctionKey, 0xC5,
116 NSF9FunctionKey, 0xC6,
117 NSF10FunctionKey, 0xC7,
118 NSF11FunctionKey, 0xC8,
119 NSF12FunctionKey, 0xC9,
120 NSF13FunctionKey, 0xCA,
121 NSF14FunctionKey, 0xCB,
122 NSF15FunctionKey, 0xCC,
124 NSBackspaceCharacter, 0x08, /* 8: Not on some KBs. */
125 NSDeleteCharacter, 0xFF, /* 127: Big 'delete' key upper right. */
126 NSDeleteFunctionKey, 0x9F, /* 63272: Del forw key off main array. */
128 NSTabCharacter, 0x09,
129 0x19, 0x09, /* left tab->regular since pass shift */
130 NSCarriageReturnCharacter, 0x0D,
131 NSNewlineCharacter, 0x0D,
132 NSEnterCharacter, 0x8D,
134 0x1B, 0x1B /* escape */
138 /* Lisp communications */
139 Lisp_Object ns_input_file, ns_input_font, ns_input_fontsize, ns_input_line;
140 Lisp_Object ns_input_color, ns_input_text, ns_working_text;
141 Lisp_Object ns_input_spi_name, ns_input_spi_arg;
142 Lisp_Object Vx_toolkit_scroll_bars;
143 static Lisp_Object Qmodifier_value;
144 /* TODO: unsure why these defined in term files, anyway we need in keymap.c */
145 Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper;
146 extern Lisp_Object Qcursor_color, Qcursor_type, Qns;
149 EmacsPrefsController *prefsController;
151 /* Defaults managed through the OpenStep defaults system. These pertain to
152 the NS interface specifically. Although a customization group could be
153 created, it's more natural to manage them via defaults. */
155 /* Specifies which emacs modifier should be generated when NS receives
156 the Alternate modifer. May be Qnone or any of the modifier lisp symbols. */
157 Lisp_Object ns_alternate_modifier;
159 /* Specifies which emacs modifier should be generated when NS receives
160 the Command modifer. May be any of the modifier lisp symbols. */
161 Lisp_Object ns_command_modifier;
163 /* Specifies which emacs modifier should be generated when NS receives
164 the Control modifer. May be any of the modifier lisp symbols. */
165 Lisp_Object ns_control_modifier;
167 /* Specifies which emacs modifier should be generated when NS receives
168 the Function modifer (laptops). May be any of the modifier lisp symbols. */
169 Lisp_Object ns_function_modifier;
171 /* A floating point value specifying vertical stretch (positive) or shrink
172 (negative) of text line spacing. Zero means default spacing.
173 YES indicates 0.5, NO indicates 0.0. */
174 Lisp_Object ns_expand_space;
176 /* Control via default 'GSFontAntiAlias' on OS X and GNUstep. */
177 Lisp_Object ns_antialias_text;
179 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
180 the maximum font size to NOT antialias. On GNUstep there is currently
181 no way to control this behavior. */
182 float ns_antialias_threshold;
184 /* Controls use of an undocumented CG function to do Quickdraw-style font
185 smoothing (less heavy) instead of regular Quartz smoothing. */
186 Lisp_Object ns_use_qd_smoothing;
188 /* Used to pick up AppleHighlightColor on OS X */
189 Lisp_Object ns_use_system_highlight_color;
190 NSString *ns_selection_color;
193 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
195 /* Display variables */
196 struct ns_display_info *x_display_list; /* Chain of existing displays */
197 Lisp_Object ns_display_name_list;
198 long context_menu_value = 0;
201 NSPoint last_mouse_motion_position;
202 static NSRect last_mouse_glyph;
203 static unsigned long last_mouse_movement_time = 0;
204 static Lisp_Object last_mouse_motion_frame;
205 static EmacsScroller *last_mouse_scroll_bar = nil;
206 static struct frame *ns_updating_frame;
207 static NSView *focus_view = NULL;
208 static int ns_window_num =0;
210 static BOOL gsaved = NO;
211 BOOL ns_in_resize = NO;
212 int ns_tmp_flags; /* FIXME */
213 struct nsfont_info *ns_tmp_font; /* FIXME */
214 /*static int debug_lock = 0; */
217 /* This undocumented Quartz function controls how fonts are anti-aliased.
218 (Found from code in Mac wxWindows impl, discovered by running `nm' on
220 Mode 0 is normal anti-aliasing, mode 1 is no anti-aliasing, and mode 2 is
221 4-bit pixel-aligned anti-aliasing (the old QuickDraw standard). */
222 extern void CGContextSetFontRenderingMode (CGContextRef cg, int v);
227 static BOOL send_appdefined = YES;
228 static NSEvent *last_appdefined_event = 0;
229 static NSTimer *timed_entry = 0;
230 static NSTimer *fd_entry = nil;
231 static NSTimer *scroll_repeat_entry = nil;
232 static fd_set select_readfds, t_readfds;
233 static struct timeval select_timeout;
234 static int select_nfds;
235 static NSAutoreleasePool *outerpool;
236 static BOOL ns_shutdown_properly = NO;
237 static struct input_event *emacs_event = NULL;
238 static struct input_event *q_event_ptr = NULL;
239 static int n_emacs_events_pending = 0;
240 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
241 *ns_pending_service_args;
242 static BOOL inNsSelect = 0;
244 /* Convert modifiers in a NeXTSTEP event to emacs style modifiers. */
245 #define NS_FUNCTION_KEY_MASK 0x800000
246 #define EV_MODIFIERS(e) \
247 ((([e modifierFlags] & NSHelpKeyMask) ? \
248 hyper_modifier : 0) \
249 | (([e modifierFlags] & NSAlternateKeyMask) ? \
250 parse_solitary_modifier (ns_alternate_modifier) : 0) \
251 | (([e modifierFlags] & NSShiftKeyMask) ? \
252 shift_modifier : 0) \
253 | (([e modifierFlags] & NSControlKeyMask) ? \
254 parse_solitary_modifier (ns_control_modifier) : 0) \
255 | (([e modifierFlags] & NS_FUNCTION_KEY_MASK) ? \
256 parse_solitary_modifier (ns_function_modifier) : 0) \
257 | (([e modifierFlags] & NSCommandKeyMask) ? \
258 parse_solitary_modifier (ns_command_modifier):0))
260 #define EV_UDMODIFIERS(e) \
261 ((([e type] == NSLeftMouseDown) ? down_modifier : 0) \
262 | (([e type] == NSRightMouseDown) ? down_modifier : 0) \
263 | (([e type] == NSLeftMouseDragged) ? down_modifier : 0) \
264 | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
265 | (([e type] == NSLeftMouseUp) ? up_modifier : 0) \
266 | (([e type] == NSRightMouseUp) ? up_modifier : 0))
268 #define EV_BUTTON(e) \
269 ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 : \
270 (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : 1)
272 /* Convert the time field to a timestamp in milliseconds. */
273 #ifdef NS_IMPL_GNUSTEP
274 /* Apple says timestamp is in seconds, but GNUstep seems to be returning msec */
275 #define EV_TIMESTAMP(e) ([e timestamp])
277 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
278 #endif /* not gnustep */
280 /* This is a piece of code which is common to all the event handling
281 methods. Maybe it should even be a function. */
282 #define EV_TRAILER(e) \
284 XSETFRAME (emacs_event->frame_or_window, [NSApp isActive] ? \
285 emacsframe : SELECTED_FRAME ()); \
286 if (e) emacs_event->timestamp = EV_TIMESTAMP (e); \
287 n_emacs_events_pending++; \
288 kbd_buffer_store_event_hold (emacs_event, q_event_ptr); \
289 EVENT_INIT (*emacs_event); \
290 ns_send_appdefined (-1); \
293 /* TODO: get rid of need for these forward declarations */
294 static void ns_condemn_scroll_bars (struct frame *f),
295 ns_judge_scroll_bars (struct frame *f);
297 /* unused variables needed for compatibility reasons */
298 int x_use_underline_position_properties, x_underline_at_descent_line;
299 /* FIXME: figure out what to do with underline_minimum_offset. */
302 /* ==========================================================================
306 ========================================================================== */
310 append2 (Lisp_Object list, Lisp_Object item)
311 /* --------------------------------------------------------------------------
312 Utility to append to a list
313 -------------------------------------------------------------------------- */
315 Lisp_Object array[2];
317 array[1] = Fcons (item, Qnil);
318 return Fnconc (2, &array[0]);
324 /* --------------------------------------------------------------------------
325 Used to allow emacs to find its resources under Emacs.app
326 Called from emacs.c at startup.
327 -------------------------------------------------------------------------- */
329 NSBundle *bundle = [NSBundle mainBundle];
330 NSString *binDir = [bundle bundlePath], *resourceDir = [bundle resourcePath];
331 NSString *resourcePath, *resourcePaths;
333 BOOL onWindows = NO; /* how do I determine this? */
334 NSString *pathSeparator = onWindows ? @";" : @":";
335 NSFileManager *fileManager = [NSFileManager defaultManager];
337 /*NSLog (@"ns_init_paths: '%@'\n%@\n", [[NSBundle mainBundle] bundlePath], [[NSBundle mainBundle] resourcePath]); */
339 /* get bindir from base */
340 range = [resourceDir rangeOfString: @"Contents"];
341 if (range.location != NSNotFound)
343 binDir = [binDir stringByAppendingPathComponent: @"Contents"];
345 binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
349 /* the following based on Andrew Choi's init_mac_osx_environment () */
350 if (!getenv ("EMACSLOADPATH"))
352 NSArray *paths = [resourceDir stringsByAppendingPaths:
353 [NSArray arrayWithObjects:
354 @"site-lisp", @"lisp", @"leim", nil]];
355 NSEnumerator *pathEnum = [paths objectEnumerator];
357 while (resourcePath = [pathEnum nextObject])
359 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
362 if ([resourcePaths length] > 0)
364 = [resourcePaths stringByAppendingString: pathSeparator];
366 = [resourcePaths stringByAppendingString: resourcePath];
369 if ([resourcePaths length] > 0)
370 setenv ("EMACSLOADPATH", [resourcePaths UTF8String], 1);
371 /*NSLog (@"loadPath: '%s'\n", resourcePaths); */
374 if (!getenv ("EMACSPATH"))
376 NSArray *paths = [binDir stringsByAppendingPaths:
377 [NSArray arrayWithObjects: @"bin",
379 NSEnumerator *pathEnum = [paths objectEnumerator];
381 while (resourcePath = [pathEnum nextObject])
383 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
386 if ([resourcePaths length] > 0)
388 = [resourcePaths stringByAppendingString: pathSeparator];
390 = [resourcePaths stringByAppendingString: resourcePath];
393 if ([resourcePaths length] > 0)
394 setenv ("EMACSPATH", [resourcePaths UTF8String], 1);
397 resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
398 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
402 if (!getenv ("EMACSDATA"))
403 setenv ("EMACSDATA", [resourcePath UTF8String], 1);
404 if (!getenv ("EMACSDOC"))
405 setenv ("EMACSDOC", [resourcePath UTF8String], 1);
409 if (!getenv ("INFOPATH"))
411 resourcePath = [resourceDir stringByAppendingPathComponent: @"info"];
412 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
414 setenv ("INFOPATH", [resourcePath UTF8String], 1);
420 timeval_subtract (struct timeval *result, struct timeval x, struct timeval y)
421 /* --------------------------------------------------------------------------
422 Subtract the `struct timeval' values X and Y, storing the result in RESULT.
423 Return 1 if the difference is negative, otherwise 0.
424 -------------------------------------------------------------------------- */
426 /* Perform the carry for the later subtraction by updating y.
427 This is safer because on some systems
428 the tv_sec member is unsigned. */
429 if (x.tv_usec < y.tv_usec)
431 int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
432 y.tv_usec -= 1000000 * nsec;
435 if (x.tv_usec - y.tv_usec > 1000000)
437 int nsec = (y.tv_usec - x.tv_usec) / 1000000;
438 y.tv_usec += 1000000 * nsec;
442 /* Compute the time remaining to wait. tv_usec is certainly positive. */
443 result->tv_sec = x.tv_sec - y.tv_sec;
444 result->tv_usec = x.tv_usec - y.tv_usec;
446 /* Return indication of whether the result should be considered negative. */
447 return x.tv_sec < y.tv_sec;
451 ns_timeout (int usecs)
452 /* --------------------------------------------------------------------------
453 Blocking timer utility used by ns_ring_bell
454 -------------------------------------------------------------------------- */
456 struct timeval wakeup;
458 EMACS_GET_TIME (wakeup);
460 /* Compute time to wait until, propagating carry from usecs. */
461 wakeup.tv_usec += usecs;
462 wakeup.tv_sec += (wakeup.tv_usec / 1000000);
463 wakeup.tv_usec %= 1000000;
465 /* Keep waiting until past the time wakeup. */
468 struct timeval timeout;
470 EMACS_GET_TIME (timeout);
472 /* In effect, timeout = wakeup - timeout.
473 Break if result would be negative. */
474 if (timeval_subtract (&timeout, wakeup, timeout))
477 /* Try to wait that long--but we might wake up sooner. */
478 select (0, NULL, NULL, NULL, &timeout);
484 ns_release_object (void *obj)
485 /* --------------------------------------------------------------------------
486 Release an object (callable from C)
487 -------------------------------------------------------------------------- */
494 ns_retain_object (void *obj)
495 /* --------------------------------------------------------------------------
496 Retain an object (callable from C)
497 -------------------------------------------------------------------------- */
504 ns_alloc_autorelease_pool ()
505 /* --------------------------------------------------------------------------
506 Allocate a pool for temporary objects (callable from C)
507 -------------------------------------------------------------------------- */
509 return [[NSAutoreleasePool alloc] init];
514 ns_release_autorelease_pool (void *pool)
515 /* --------------------------------------------------------------------------
516 Free a pool and temporary objects it refers to (callable from C)
517 -------------------------------------------------------------------------- */
519 ns_release_object (pool);
524 /* ==========================================================================
526 Focus (clipping) and screen update
528 ========================================================================== */
531 ns_resize_handle_rect (NSWindow *window)
533 NSRect r = [window frame];
534 r.origin.x = r.size.width - RESIZE_HANDLE_SIZE;
536 r.size.width = r.size.height = RESIZE_HANDLE_SIZE;
542 ns_update_begin (struct frame *f)
543 /* --------------------------------------------------------------------------
544 Prepare for a grouped sequence of drawing calls
545 23: external (RIF) call; now split w/ and called before update_window_begin
546 -------------------------------------------------------------------------- */
548 NSView *view = FRAME_NS_VIEW (f);
549 NSTRACE (ns_update_begin);
550 /*fprintf (stderr, "\\%p\n", f); */
552 ns_updating_frame = f;
555 #ifdef NS_IMPL_GNUSTEP
556 uRect = NSMakeRect (0, 0, 0, 0);
562 ns_update_window_begin (struct window *w)
563 /* --------------------------------------------------------------------------
564 Prepare for a grouped sequence of drawing calls
565 23: external (RIF) call; now split with and called after update_begin
566 -------------------------------------------------------------------------- */
568 struct frame *f = XFRAME (WINDOW_FRAME (w));
569 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
570 NSTRACE (ns_update_window_begin);
573 set_output_cursor (&w->cursor);
577 if (f == dpyinfo->mouse_face_mouse_frame)
579 /* Don't do highlighting for mouse motion during the update. */
580 dpyinfo->mouse_face_defer = 1;
582 /* If the frame needs to be redrawn,
583 simply forget about any prior mouse highlighting. */
584 if (FRAME_GARBAGED_P (f))
585 dpyinfo->mouse_face_window = Qnil;
587 /* (further code for mouse faces ifdef'd out in other terms elided) */
595 ns_update_window_end (struct window *w, int cursor_on_p,
596 int mouse_face_overwritten_p)
597 /* --------------------------------------------------------------------------
598 Finished a grouped sequence of drawing calls
599 23: external (RIF) call; now split with and called before update_window_end
600 -------------------------------------------------------------------------- */
602 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (XFRAME (w->frame));
604 /* note: this fn is nearly identical in all terms */
605 if (!w->pseudo_window_p)
610 display_and_set_cursor (w, 1,
611 output_cursor.hpos, output_cursor.vpos,
612 output_cursor.x, output_cursor.y);
614 if (draw_window_fringes (w, 1))
615 x_draw_vertical_border (w);
620 /* If a row with mouse-face was overwritten, arrange for
621 frame_up_to_date to redisplay the mouse highlight. */
622 if (mouse_face_overwritten_p)
624 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
625 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
626 dpyinfo->mouse_face_window = Qnil;
629 updated_window = NULL;
630 NSTRACE (update_window_end);
635 ns_update_end (struct frame *f)
636 /* --------------------------------------------------------------------------
637 Finished a grouped sequence of drawing calls
638 23: external (RIF) call; now split with and called after update_window_end
639 -------------------------------------------------------------------------- */
641 NSView *view = FRAME_NS_VIEW (f);
643 /* if (f == FRAME_NS_DISPLAY_INFO (f)->mouse_face_mouse_frame) */
644 FRAME_NS_DISPLAY_INFO (f)->mouse_face_defer = 0;
648 #ifdef NS_IMPL_GNUSTEP
649 /* trigger flush only in the rectangle we tracked as being drawn */
650 [view unlockFocusNeedsFlush: NO];
651 /*fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", uRect.origin.x, uRect.origin.y, uRect.size.width, uRect.size.height); */
652 [view lockFocusInRect: uRect];
656 [[view window] flushWindow];
659 ns_updating_frame = NULL;
660 NSTRACE (ns_update_end);
665 ns_flush (struct frame *f)
666 /* --------------------------------------------------------------------------
667 23: external (RIF) call
668 NS impl is no-op since currently we flush in ns_update_end and elsewhere
669 -------------------------------------------------------------------------- */
676 ns_focus (struct frame *f, NSRect *r, int n)
677 /* --------------------------------------------------------------------------
678 Internal: Focus on given frame. During small local updates this is used to
679 draw, however during large updates, ns_update_begin and ns_update_end are
680 called to wrap the whole thing, in which case these calls are stubbed out.
681 Except, on GNUstep, we accumulate the rectangle being drawn into, because
682 the back end won't do this automatically, and will just end up flushing
684 -------------------------------------------------------------------------- */
687 #ifdef NS_IMPL_GNUSTEP
690 u = NSUnionRect (r[0], r[1]);
695 fprintf (stderr, "focus: %d", c++);
696 if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
697 fprintf (stderr, "\n"); */
699 if (f != ns_updating_frame)
701 NSView *view = FRAME_NS_VIEW (f);
702 if (view != focus_view)
704 if (focus_view != NULL)
706 [focus_view unlockFocus];
707 [[focus_view window] flushWindow];
712 #ifdef NS_IMPL_GNUSTEP
713 r ? [view lockFocusInRect: u] : [view lockFocus];
718 /*if (view) debug_lock++; */
720 #ifdef NS_IMPL_GNUSTEP
723 /* more than one rect being drawn into */
726 [view unlockFocus]; /* add prev rect to redraw list */
727 [view lockFocusInRect: u]; /* focus for draw in new rect */
732 #ifdef NS_IMPL_GNUSTEP
735 /* in batch mode, but in GNUstep must still track rectangles explicitly */
736 uRect = (r ? NSUnionRect (uRect, u) : [FRAME_NS_VIEW (f) visibleRect]);
743 [[NSGraphicsContext currentContext] saveGraphicsState];
745 NSRectClipList (r, 2);
754 ns_unfocus (struct frame *f)
755 /* --------------------------------------------------------------------------
756 Internal: Remove focus on given frame
757 -------------------------------------------------------------------------- */
759 NSTRACE (ns_unfocus);
763 [[NSGraphicsContext currentContext] restoreGraphicsState];
767 if (f != ns_updating_frame)
769 if (focus_view != NULL)
771 [focus_view unlockFocus];
772 [[focus_view window] flushWindow];
781 ns_clip_to_row (struct window *w, struct glyph_row *row, int area, BOOL gc)
782 /* --------------------------------------------------------------------------
783 23: Internal (but parallels other terms): Focus drawing on given row
784 -------------------------------------------------------------------------- */
786 struct frame *f = XFRAME (WINDOW_FRAME (w));
788 int window_x, window_y, window_width;
790 window_box (w, area, &window_x, &window_y, &window_width, 0);
792 clip_rect.origin.x = window_x - FRAME_INTERNAL_BORDER_WIDTH (f);
793 clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
794 clip_rect.origin.y = max (clip_rect.origin.y, window_y);
795 clip_rect.size.width = window_width + 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
796 clip_rect.size.height = row->visible_height;
798 /* allow a full-height row at the top when requested
799 (used to draw fringe all the way through internal border area) */
800 if (gc && clip_rect.origin.y < 5)
802 clip_rect.origin.y -= FRAME_INTERNAL_BORDER_WIDTH (f);
803 clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
806 /* likewise at bottom */
808 FRAME_PIXEL_HEIGHT (f) - (clip_rect.origin.y + clip_rect.size.height) < 5)
809 clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
811 ns_focus (f, &clip_rect, 1);
817 /* --------------------------------------------------------------------------
819 -------------------------------------------------------------------------- */
821 NSTRACE (ns_ring_bell);
824 NSAutoreleasePool *pool;
825 struct frame *frame = SELECTED_FRAME ();
829 pool = [[NSAutoreleasePool alloc] init];
831 view = FRAME_NS_VIEW (frame);
835 NSPoint dim = NSMakePoint (128, 128);
838 r.origin.x += (r.size.width - dim.x) / 2;
839 r.origin.y += (r.size.height - dim.y) / 2;
840 r.size.width = dim.x;
841 r.size.height = dim.y;
842 /* XXX: cacheImageInRect under GNUSTEP does not account for
843 offset in x_set_window_size, so overestimate (4 fine on Cocoa) */
844 surr = NSInsetRect (r, -10, -10);
845 ns_focus (frame, &surr, 1);
846 [[view window] cacheImageInRect: surr];
847 [ns_lookup_indexed_color (NS_FACE_FOREGROUND
848 (FRAME_DEFAULT_FACE (frame)), frame) set];
850 [[view window] flushWindow];
852 [[view window] restoreCachedImage];
853 [[view window] flushWindow];
867 ns_reset_terminal_modes (struct terminal *terminal)
868 /* Externally called as hook */
870 NSTRACE (ns_reset_terminal_modes);
874 ns_set_terminal_modes (struct terminal *terminal)
875 /* Externally called as hook */
877 NSTRACE (ns_set_terminal_modes);
882 /* ==========================================================================
884 Frame / window manager related functions
886 ========================================================================== */
890 ns_raise_frame (struct frame *f)
891 /* --------------------------------------------------------------------------
892 Bring window to foreground and make it active
893 -------------------------------------------------------------------------- */
895 NSView *view = FRAME_NS_VIEW (f);
898 [[view window] makeKeyAndOrderFront: NSApp];
904 ns_lower_frame (struct frame *f)
905 /* --------------------------------------------------------------------------
907 -------------------------------------------------------------------------- */
909 NSView *view = FRAME_NS_VIEW (f);
912 [[view window] orderBack: NSApp];
918 ns_frame_raise_lower (struct frame *f, int raise)
919 /* --------------------------------------------------------------------------
921 -------------------------------------------------------------------------- */
923 NSTRACE (ns_frame_raise_lower);
933 ns_frame_rehighlight (struct frame *frame)
934 /* --------------------------------------------------------------------------
935 External (hook): called on things like window switching within frame
936 -------------------------------------------------------------------------- */
938 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
939 struct frame *old_highlight = dpyinfo->x_highlight_frame;
941 NSTRACE (ns_frame_rehighlight);
942 if (dpyinfo->x_focus_frame)
944 dpyinfo->x_highlight_frame
945 = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
946 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
947 : dpyinfo->x_focus_frame);
948 if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
950 FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
951 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
955 dpyinfo->x_highlight_frame = 0;
957 if (dpyinfo->x_highlight_frame &&
958 dpyinfo->x_highlight_frame != old_highlight)
960 /* as of 20080602 the lower and raise are superfluous */
963 /*ns_lower_frame (old_highlight); */
964 x_update_cursor (old_highlight, 1);
966 if (dpyinfo->x_highlight_frame)
968 /*ns_raise_frame (dpyinfo->x_highlight_frame); */
969 x_update_cursor (dpyinfo->x_highlight_frame, 1);
976 x_make_frame_visible (struct frame *f)
977 /* --------------------------------------------------------------------------
978 External: Show the window (X11 semantics)
979 -------------------------------------------------------------------------- */
981 NSTRACE (x_make_frame_visible);
982 /* XXX: at some points in past this was not needed, as the only place that
983 called this (frame.c:Fraise_frame ()) also called raise_lower;
984 if this ends up the case again, comment this out again. */
985 if (!FRAME_VISIBLE_P (f))
991 x_make_frame_invisible (struct frame *f)
992 /* --------------------------------------------------------------------------
993 External: Hide the window (X11 semantics)
994 -------------------------------------------------------------------------- */
996 NSView * view = FRAME_NS_VIEW (f);
997 NSTRACE (x_make_frame_invisible);
999 [[view window] orderOut: NSApp];
1004 x_iconify_frame (struct frame *f)
1005 /* --------------------------------------------------------------------------
1006 External: Iconify window
1007 -------------------------------------------------------------------------- */
1009 NSView * view = FRAME_NS_VIEW (f);
1010 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1011 NSTRACE (x_iconify_frame);
1014 if (dpyinfo->x_highlight_frame == f)
1015 dpyinfo->x_highlight_frame = 0;
1017 if ([[view window] windowNumber] <= 0)
1019 /* the window is still deferred. Make it very small, bring it
1020 on screen and order it out. */
1021 NSRect s = { { 100, 100}, {0, 0} };
1023 t = [[view window] frame];
1024 [[view window] setFrame: s display: NO];
1025 [[view window] orderBack: NSApp];
1026 [[view window] orderOut: NSApp];
1027 [[view window] setFrame: t display: NO];
1029 [[view window] miniaturize: NSApp];
1034 x_destroy_window (struct frame *f)
1035 /* --------------------------------------------------------------------------
1036 External: Delete the window
1037 -------------------------------------------------------------------------- */
1039 NSView *view = FRAME_NS_VIEW (f);
1040 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1041 NSTRACE (x_destroy_window);
1044 [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1048 free_frame_menubar (f);
1050 if (FRAME_FACE_CACHE (f))
1051 free_frame_faces (f);
1053 if (f == dpyinfo->x_focus_frame)
1054 dpyinfo->x_focus_frame = 0;
1055 if (f == dpyinfo->x_highlight_frame)
1056 dpyinfo->x_highlight_frame = 0;
1057 if (f == dpyinfo->mouse_face_mouse_frame)
1059 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
1060 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
1061 dpyinfo->mouse_face_window = Qnil;
1062 dpyinfo->mouse_face_deferred_gc = 0;
1063 dpyinfo->mouse_face_mouse_frame = 0;
1066 xfree (f->output_data.ns);
1068 [[view window] close];
1077 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1078 /* --------------------------------------------------------------------------
1079 External: Position the window
1080 -------------------------------------------------------------------------- */
1083 NSView *view = FRAME_NS_VIEW (f);
1085 NSTRACE (x_set_offset);
1091 #ifdef NS_IMPL_GNUSTEP
1093 f->left_pos = 100; /* don't overlap menu */
1095 if (view != nil && (screen = [[view window] screen]))
1096 [[view window] setFrameTopLeftPoint:
1097 NSMakePoint (SCREENMAXBOUND (f->left_pos),
1098 SCREENMAXBOUND ([screen frame].size.height
1099 - NS_TOP_POS (f)))];
1105 x_set_window_size (struct frame *f, int change_grav, int cols, int rows)
1106 /* --------------------------------------------------------------------------
1107 Adjust window pixel size based on given character grid size
1108 Impl is a bit more complex than other terms, need to do some
1109 internal clipping and also pay attention to screen constraints.
1110 -------------------------------------------------------------------------- */
1112 EmacsView *view = FRAME_NS_VIEW (f);
1113 EmacsToolbar *toolbar = [view toolbar];
1114 NSWindow *window = [view window];
1115 NSScreen *screen = [window screen];
1116 NSRect wr = [window frame];
1117 int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1118 int pixelwidth, pixelheight;
1119 static int oldRows, oldCols, oldFontWidth, oldFontHeight;
1121 static struct frame *oldF;
1123 NSTRACE (x_set_window_size);
1127 && rows == oldRows && cols == oldCols
1128 && oldFontWidth == FRAME_COLUMN_WIDTH (f)
1129 && oldFontHeight == FRAME_LINE_HEIGHT (f)
1133 /*fprintf (stderr, "\tsetWindowSize: %d x %d, font size %d x %d\n", cols, rows, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f)); */
1137 check_frame_size (f, &rows, &cols);
1141 oldFontWidth = FRAME_COLUMN_WIDTH (f);
1142 oldFontHeight = FRAME_LINE_HEIGHT (f);
1145 f->scroll_bar_actual_width = NS_SCROLL_BAR_WIDTH (f);
1146 compute_fringe_widths (f, 0);
1148 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols);
1149 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
1151 /* If we have a change in toolbar display, calculate height */
1153 /* XXX: GNUstep has not yet implemented the first method below, added
1154 in Panther, however the second is incorrect under Cocoa. */
1155 #ifdef NS_IMPL_GNUSTEP
1156 FRAME_NS_TOOLBAR_HEIGHT (f)
1157 = NSHeight ([NSWindow frameRectForContentRect: NSMakeRect (0, 0, 0, 0)
1158 styleMask: [window styleMask]])
1159 - FRAME_NS_TITLEBAR_HEIGHT (f);
1161 FRAME_NS_TOOLBAR_HEIGHT (f) = 32;
1162 /* actually get wrong result here if toolbar not yet displayed
1163 NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1164 - FRAME_NS_TITLEBAR_HEIGHT (f); */
1167 FRAME_NS_TOOLBAR_HEIGHT (f) = 0;
1169 wr.size.width = pixelwidth + f->border_width;
1170 wr.size.height = pixelheight + FRAME_NS_TITLEBAR_HEIGHT (f)
1171 + FRAME_NS_TOOLBAR_HEIGHT (f);
1173 /* constrain to screen if we can */
1176 NSSize sz = [screen visibleFrame].size;
1177 NSSize ez = { wr.size.width - sz.width, wr.size.height - sz.height };
1180 int cr = ez.width / FRAME_COLUMN_WIDTH (f) + 1;
1183 wr.size.width -= cr * FRAME_COLUMN_WIDTH (f);
1184 pixelwidth -= cr * FRAME_COLUMN_WIDTH (f);
1188 int rr = ez.height / FRAME_LINE_HEIGHT (f) + 1;
1191 wr.size.height -= rr * FRAME_LINE_HEIGHT (f);
1192 pixelheight -= rr * FRAME_LINE_HEIGHT (f);
1194 wr.origin.x = f->left_pos;
1195 wr.origin.y = [screen frame].size.height - NS_TOP_POS (f)
1199 [view setRows: rows andColumns: cols];
1200 [window setFrame: wr display: YES];
1202 /*fprintf (stderr, "\tx_set_window_size %d, %d\t%d, %d\n", cols, rows, pixelwidth, pixelheight); */
1204 /* This is a trick to compensate for Emacs' managing the scrollbar area
1205 as a fixed number of standard character columns. Instead of leaving
1206 blank space for the extra, we chopped it off above. Now for
1207 left-hand scrollbars, we shift all rendering to the left by the
1208 difference between the real width and Emacs' imagined one. For
1209 right-hand bars, don't worry about it since the extra is never used.
1210 (Obviously doesn't work for vertically split windows tho..) */
1211 NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1212 ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1213 - NS_SCROLL_BAR_WIDTH (f), 0)
1214 : NSMakePoint (0, 0);
1215 [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1216 [view setBoundsOrigin: origin];
1218 change_frame_size (f, rows, cols, 0, 1, 0); /* pretend, delay, safe */
1219 FRAME_PIXEL_WIDTH (f) = pixelwidth;
1220 FRAME_PIXEL_HEIGHT (f) = pixelheight;
1221 /* SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */
1223 mark_window_cursors_off (XWINDOW (f->root_window));
1224 cancel_mouse_face (f);
1230 /* ==========================================================================
1234 ========================================================================== */
1237 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1239 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1240 return color_table->colors[idx];
1245 ns_index_color (NSColor *color, struct frame *f)
1247 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1251 if (!color_table->colors)
1253 color_table->size = NS_COLOR_CAPACITY;
1254 color_table->avail = 1; /* skip idx=0 as marker */
1256 = (NSColor **)xmalloc (color_table->size * sizeof (NSColor *));
1257 color_table->empty_indices = [[NSMutableSet alloc] init];
1260 /* do we already have this color ? */
1263 for (i = 1; i < color_table->avail; i++)
1265 if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1267 [color_table->colors[i] retain];
1273 if ([color_table->empty_indices count] > 0)
1275 index = [color_table->empty_indices anyObject];
1276 [color_table->empty_indices removeObject: index];
1277 idx = [index unsignedIntValue];
1281 if (color_table->avail == color_table->size)
1283 color_table->size += NS_COLOR_CAPACITY;
1285 = (NSColor **)xrealloc (color_table->colors,
1286 color_table->size * sizeof (NSColor *));
1288 idx = color_table->avail++;
1289 index = [NSNumber numberWithUnsignedInt: idx];
1292 color_table->colors[idx] = color;
1294 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1300 ns_free_indexed_color (unsigned long idx, struct frame *f)
1302 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1306 color = color_table->colors[idx];
1308 color_table->colors[idx] = nil;
1309 [color_table->empty_indices addObject: [NSNumber numberWithUnsignedInt: idx]];
1310 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1315 ns_get_color (const char *name, NSColor **col)
1316 /* --------------------------------------------------------------------------
1318 /* --------------------------------------------------------------------------
1319 /* On *Step, we recognize several color formats, in addition to a catalog
1320 of colors found in the file Emacs.clr. Color formats include:
1321 - #rrggbb or RGBrrggbb where rr, gg, bb specify red, green and blue in hex
1322 - ARGBaarrggbb is similar, with aa being the alpha channel (FF = opaque)
1323 - HSVhhssvv and AHSVaahhssvv (or HSB/AHSB) are similar for hue, saturation,
1325 - CMYKccmmyykk is similar for cyan, magenta, yellow, black. */
1327 NSColor * new = nil;
1328 const char *hex = NULL;
1329 enum { rgb, argb, hsv, ahsv, cmyk, gray } color_space;
1330 NSString *nsname = [NSString stringWithUTF8String: name];
1332 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1335 if ([nsname isEqualToString: @"ns_selection_color"])
1337 nsname = ns_selection_color;
1338 name = [ns_selection_color UTF8String];
1341 if (name[0] == '0' || name[0] == '1' || name[0] == '.')
1344 NSScanner *scanner = [NSScanner scannerWithString: nsname];
1346 [scanner scanFloat: &r];
1347 [scanner scanFloat: &g];
1348 [scanner scanFloat: &b];
1349 *col = [NSColor colorWithCalibratedRed: r green: g blue: b alpha: 1.0];
1354 /* 23: FIXME: emacs seems to downcase everything before passing it here,
1355 which we can work around, except for GRAY, since gray##, where ## is
1356 decimal between 0 and 99, is also an X11 colorname. */
1357 if (name[0] == '#') /* X11 format */
1362 else if (!memcmp (name, "RGB", 3) || !memcmp (name, "rgb", 3))
1367 else if (!memcmp (name, "ARGB", 4) || !memcmp (name, "argb", 4))
1372 else if (!memcmp (name, "HSV", 3) || !memcmp (name, "hsv", 3) ||
1373 !memcmp (name, "HSB", 3) || !memcmp (name, "hsb", 3))
1378 else if (!memcmp (name, "AHSV", 4) || !memcmp (name, "ahsv", 4) ||
1379 !memcmp (name, "AHSB", 4) || !memcmp (name, "ahsb", 4))
1384 else if (!memcmp (name, "CMYK", 4) || !memcmp (name, "cmyk", 4))
1389 else if (!memcmp (name, "GRAY", 4) /*|| !memcmp (name, "gray", 4)*/)
1395 /* Direct colors (hex values) */
1398 unsigned int color = 0;
1399 if (sscanf (hex, "%x", &color))
1401 float f1 = ((color >> 24) & 0xff) / 255.0;
1402 float f2 = ((color >> 16) & 0xff) / 255.0;
1403 float f3 = ((color >> 8) & 0xff) / 255.0;
1404 float f4 = ((color ) & 0xff) / 255.0;
1406 switch (color_space)
1409 *col = [NSColor colorWithCalibratedRed: f2
1415 *col = [NSColor colorWithCalibratedRed: f2
1421 *col = [NSColor colorWithCalibratedHue: f2
1427 *col = [NSColor colorWithCalibratedHue: f2
1433 *col = [NSColor colorWithCalibratedWhite: f3 alpha: f4];
1436 *col = [NSColor colorWithDeviceCyan: f1
1443 *col = [*col colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1449 /* Otherwise, color is expected to be from a list */
1451 NSEnumerator *lenum, *cenum;
1455 #ifdef NS_IMPL_GNUSTEP
1456 /* XXX: who is wrong, the requestor or the implementation? */
1457 if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1459 nsname = @"highlightColor";
1462 lenum = [[NSColorList availableColorLists] objectEnumerator];
1463 while ( (clist = [lenum nextObject]) && new == nil)
1465 cenum = [[clist allKeys] objectEnumerator];
1466 while ( (name = [cenum nextObject]) && new == nil )
1468 if ([name compare: nsname
1469 options: NSCaseInsensitiveSearch] == NSOrderedSame )
1470 new = [clist colorWithKey: name];
1476 *col = [new colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1478 NSLog (@"Failed to find color '%@'", nsname); */
1485 ns_get_color_default (const char *name, NSColor *dflt)
1486 /* --------------------------------------------------------------------------
1487 Parse a color or use a default value
1488 -------------------------------------------------------------------------- */
1492 if (ns_get_color (name, &col))
1500 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1501 /* --------------------------------------------------------------------------
1502 Convert a Lisp string object to a NS color
1503 -------------------------------------------------------------------------- */
1505 NSTRACE (ns_lisp_to_color);
1506 if (STRINGP (color))
1507 return ns_get_color (SDATA (color), col);
1508 else if (SYMBOLP (color))
1509 return ns_get_color (SDATA (SYMBOL_NAME (color)), col);
1515 ns_color_to_lisp (NSColor *col)
1516 /* --------------------------------------------------------------------------
1517 Convert a color to a lisp string with the RGB equivalent
1518 -------------------------------------------------------------------------- */
1520 float red, green, blue, alpha, gray;
1523 NSTRACE (ns_color_to_lisp);
1526 if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1528 if ((str =[[col colorNameComponent] UTF8String]))
1531 return build_string ((char *)str);
1534 [[col colorUsingColorSpaceName: NSCalibratedRGBColorSpace]
1535 getRed: &red green: &green blue: &blue alpha: &alpha];
1536 if (red ==green && red ==blue)
1538 [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1539 getWhite: &gray alpha: &alpha];
1540 snprintf (buf, sizeof (buf), "GRAY%02.2lx%02.2lx",
1541 lrint (gray * 0xff), lrint (alpha * 0xff));
1543 return build_string (buf);
1546 snprintf (buf, sizeof (buf), "ARGB%02.2lx%02.2lx%02.2lx%02.2lx",
1548 lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1551 return build_string (buf);
1556 ns_defined_color (struct frame *f, char *name, XColor *color_def, int alloc,
1558 /* --------------------------------------------------------------------------
1559 23: Return 1 if named color found, and set color_def rgb accordingly.
1560 If makeIndex and alloc are nonzero put the color in the color_table,
1561 and set color_def pixel to the resulting index.
1562 If makeIndex is zero, set color_def pixel to ARGB.
1563 Return 0 if not found
1564 -------------------------------------------------------------------------- */
1568 int notFound = ns_get_color (name, &temp);
1570 NSTRACE (ns_defined_color);
1575 if (makeIndex && alloc)
1576 color_def->pixel = ns_index_color(temp, f); /* [temp retain]; */
1578 [temp getRed: &r green: &g blue: &b alpha: &a];
1579 color_def->red = r * 256;
1580 color_def->green = g * 256;
1581 color_def->blue = b * 256;
1585 = ARGB_TO_ULONG((int)(a*256),
1586 color_def->red, color_def->green, color_def->blue);
1593 ns_get_rgb_color (struct frame *f, float r, float g, float b, float a)
1594 /* --------------------------------------------------------------------------
1595 return an autoreleased RGB color
1596 -------------------------------------------------------------------------- */
1598 /*static int c = 1; fprintf (stderr, "color request %d\n", c++); */
1599 if (r < 0.0) r = 0.0;
1600 else if (r > 1.0) r = 1.0;
1601 if (g < 0.0) g = 0.0;
1602 else if (g > 1.0) g = 1.0;
1603 if (b < 0.0) b = 0.0;
1604 else if (b > 1.0) b = 1.0;
1605 if (a < 0.0) a = 0.0;
1606 else if (a > 1.0) a = 1.0;
1607 return (unsigned long) ns_index_color(
1608 [NSColor colorWithCalibratedRed: r green: g blue: b alpha: a], f);
1613 /* ==========================================================================
1617 ========================================================================== */
1621 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1622 /* --------------------------------------------------------------------------
1623 Programmatically reposition mouse pointer in pixel coordinates
1624 -------------------------------------------------------------------------- */
1626 NSTRACE (x_set_mouse_pixel_position);
1629 /* FIXME: this does not work, and what about GNUstep? */
1630 #ifdef NS_IMPL_COCOA
1631 [FRAME_NS_VIEW (f) lockFocus];
1632 PSsetmouse ((float)pix_x, (float)pix_y);
1633 [FRAME_NS_VIEW (f) unlockFocus];
1640 x_set_mouse_position (struct frame *f, int h, int v)
1641 /* --------------------------------------------------------------------------
1642 Programmatically reposition mouse pointer in character coordinates
1643 -------------------------------------------------------------------------- */
1647 pix_x = FRAME_COL_TO_PIXEL_X (f, h) + FRAME_COLUMN_WIDTH (f) / 2;
1648 pix_y = FRAME_LINE_TO_PIXEL_Y (f, v) + FRAME_LINE_HEIGHT (f) / 2;
1650 if (pix_x < 0) pix_x = 0;
1651 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
1653 if (pix_y < 0) pix_y = 0;
1654 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
1656 x_set_mouse_pixel_position (f, pix_x, pix_y);
1661 note_mouse_movement (struct frame *frame, float x, float y)
1662 /* ------------------------------------------------------------------------
1663 Called by EmacsView on mouseMovement events. Passes on
1664 to emacs mainstream code if we moved off of a rect of interest
1665 known as last_mouse_glyph.
1666 ------------------------------------------------------------------------ */
1668 NSTRACE (note_mouse_movement);
1670 XSETFRAME (last_mouse_motion_frame, frame);
1672 /* Note, this doesn't get called for enter/leave, since we don't have a
1673 position. Those are taken care of in the corresponding NSView methods. */
1675 /* has movement gone beyond last rect we were tracking? */
1676 if (x < last_mouse_glyph.origin.x ||
1677 x >= (last_mouse_glyph.origin.x + last_mouse_glyph.size.width) ||
1678 y < last_mouse_glyph.origin.y ||
1679 y >= (last_mouse_glyph.origin.y + last_mouse_glyph.size.height))
1681 frame->mouse_moved = 1;
1682 note_mouse_highlight (frame, x, y);
1683 remember_mouse_glyph (frame, x, y, &last_mouse_glyph);
1692 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1693 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1694 unsigned long *time)
1695 /* --------------------------------------------------------------------------
1696 External (hook): inform emacs about mouse position and hit parts.
1697 If a scrollbar is being dragged, set bar_window, part, x, y, time.
1698 x & y should be position in the scrollbar (the whole bar, not the handle)
1699 and length of scrollbar respectively
1700 -------------------------------------------------------------------------- */
1705 Lisp_Object frame, tail;
1707 struct ns_display_info *dpyinfo;
1709 NSTRACE (ns_mouse_position);
1713 fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1717 dpyinfo = FRAME_NS_DISPLAY_INFO (*fp);
1721 if (last_mouse_scroll_bar != nil && insist == 0)
1723 /* TODO: we do not use this path at the moment because drag events will
1724 go directly to the EmacsScroller. Leaving code in for now. */
1725 [last_mouse_scroll_bar getMouseMotionPart: (int *)part window: bar_window
1727 if (time) *time = last_mouse_movement_time;
1728 last_mouse_scroll_bar = nil;
1732 /* Clear the mouse-moved flag for every frame on this display. */
1733 FOR_EACH_FRAME (tail, frame)
1734 if (FRAME_NS_P (XFRAME (frame))
1735 && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1736 XFRAME (frame)->mouse_moved = 0;
1738 last_mouse_scroll_bar = nil;
1739 if (last_mouse_frame && FRAME_LIVE_P (last_mouse_frame))
1740 f = last_mouse_frame;
1742 f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame
1743 : SELECTED_FRAME ();
1745 if (f && f->output_data.ns) /* TODO: 2nd check no longer needed? */
1747 view = FRAME_NS_VIEW (*fp);
1749 position = [[view window] mouseLocationOutsideOfEventStream];
1750 position = [view convertPoint: position fromView: nil];
1751 remember_mouse_glyph (f, position.x, position.y, &last_mouse_glyph);
1752 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1754 if (bar_window) *bar_window = Qnil;
1755 if (part) *part = 0; /*scroll_bar_handle; */
1757 if (x) XSETINT (*x, lrint (position.x));
1758 if (y) XSETINT (*y, lrint (position.y));
1759 if (time) *time = last_mouse_movement_time;
1769 ns_frame_up_to_date (struct frame *f)
1770 /* --------------------------------------------------------------------------
1771 External (hook): Fix up mouse highlighting right after a full update.
1772 Some highlighting was deferred if GC was happening during
1773 note_mouse_highlight (), while other highlighting was deferred for update.
1774 -------------------------------------------------------------------------- */
1776 NSTRACE (ns_frame_up_to_date);
1780 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1781 if ((dpyinfo->mouse_face_deferred_gc||f ==dpyinfo->mouse_face_mouse_frame)
1782 /*&& dpyinfo->mouse_face_mouse_frame*/)
1785 if (dpyinfo->mouse_face_mouse_frame)
1786 note_mouse_highlight (dpyinfo->mouse_face_mouse_frame,
1787 dpyinfo->mouse_face_mouse_x,
1788 dpyinfo->mouse_face_mouse_y);
1789 dpyinfo->mouse_face_deferred_gc = 0;
1797 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1798 /* --------------------------------------------------------------------------
1799 External (RIF): set frame mouse pointer type.
1800 -------------------------------------------------------------------------- */
1802 NSTRACE (ns_define_frame_cursor);
1803 if (FRAME_POINTER_TYPE (f) != cursor)
1805 EmacsView *view = FRAME_NS_VIEW (f);
1806 FRAME_POINTER_TYPE (f) = cursor;
1807 [[view window] invalidateCursorRectsForView: view];
1813 /* ==========================================================================
1817 ========================================================================== */
1821 ns_convert_key (unsigned code)
1822 /* --------------------------------------------------------------------------
1823 Internal call used by NSView-keyDown.
1824 -------------------------------------------------------------------------- */
1826 const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym)
1827 / sizeof (convert_ns_to_X_keysym[0]));
1829 /* An array would be faster, but less easy to read. */
1830 for (keysym = 0; keysym < last_keysym; keysym += 2)
1831 if (code == convert_ns_to_X_keysym[keysym])
1832 return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
1834 /* if decide to use keyCode and Carbon table, use this line:
1835 return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
1840 x_get_keysym_name (int keysym)
1841 /* --------------------------------------------------------------------------
1842 Called by keyboard.c. Not sure if the return val is important, except
1844 -------------------------------------------------------------------------- */
1846 static char value[16];
1847 NSTRACE (x_get_keysym_name);
1848 sprintf (value, "%d", keysym);
1854 /* ==========================================================================
1856 Block drawing operations
1858 ========================================================================== */
1862 ns_redraw_scroll_bars (struct frame *f)
1866 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
1867 NSTRACE (ns_judge_scroll_bars);
1868 for (i =[subviews count]-1; i >= 0; i--)
1870 view = [subviews objectAtIndex: i];
1871 if (![view isKindOfClass: [EmacsScroller class]]) continue;
1878 ns_clear_frame (struct frame *f)
1879 /* --------------------------------------------------------------------------
1880 External (hook): Erase the entire frame
1881 -------------------------------------------------------------------------- */
1883 NSView *view = FRAME_NS_VIEW (f);
1886 NSTRACE (ns_clear_frame);
1890 /* comes on initial frame because we have
1891 after-make-frame-functions = select-frame */
1892 if (!FRAME_DEFAULT_FACE (f))
1895 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
1897 output_cursor.hpos = output_cursor.vpos = 0;
1898 output_cursor.x = -1;
1903 ns_focus (f, &r, 1);
1904 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
1908 #ifdef NS_IMPL_COCOA
1909 [[view window] display]; /* redraw resize handle */
1912 /* as of 2006/11 or so this is now needed */
1913 ns_redraw_scroll_bars (f);
1919 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
1920 /* --------------------------------------------------------------------------
1921 23: External (RIF): Clear section of frame
1922 -------------------------------------------------------------------------- */
1924 NSRect r = NSMakeRect (x, y, width, height);
1925 NSView *view = FRAME_NS_VIEW (f);
1926 struct face *face = FRAME_DEFAULT_FACE (f);
1931 r = NSIntersectionRect (r, [view frame]);
1932 ns_focus (f, &r, 1);
1933 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
1935 #ifdef NS_IMPL_COCOA
1937 /* clip out the resize handle */
1938 NSWindow *window = [FRAME_NS_VIEW (f) window];
1940 = [view convertRect: ns_resize_handle_rect (window) fromView: nil];
1942 ir = NSIntersectionRect (r, ir);
1943 if (NSIsEmptyRect (ir))
1949 #ifdef NS_IMPL_COCOA
1953 NSRect r1 = r, r2 = r; /* upper and lower non-intersecting */
1954 r1.size.height -= ir.size.height;
1955 r2.origin.y += r1.size.height;
1956 r2.size.width -= ir.size.width;
1957 r2.size.height = ir.size.height;
1970 ns_scroll_run (struct window *w, struct run *run)
1971 /* --------------------------------------------------------------------------
1972 23: External (RIF): Insert or delete n lines at line vpos
1973 -------------------------------------------------------------------------- */
1975 struct frame *f = XFRAME (w->frame);
1976 int x, y, width, height, from_y, to_y, bottom_y;
1978 NSTRACE (ns_scroll_run);
1980 /* begin copy from other terms */
1981 /* Get frame-relative bounding box of the text display area of W,
1982 without mode lines. Include in this box the left and right
1984 window_box (w, -1, &x, &y, &width, &height);
1986 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
1987 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
1988 bottom_y = y + height;
1992 /* Scrolling up. Make sure we don't copy part of the mode
1993 line at the bottom. */
1994 if (from_y + run->height > bottom_y)
1995 height = bottom_y - from_y;
1997 height = run->height;
2001 /* Scolling down. Make sure we don't copy over the mode line.
2003 if (to_y + run->height > bottom_y)
2004 height = bottom_y - to_y;
2006 height = run->height;
2008 /* end copy from other terms */
2019 NSRect srcRect = NSMakeRect (x, from_y, width, height);
2020 NSRect dstRect = NSMakeRect (x, to_y, width, height);
2021 NSPoint dstOrigin = NSMakePoint (x, to_y);
2023 ns_focus (f, &dstRect, 1);
2024 NSCopyBits (0, srcRect , dstOrigin);
2033 ns_after_update_window_line (struct glyph_row *desired_row)
2034 /* --------------------------------------------------------------------------
2035 23: External (RIF): preparatory to fringe update after text was updated
2036 -------------------------------------------------------------------------- */
2038 struct window *w = updated_window;
2042 NSTRACE (ns_after_update_window_line);
2044 /* begin copy from other terms */
2047 if (!desired_row->mode_line_p && !w->pseudo_window_p)
2048 desired_row->redraw_fringe_bitmaps_p = 1;
2050 /* When a window has disappeared, make sure that no rest of
2051 full-width rows stays visible in the internal border.
2052 Under NS this is drawn inside the fringes. */
2053 if (windows_or_buffers_changed
2054 && (f = XFRAME (w->frame),
2055 width = FRAME_INTERNAL_BORDER_WIDTH (f),
2057 && (height = desired_row->visible_height,
2060 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2062 /* Internal border is drawn below the tool bar. */
2063 if (WINDOWP (f->tool_bar_window)
2064 && w == XWINDOW (f->tool_bar_window))
2066 /* end copy from other terms */
2069 if (!desired_row->full_width_p)
2071 int x1 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2072 + WINDOW_LEFT_FRINGE_WIDTH (w);
2073 int x2 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2074 + FRAME_PIXEL_WIDTH (f) - NS_SCROLL_BAR_WIDTH (f)
2075 - WINDOW_RIGHT_FRINGE_WIDTH (w)
2076 - FRAME_INTERNAL_BORDER_WIDTH (f);
2077 ns_clear_frame_area (f, x1, y, width, height);
2078 ns_clear_frame_area (f, x2, y, width, height);
2086 ns_shift_glyphs_for_insert (struct frame *f,
2087 int x, int y, int width, int height,
2089 /* --------------------------------------------------------------------------
2090 23: External (RIF): copy an area horizontally, don't worry about clearing src
2091 -------------------------------------------------------------------------- */
2093 NSRect srcRect = NSMakeRect (x, y, width, height);
2094 NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2095 NSPoint dstOrigin = dstRect.origin;
2097 NSTRACE (ns_shift_glyphs_for_insert);
2099 ns_focus (f, &dstRect, 1);
2100 NSCopyBits (0, srcRect, dstOrigin);
2106 /* ==========================================================================
2108 Character encoding and metrics
2110 ========================================================================== */
2114 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2115 /* --------------------------------------------------------------------------
2116 23: External (RIF); compute left/right overhang of whole string and set in s
2117 -------------------------------------------------------------------------- */
2119 struct face *face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2120 struct font *font = s->font; /*face->font; */
2124 struct font_metrics metrics;
2125 unsigned int codes[2];
2126 codes[0] = *(s->char2b);
2127 codes[1] = *(s->char2b + s->nchars - 1);
2129 font->driver->text_extents (font, codes, 2, &metrics);
2130 s->left_overhang = -metrics.lbearing;
2132 = metrics.rbearing > metrics.width
2133 ? metrics.rbearing - metrics.width : 0;
2137 s->left_overhang = 0;
2138 s->right_overhang = ((struct nsfont_info *)font)->ital ?
2139 FONT_HEIGHT (font) * 0.2 : 0;
2145 /* ==========================================================================
2147 Fringe and cursor drawing
2149 ========================================================================== */
2152 extern int max_used_fringe_bitmap;
2154 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2155 struct draw_fringe_bitmap_params *p)
2156 /* --------------------------------------------------------------------------
2157 23: External (RIF); fringe-related
2158 -------------------------------------------------------------------------- */
2160 struct frame *f = XFRAME (WINDOW_FRAME (w));
2161 struct face *face = p->face;
2163 static EmacsImage **bimgs = NULL;
2164 static int nBimgs = 0;
2165 /* NS-specific: move internal border inside fringe */
2166 int x = p->bx < 0 ? p->x : p->bx;
2167 int wd = p->bx < 0 ? p->wd : p->nx;
2168 BOOL fringeOnVeryLeft
2169 = x - WINDOW_LEFT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w)
2170 - FRAME_INTERNAL_BORDER_WIDTH (f) < 10;
2171 BOOL fringeOnVeryRight
2172 = FRAME_PIXEL_WIDTH (f) - x - wd - FRAME_INTERNAL_BORDER_WIDTH (f)
2173 - WINDOW_RIGHT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w) < 10;
2174 int xAdjust = FRAME_INTERNAL_BORDER_WIDTH (f) *
2175 (fringeOnVeryLeft ? -1 : (fringeOnVeryRight ? 1 : 0));
2177 /* grow bimgs if needed */
2178 if (nBimgs < max_used_fringe_bitmap)
2180 EmacsImage **newBimgs
2181 = xmalloc (max_used_fringe_bitmap * sizeof (EmacsImage *));
2182 bzero (newBimgs, max_used_fringe_bitmap * sizeof (EmacsImage *));
2186 bcopy (bimgs, newBimgs, nBimgs * sizeof (EmacsImage *));
2191 nBimgs = max_used_fringe_bitmap;
2194 /* Must clip because of partially visible lines. */
2195 rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
2198 /* Adjust position of "bottom aligned" bitmap on partially
2199 visible last row. */
2201 int oldVH = row->visible_height;
2202 row->visible_height = p->h;
2203 row->y -= rowY - p->y;
2204 ns_clip_to_row (w, row, -1, NO);
2206 row->visible_height = oldVH;
2209 ns_clip_to_row (w, row, -1, YES);
2211 if (p->bx >= 0 && !p->overlay_p)
2213 int yAdjust = rowY - FRAME_INTERNAL_BORDER_WIDTH (f) < 5 ?
2214 -FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2215 int yIncr = FRAME_PIXEL_HEIGHT (f) - (p->by+yAdjust + p->ny) < 5 ?
2216 FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2218 yIncr += FRAME_INTERNAL_BORDER_WIDTH (f);
2219 NSRect r = NSMakeRect (p->bx+xAdjust, p->by+yAdjust, p->nx, p->ny+yIncr);
2221 [ns_lookup_indexed_color(face->background, f) set];
2227 NSRect r = NSMakeRect (p->x+xAdjust, p->y, p->wd, p->h);
2228 NSPoint pt = r.origin;
2229 EmacsImage *img = bimgs[p->which - 1];
2233 unsigned short *bits = p->bits + p->dh;
2234 int len = 8 * p->h/8;
2236 unsigned char *cbits = xmalloc (len);
2238 for (i =0; i<len; i++)
2239 cbits[i] = ~(bits[i] & 0xff);
2240 img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2242 bimgs[p->which - 1] = img;
2247 /* Since we composite the bitmap instead of just blitting it, we need
2248 to erase the whole background. */
2249 [ns_lookup_indexed_color(face->background, f) set];
2252 [img setXBMColor: ns_lookup_indexed_color(face->foreground, f)];
2253 [img compositeToPoint: pt operation: NSCompositeSourceOver];
2260 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2261 int x, int y, int cursor_type, int cursor_width,
2262 int on_p, int active_p)
2263 /* --------------------------------------------------------------------------
2264 External call (RIF): draw cursor
2265 (modeled after x_draw_window_cursor and erase_phys_cursor.
2266 FIXME: erase_phys_cursor is called from display_and_set_cursor,
2267 called from update_window_cursor/x_update_window_end/...
2268 Why do we have to duplicate this code?
2269 -------------------------------------------------------------------------- */
2273 struct frame *f = WINDOW_XFRAME (w);
2274 struct glyph *phys_cursor_glyph;
2276 char drawGlyph = 0, cursorType, oldCursorType;
2277 int new_cursor_type;
2278 int new_cursor_width;
2280 enum draw_glyphs_face hl;
2281 struct glyph_matrix *active_glyphs = w->current_matrix;
2282 Display_Info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
2283 int hpos = w->phys_cursor.hpos;
2284 int vpos = w->phys_cursor.vpos;
2285 struct glyph_row *cursor_row;
2287 NSTRACE (dumpcursor);
2289 if (!on_p) // check this? && !w->phys_cursor_on_p)
2292 w->phys_cursor_type = cursor_type;
2293 w->phys_cursor_on_p = on_p;
2295 if (cursor_type == NO_CURSOR)
2297 w->phys_cursor_on_p = 0;
2298 w->phys_cursor_width = 0;
2302 if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2304 if (glyph_row->exact_window_width_line_p
2305 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2307 glyph_row->cursor_in_fringe_p = 1;
2308 draw_fringe_bitmap (w, glyph_row, 0);
2313 get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2315 r.origin.x = fx, r.origin.y = fy;
2317 r.size.width = w->phys_cursor_width;
2319 /* FIXME: if we overwrite the internal border area, it does not get erased;
2320 fix by truncating cursor, but better would be to erase properly */
2321 overspill = r.origin.x + r.size.width -
2322 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, WINDOW_BOX_RIGHT_EDGE_X (w)
2323 - WINDOW_TOTAL_FRINGE_WIDTH (w) - FRAME_INTERNAL_BORDER_WIDTH (f));
2325 r.size.width -= overspill;
2327 oldCursorType = FRAME_CURSOR (f);
2328 cursorType = FRAME_CURSOR (f) = FRAME_NEW_CURSOR (f);
2329 /* TODO: 23: use emacs stored cursor color instead of ns-specific */
2330 f->output_data.ns->current_cursor_color
2331 = f->output_data.ns->desired_cursor_color;
2333 /* TODO: only needed in rare cases with last-resort font in HELLO..
2334 should we do this more efficiently? */
2335 ns_clip_to_row (w, glyph_row, -1, NO);
2336 /* ns_focus (f, &r, 1); */
2338 /* Why would this be needed?
2339 if (FRAME_LAST_INACTIVE (f))
2341 * previously hollow box; clear entire area *
2342 [FRAME_BACKGROUND_COLOR (f) set];
2345 FRAME_LAST_INACTIVE (f) = NO;
2349 /* prepare to draw */
2350 if (cursorType == no_highlight || cursor_type == NO_CURSOR)
2352 /* clearing for blink: erase the cursor itself */
2354 /* No cursor displayed or row invalidated => nothing to do on the
2356 if (w->phys_cursor_type == NO_CURSOR)
2359 /* VPOS >= active_glyphs->nrows means that window has been resized.
2360 Don't bother to erase the cursor. */
2361 if (vpos >= active_glyphs->nrows)
2364 /* If row containing cursor is marked invalid, there is nothing we
2366 cursor_row = MATRIX_ROW (active_glyphs, vpos);
2367 if (!cursor_row->enabled_p)
2370 /* If line spacing is > 0, old cursor may only be partially visible in
2371 window after split-window. So adjust visible height. */
2372 cursor_row->visible_height = min (cursor_row->visible_height,
2373 window_text_bottom_y (w) - cursor_row->y);
2375 /* If row is completely invisible, don't attempt to delete a cursor which
2376 isn't there. This can happen if cursor is at top of a window, and
2377 we switch to a buffer with a header line in that window. */
2378 if (cursor_row->visible_height <= 0)
2381 /* If cursor is in the fringe, erase by drawing actual bitmap there. */
2382 if (cursor_row->cursor_in_fringe_p)
2384 cursor_row->cursor_in_fringe_p = 0;
2385 draw_fringe_bitmap (w, cursor_row, 0);
2389 /* This can happen when the new row is shorter than the old one.
2390 In this case, either draw_glyphs or clear_end_of_line
2391 should have cleared the cursor. Note that we wouldn't be
2392 able to erase the cursor in this case because we don't have a
2393 cursor glyph at hand. */
2394 if (w->phys_cursor.hpos >= cursor_row->used[TEXT_AREA])
2397 /* If the cursor is in the mouse face area, redisplay that when
2398 we clear the cursor. */
2399 if (! NILP (dpyinfo->mouse_face_window)
2400 && w == XWINDOW (dpyinfo->mouse_face_window)
2401 && (vpos > dpyinfo->mouse_face_beg_row
2402 || (vpos == dpyinfo->mouse_face_beg_row
2403 && hpos >= dpyinfo->mouse_face_beg_col))
2404 && (vpos < dpyinfo->mouse_face_end_row
2405 || (vpos == dpyinfo->mouse_face_end_row
2406 && hpos < dpyinfo->mouse_face_end_col))
2407 /* Don't redraw the cursor's spot in mouse face if it is at the
2408 end of a line (on a newline). The cursor appears there, but
2409 mouse highlighting does not. */
2410 && cursor_row->used[TEXT_AREA] > hpos)
2411 hl = DRAW_MOUSE_FACE;
2413 hl = DRAW_NORMAL_TEXT;
2414 drawGlyph = 1; // just draw the Glyph
2415 [FRAME_BACKGROUND_COLOR (f) set];
2417 #ifdef NS_IMPL_COCOA
2418 NSDisableScreenUpdates ();
2423 cursorType = cursor_type;
2425 [FRAME_CURSOR_COLOR (f) set];
2430 /* inactive window: ignore what we just set and use a hollow box */
2431 cursorType = HOLLOW_BOX_CURSOR;
2434 #ifdef NS_IMPL_COCOA
2435 NSDisableScreenUpdates ();
2440 case NO_CURSOR: // no_highlight:
2442 case FILLED_BOX_CURSOR: //filled_box:
2446 case HOLLOW_BOX_CURSOR: //hollow_box:
2448 [FRAME_BACKGROUND_COLOR (f) set];
2449 NSRectFill (NSInsetRect (r, 1, 1));
2450 [FRAME_CURSOR_COLOR (f) set];
2453 case HBAR_CURSOR: // underscore:
2455 s.origin.y += lrint (0.75 * s.size.height);
2456 s.size.height = cursor_width; //lrint (s.size.height * 0.25);
2459 case BAR_CURSOR: //bar:
2461 s.size.width = cursor_width;
2469 /* if needed, draw the character under the cursor */
2471 draw_phys_cursor_glyph (w, glyph_row, hl);
2473 #ifdef NS_IMPL_COCOA
2474 NSEnableScreenUpdates ();
2481 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2482 /* --------------------------------------------------------------------------
2483 External (RIF): Draw a vertical line.
2484 -------------------------------------------------------------------------- */
2486 struct frame *f = XFRAME (WINDOW_FRAME (w));
2488 NSRect r = NSMakeRect (x, y0, 2, y1-y0);
2490 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2492 [ns_lookup_indexed_color(face->foreground, f) set];
2494 ns_focus (f, &r, 1);
2495 NSDrawGroove (r, r);
2501 show_hourglass (struct atimer *timer)
2503 if (hourglass_shown_p)
2508 /* TODO: add NSProgressIndicator to selected frame (see macfns.c) */
2510 hourglass_shown_p = 1;
2518 if (!hourglass_shown_p)
2523 /* TODO: remove NSProgressIndicator from all frames */
2525 hourglass_shown_p = 0;
2531 /* ==========================================================================
2533 Glyph drawing operations
2535 ========================================================================== */
2538 static inline NSRect
2539 /* --------------------------------------------------------------------------
2540 Under NS we draw internal borders inside fringes, and want full-width
2541 rendering to go all the way to edge. This function makes that correction.
2542 -------------------------------------------------------------------------- */
2543 ns_fix_rect_ibw (NSRect r, int fibw, int frame_pixel_width)
2545 if (r.origin.y <= fibw+1)
2547 r.size.height += r.origin.y;
2550 if (r.origin.x <= fibw+1)
2552 r.size.width += r.origin.x;
2555 if (frame_pixel_width - (r.origin.x+r.size.width) <= fibw+1)
2556 r.size.width += fibw;
2563 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2564 /* --------------------------------------------------------------------------
2565 Wrapper utility to account for internal border width on full-width lines,
2566 and allow top full-width rows to hit the frame top. nr should be pointer
2567 to two successive NSRects. Number of rects actually used is returned.
2568 -------------------------------------------------------------------------- */
2570 int n = get_glyph_string_clip_rects (s, nr, 2);
2571 if (s->row->full_width_p)
2573 *nr = ns_fix_rect_ibw (*nr, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2574 FRAME_PIXEL_WIDTH (s->f));
2576 *nr = ns_fix_rect_ibw (*(nr+1), FRAME_INTERNAL_BORDER_WIDTH (s->f),
2577 FRAME_PIXEL_WIDTH (s->f));
2584 ns_draw_box (NSRect r, float thickness, NSColor *col, char left_p, char right_p)
2585 /* --------------------------------------------------------------------------
2586 Draw an unfilled rect inside r, optionally leaving left and/or right open.
2587 Note we can't just use an NSDrawRect command, because of the possibility
2588 of some sides not being drawn, and because the rect will be filled.
2589 -------------------------------------------------------------------------- */
2595 s.size.height = thickness;
2597 s.origin.y += r.size.height - thickness;
2600 s.size.height = r.size.height;
2601 s.origin.y = r.origin.y;
2603 /* left, right (optional) */
2604 s.size.width = thickness;
2609 s.origin.x += r.size.width - thickness;
2616 ns_draw_relief (NSRect r, int thickness, char raised_p,
2617 char top_p, char bottom_p, char left_p, char right_p,
2618 struct glyph_string *s)
2619 /* --------------------------------------------------------------------------
2620 Draw a relief rect inside r, optionally leaving some sides open.
2621 Note we can't just use an NSDrawBezel command, because of the possibility
2622 of some sides not being drawn, and because the rect will be filled.
2623 -------------------------------------------------------------------------- */
2625 static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2626 NSColor *newBaseCol = nil;
2629 NSTRACE (ns_draw_relief);
2633 if (s->face->use_box_color_for_shadows_p)
2635 newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2637 /* else if (s->first_glyph->type == IMAGE_GLYPH
2639 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2641 newBaseCol = IMAGE_BACKGROUND (s->img, s->f, 0);
2645 newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2648 if (newBaseCol == nil)
2649 newBaseCol = [NSColor grayColor];
2651 if (newBaseCol != baseCol) /* TODO: better check */
2654 baseCol = [newBaseCol retain];
2656 lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2658 darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2661 [(raised_p ? lightCol : darkCol) set];
2663 /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2666 sr.size.height = thickness;
2667 if (top_p) NSRectFill (sr);
2670 sr.size.height = r.size.height;
2671 sr.size.width = thickness;
2672 if (left_p) NSRectFill (sr);
2674 [(raised_p ? darkCol : lightCol) set];
2677 sr.size.width = r.size.width;
2678 sr.size.height = thickness;
2679 sr.origin.y += r.size.height - thickness;
2680 if (bottom_p) NSRectFill (sr);
2683 sr.size.height = r.size.height;
2684 sr.origin.y = r.origin.y;
2685 sr.size.width = thickness;
2686 sr.origin.x += r.size.width - thickness;
2687 if (right_p) NSRectFill (sr);
2692 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2693 /* --------------------------------------------------------------------------
2694 Function modeled after x_draw_glyph_string_box ().
2695 Sets up parameters for drawing.
2696 -------------------------------------------------------------------------- */
2698 int right_x, last_x;
2699 char left_p, right_p;
2700 struct glyph *last_glyph;
2705 if (s->hl == DRAW_MOUSE_FACE)
2708 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2710 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2715 thickness = face->box_line_width;
2717 NSTRACE (ns_dumpglyphs_box_or_relief);
2719 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2720 ? WINDOW_RIGHT_EDGE_X (s->w)
2721 : window_box_right (s->w, s->area));
2722 last_glyph = (s->cmp || s->img
2723 ? s->first_glyph : s->first_glyph + s->nchars-1);
2725 right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2726 ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2728 left_p = (s->first_glyph->left_box_line_p
2729 || (s->hl == DRAW_MOUSE_FACE
2730 && (s->prev == NULL || s->prev->hl != s->hl)));
2731 right_p = (last_glyph->right_box_line_p
2732 || (s->hl == DRAW_MOUSE_FACE
2733 && (s->next == NULL || s->next->hl != s->hl)));
2735 r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2737 /* expand full-width row over internal borders */
2738 if (s->row->full_width_p)
2739 r = ns_fix_rect_ibw (r, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2740 FRAME_PIXEL_WIDTH (s->f));
2742 if (s->face->box == FACE_SIMPLE_BOX)
2744 xassert (s->face->box_color != nil);
2745 ns_draw_box (r, abs (thickness),
2746 ns_lookup_indexed_color (face->box_color, s->f),
2751 ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2752 1, 1, left_p, right_p, s);
2758 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2759 /* --------------------------------------------------------------------------
2760 Modeled after x_draw_glyph_string_background, which draws BG in
2761 certain cases. Others are left to the text rendering routine.
2762 -------------------------------------------------------------------------- */
2764 NSTRACE (ns_maybe_dumpglyphs_background);
2766 if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2768 int box_line_width = max (s->face->box_line_width, 0);
2769 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2770 || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2773 if (s->hl == DRAW_MOUSE_FACE)
2776 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2778 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2781 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2783 [(NS_FACE_BACKGROUND (face) != 0
2784 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2785 : FRAME_BACKGROUND_COLOR (s->f)) set];
2788 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (s->f);
2789 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2792 if (s->hl != DRAW_CURSOR)
2794 NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2795 s->background_width,
2796 s->height-2*box_line_width);
2798 /* expand full-width row over internal borders */
2799 if (s->row->full_width_p)
2801 int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2802 if (r.origin.y <= fibw+1 + box_line_width)
2804 r.size.height += r.origin.y;
2807 if (r.origin.x <= fibw+1)
2809 r.size.width += 2*r.origin.x;
2812 if (FRAME_PIXEL_WIDTH (s->f) - (r.origin.x + r.size.width)
2814 r.size.width += fibw;
2820 s->background_filled_p = 1;
2827 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2828 /* --------------------------------------------------------------------------
2829 Renders an image and associated borders.
2830 -------------------------------------------------------------------------- */
2832 EmacsImage *img = s->img->pixmap;
2833 int box_line_vwidth = max (s->face->box_line_width, 0);
2834 int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2835 int bg_x, bg_y, bg_height;
2840 NSTRACE (ns_dumpglyphs_image);
2842 if (s->face->box != FACE_NO_BOX
2843 && s->first_glyph->left_box_line_p && s->slice.x == 0)
2844 x += abs (s->face->box_line_width);
2847 bg_y = s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2848 bg_height = s->height;
2849 /* other terms have this, but was causing problems w/tabbar mode */
2850 /* - 2 * box_line_vwidth; */
2852 if (s->slice.x == 0) x += s->img->hmargin;
2853 if (s->slice.y == 0) y += s->img->vmargin;
2855 /* Draw BG: if we need larger area than image itself cleared, do that,
2856 otherwise, since we composite the image under NS (instead of mucking
2857 with its background color), we must clear just the image area. */
2858 [ns_lookup_indexed_color (NS_FACE_BACKGROUND
2859 (FACE_FROM_ID (s->f, s->first_glyph->face_id)), s->f) set];
2861 if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
2862 || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
2864 br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
2865 s->background_filled_p = 1;
2869 br = NSMakeRect (x, y, s->slice.width, s->slice.height);
2872 /* expand full-width row over internal borders */
2873 if (s->row->full_width_p)
2875 int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2876 if (br.origin.y <= fibw+1 + box_line_vwidth)
2878 br.size.height += br.origin.y;
2881 if (br.origin.x <= fibw+1 + box_line_vwidth)
2883 br.size.width += br.origin.x;
2886 if (FRAME_PIXEL_WIDTH (s->f) - (br.origin.x + br.size.width) <= fibw+1)
2887 br.size.width += fibw;
2892 /* Draw the image.. do we need to draw placeholder if img ==nil? */
2894 [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
2895 operation: NSCompositeSourceOver];
2897 /* Draw relief, if requested */
2898 if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
2900 if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
2902 th = tool_bar_button_relief >= 0 ?
2903 tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2904 raised_p = (s->hl == DRAW_IMAGE_RAISED);
2908 th = abs (s->img->relief);
2909 raised_p = (s->img->relief > 0);
2912 r.origin.x = x - th;
2913 r.origin.y = y - th;
2914 r.size.width = s->slice.width + 2*th-1;
2915 r.size.height = s->slice.height + 2*th-1;
2916 ns_draw_relief (r, th, raised_p,
2918 s->slice.y + s->slice.height == s->img->height,
2920 s->slice.x + s->slice.width == s->img->width, s);
2926 ns_draw_glyph_string (struct glyph_string *s)
2927 /* --------------------------------------------------------------------------
2928 External (RIF): Main draw-text call.
2929 -------------------------------------------------------------------------- */
2931 /* TODO (optimize): focus for box and contents draw */
2934 char box_drawn_p = 0;
2936 NSTRACE (ns_draw_glyph_string);
2938 if (s->next && s->right_overhang && !s->for_overlaps/* && s->hl != DRAW_CURSOR*/)
2941 struct glyph_string *next;
2943 for (width = 0, next = s->next; next;
2944 width += next->width, next = next->next)
2945 if (next->first_glyph->type != IMAGE_GLYPH)
2947 n = ns_get_glyph_string_clip_rect (s->next, r);
2948 ns_focus (s->f, r, n);
2949 ns_maybe_dumpglyphs_background (s->next, 1);
2951 next->num_clips = 0;
2955 if (!s->for_overlaps && s->face->box != FACE_NO_BOX
2956 && (s->first_glyph->type == CHAR_GLYPH
2957 || s->first_glyph->type == COMPOSITE_GLYPH))
2959 n = ns_get_glyph_string_clip_rect (s, r);
2960 ns_focus (s->f, r, n);
2961 ns_maybe_dumpglyphs_background (s, 1);
2962 ns_dumpglyphs_box_or_relief (s);
2967 switch (s->first_glyph->type)
2971 n = ns_get_glyph_string_clip_rect (s, r);
2972 ns_focus (s->f, r, n);
2973 ns_dumpglyphs_image (s, r[0]);
2978 if (!s->background_filled_p)
2980 *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
2982 if (!s->row->full_width_p)
2984 /* truncate to avoid overwriting fringe and/or scrollbar */
2985 int overrun = max (0, (s->x + s->background_width)
2986 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
2987 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
2988 r[0].size.width -= overrun;
2990 /* XXX: Try to work between problem where a stretch glyph on
2991 a partially-visible bottom row will clear part of the
2992 modeline, and another where list-buffers headers and similar
2993 rows erroneously have visible_height set to 0. Not sure
2994 where this is coming from as other terms seem not to show. */
2995 r[0].size.height = min (s->height, s->row->visible_height);
2998 /* expand full-width rows over internal borders */
3001 r[0] = ns_fix_rect_ibw (r[0], FRAME_INTERNAL_BORDER_WIDTH (s->f),
3002 FRAME_PIXEL_WIDTH (s->f));
3005 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3006 overwriting cursor (usually when cursor on a tab) */
3007 if (s->hl == DRAW_CURSOR)
3009 r[0].origin.x += s->width;
3010 r[0].size.width -= s->width;
3013 ns_focus (s->f, r, 1);
3014 [ns_lookup_indexed_color (NS_FACE_BACKGROUND
3015 (FACE_FROM_ID (s->f, s->first_glyph->face_id)), s->f) set];
3018 s->background_filled_p = 1;
3023 case COMPOSITE_GLYPH:
3024 n = ns_get_glyph_string_clip_rect (s, r);
3025 ns_focus (s->f, r, n);
3027 if (s->for_overlaps || s->gidx > 0)
3028 s->background_filled_p = 1;
3030 ns_maybe_dumpglyphs_background
3031 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3033 ns_tmp_flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3034 (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3035 (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3036 NS_DUMPGLYPH_NORMAL));
3037 ns_tmp_font = (struct nsfont_info *)s->face->font;
3038 if (ns_tmp_font == NULL)
3039 ns_tmp_font = (struct nsfont_info *)FRAME_FONT (s->f);
3041 ns_tmp_font->font.driver->draw
3042 (s, 0, s->nchars, s->x, s->y,
3043 (ns_tmp_flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3044 || ns_tmp_flags == NS_DUMPGLYPH_MOUSEFACE);
3053 /* Draw box if not done already. */
3054 if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3056 n = ns_get_glyph_string_clip_rect (s, r);
3057 ns_focus (s->f, r, n);
3058 ns_dumpglyphs_box_or_relief (s);
3067 /* ==========================================================================
3071 ========================================================================== */
3075 ns_send_appdefined (int value)
3076 /* --------------------------------------------------------------------------
3077 Internal: post an appdefined event which EmacsApp-sendEvent will
3078 recognize and take as a command to halt the event loop.
3079 -------------------------------------------------------------------------- */
3081 /*NSTRACE (ns_send_appdefined); */
3083 /* Only post this event if we haven't already posted one. This will end
3084 the [NXApp run] main loop after having processed all events queued at
3086 if (send_appdefined)
3090 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
3091 send_appdefined = NO;
3093 /* Don't need wakeup timer any more */
3096 [timed_entry invalidate];
3097 [timed_entry release];
3101 /* Ditto for file descriptor poller */
3104 [fd_entry invalidate];
3109 nxev = [NSEvent otherEventWithType: NSApplicationDefined
3110 location: NSMakePoint (0, 0)
3113 windowNumber: [[NSApp mainWindow] windowNumber]
3114 context: [NSApp context]
3119 /* Post an application defined event on the event queue. When this is
3120 received the [NXApp run] will return, thus having processed all
3121 events which are currently queued. */
3122 [NSApp postEvent: nxev atStart: NO];
3128 ns_read_socket (struct terminal *terminal, int expected,
3129 struct input_event *hold_quit)
3130 /* --------------------------------------------------------------------------
3131 External (hook): Post an event to ourself and keep reading events until
3132 we read it back again. In effect process all events which were waiting.
3133 23: Now we have to manage the event buffer ourselves.
3134 -------------------------------------------------------------------------- */
3136 struct input_event ev;
3138 static NSDate *lastCheck = nil;
3139 /* NSTRACE (ns_read_socket); */
3141 if (interrupt_input_blocked)
3143 interrupt_input_pending = 1;
3147 interrupt_input_pending = 0;
3150 #ifdef COCOA_EXPERIMENTAL_CTRL_G
3151 /* causes Feval to abort; unclear on why this isn't in calling code */
3155 n_emacs_events_pending = 0;
3158 q_event_ptr = hold_quit;
3160 /* we manage autorelease pools by allocate/reallocate each time around
3161 the loop; strict nesting is occasionally violated but seems not to
3162 matter.. earlier methods using full nesting caused major memory leaks */
3163 [outerpool release];
3164 outerpool = [[NSAutoreleasePool alloc] init];
3166 /* If have pending open-file requests, attend to the next one of those. */
3167 if (ns_pending_files && [ns_pending_files count] != 0
3168 && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3170 [ns_pending_files removeObjectAtIndex: 0];
3172 /* Deal with pending service requests. */
3173 else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3175 NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3176 withArg: [ns_pending_service_args objectAtIndex: 0]])
3178 [ns_pending_service_names removeObjectAtIndex: 0];
3179 [ns_pending_service_args removeObjectAtIndex: 0];
3183 /* Run and wait for events. We must always send one NX_APPDEFINED event
3184 to ourself, otherwise [NXApp run] will never exit. */
3185 send_appdefined = YES;
3187 /* TODO: from termhooks.h: */
3188 /* XXX Please note that a non-zero value of EXPECTED only means that
3189 there is available input on at least one of the currently opened
3190 terminal devices -- but not necessarily on this device.
3191 Therefore, in most cases EXPECTED should be simply ignored. */
3192 /* However, if in ns_select, this is called from gobble_input, which
3193 appears to set it correctly for our purposes, and always assuming
3194 !expected causes 100% CPU usage. */
3195 if (!inNsSelect || !expected)
3197 /* Post an application defined event on the event queue. When this is
3198 received the [NXApp run] will return, thus having processed all
3199 events which are currently queued, if any. */
3200 ns_send_appdefined (-1);
3206 nevents = n_emacs_events_pending;
3207 n_emacs_events_pending = 0;
3208 emacs_event = q_event_ptr = NULL;
3210 #ifdef COCOA_EXPERIMENTAL_CTRL_G
3219 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3220 fd_set *exceptfds, struct timeval *timeout)
3221 /* --------------------------------------------------------------------------
3222 Replacement for select, checking for events
3223 -------------------------------------------------------------------------- */
3228 /* NSTRACE (ns_select); */
3230 if (NSApp == nil /* || ([NSApp isActive] == NO &&
3231 [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
3232 inMode:NSDefaultRunLoopMode dequeue:NO] == nil) */)
3233 return select (nfds, readfds, writefds, exceptfds, timeout);
3235 /* Save file descriptor set, which gets overwritten in calls to select ()
3236 Note, this is called from process.c, and only readfds is ever set */
3239 memcpy (&select_readfds, readfds, sizeof (fd_set));
3245 /* Try an initial select for pending data on input files */
3246 select_timeout.tv_sec = select_timeout.tv_usec = 0;
3247 result = select (nfds, readfds, writefds, exceptfds, &select_timeout);
3251 /* if (!timeout || timed_entry || fd_entry)
3252 fprintf (stderr, "assertion failed: timeout null or timed_entry/fd_entry non-null in ns_select\n"); */
3254 /* set a timeout and run the main AppKit event loop while continuing
3255 to monitor the files */
3256 time = ((double) timeout->tv_sec) + ((double) timeout->tv_usec)/1000000.0;
3257 timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3259 selector: @selector (timeout_handler:)
3261 repeats: YES] /* for safe removal */
3264 /* set a periodic task to try the select () again */
3265 fd_entry = [[NSTimer scheduledTimerWithTimeInterval: 0.1
3267 selector: @selector (fd_handler:)
3272 /* Let Application dispatch events until it receives an event of the type
3273 NX_APPDEFINED, which should only be sent by timeout_handler. */
3275 gobble_input (timeout ? 1 : 0);
3276 ev = last_appdefined_event;
3282 if ([ev type] != NSApplicationDefined)
3286 last_appdefined_event = 0;
3290 /* The NX_APPDEFINED event we received was a timeout. */
3295 /* The NX_APPDEFINED event we received was the result of
3296 at least one real input event arriving. */
3302 /* Received back from select () in fd_handler; copy the results */
3304 memcpy (readfds, &select_readfds, sizeof (fd_set));
3308 /* never reached, shut compiler up */
3314 /* ==========================================================================
3318 ========================================================================== */
3322 ns_set_vertical_scroll_bar (struct window *window,
3323 int portion, int whole, int position)
3324 /* --------------------------------------------------------------------------
3325 External (hook): Update or add scrollbar
3326 -------------------------------------------------------------------------- */
3330 struct frame *f = XFRAME (WINDOW_FRAME (window));
3331 EmacsView *view = FRAME_NS_VIEW (f);
3332 int window_y, window_height;
3333 BOOL barOnVeryLeft, barOnVeryRight;
3334 int top, left, height, width, sb_width, sb_left;
3336 static int count = 0;
3338 /* optimization; display engine sends WAY too many of these.. */
3339 if (!NILP (window->vertical_scroll_bar))
3341 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3342 if ([bar checkSamePosition: position portion: portion whole: whole])
3344 if (view->scrollbarsNeedingUpdate == 0)
3346 if (!windows_or_buffers_changed)
3350 view->scrollbarsNeedingUpdate--;
3354 NSTRACE (ns_set_vertical_scroll_bar);
3356 /* Get dimensions. */
3357 window_box (window, -1, 0, &window_y, 0, &window_height);
3359 height = window_height;
3360 width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3361 left = WINDOW_SCROLL_BAR_AREA_X (window);
3363 if (top < 5) /* top scrollbar adjustment */
3365 top -= FRAME_INTERNAL_BORDER_WIDTH (f);
3366 height += FRAME_INTERNAL_BORDER_WIDTH (f);
3369 /* allow for displaying a skinnier scrollbar than char area allotted */
3370 sb_width = (WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) > 0) ?
3371 WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) : width;
3373 barOnVeryLeft = left < 5;
3374 barOnVeryRight = FRAME_PIXEL_WIDTH (f) - left - width < 5;
3375 sb_left = left + FRAME_INTERNAL_BORDER_WIDTH (f)
3376 * (barOnVeryLeft ? -1 : (barOnVeryRight ? 1 : 0));
3378 r = NSMakeRect (sb_left, top, sb_width, height);
3379 /* the parent view is flipped, so we need to flip y value */
3381 r.origin.y = (v.size.height - r.size.height - r.origin.y);
3383 XSETWINDOW (win, window);
3386 /* we want at least 5 lines to display a scrollbar */
3387 if (WINDOW_TOTAL_LINES (window) < 5)
3389 if (!NILP (window->vertical_scroll_bar))
3391 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3392 [bar removeFromSuperview];
3393 window->vertical_scroll_bar = Qnil;
3395 ns_clear_frame_area (f, sb_left, top, width, height);
3400 if (NILP (window->vertical_scroll_bar))
3402 ns_clear_frame_area (f, sb_left, top, width, height);
3403 bar = [[EmacsScroller alloc] initFrame: r window: win];
3404 window->vertical_scroll_bar = make_save_value (bar, 0);
3409 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3410 oldRect = [bar frame];
3411 r.size.width = oldRect.size.width;
3412 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3414 if (oldRect.origin.x != r.origin.x)
3415 ns_clear_frame_area (f, sb_left, top, width, height);
3420 [bar setPosition: position portion: portion whole: whole];
3426 ns_condemn_scroll_bars (struct frame *f)
3427 /* --------------------------------------------------------------------------
3428 External (hook): arrange for all frame's scrollbars to be removed
3429 at next call to judge_scroll_bars, except for those redeemed.
3430 -------------------------------------------------------------------------- */
3434 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3436 NSTRACE (ns_condemn_scroll_bars);
3438 for (i =[subviews count]-1; i >= 0; i--)
3440 view = [subviews objectAtIndex: i];
3441 if ([view isKindOfClass: [EmacsScroller class]])
3448 ns_redeem_scroll_bar (struct window *window)
3449 /* --------------------------------------------------------------------------
3450 External (hook): arrange to spare this window's scrollbar
3451 at next call to judge_scroll_bars.
3452 -------------------------------------------------------------------------- */
3455 NSTRACE (ns_redeem_scroll_bar);
3456 if (!NILP (window->vertical_scroll_bar))
3458 bar =XNS_SCROLL_BAR (window->vertical_scroll_bar);
3465 ns_judge_scroll_bars (struct frame *f)
3466 /* --------------------------------------------------------------------------
3467 External (hook): destroy all scrollbars on frame that weren't
3468 redeemed after call to condemn_scroll_bars.
3469 -------------------------------------------------------------------------- */
3473 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3474 NSTRACE (ns_judge_scroll_bars);
3475 for (i =[subviews count]-1; i >= 0; i--)
3477 view = [subviews objectAtIndex: i];
3478 if (![view isKindOfClass: [EmacsScroller class]]) continue;
3485 /* ==========================================================================
3487 Miscellaneous, mainly stubbed-out functions added in 23
3489 ========================================================================== */
3493 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
3499 /* ==========================================================================
3503 ========================================================================== */
3505 static Lisp_Object ns_string_to_lispmod (const char *s)
3506 /* --------------------------------------------------------------------------
3507 Convert modifier name to lisp symbol
3508 -------------------------------------------------------------------------- */
3510 if (!strncmp (SDATA (SYMBOL_NAME (Qmeta)), s, 10))
3512 else if (!strncmp (SDATA (SYMBOL_NAME (Qsuper)), s, 10))
3514 else if (!strncmp (SDATA (SYMBOL_NAME (Qcontrol)), s, 10))
3516 else if (!strncmp (SDATA (SYMBOL_NAME (Qalt)), s, 10))
3518 else if (!strncmp (SDATA (SYMBOL_NAME (Qhyper)), s, 10))
3520 else if (!strncmp (SDATA (SYMBOL_NAME (Qnone)), s, 10))
3527 static Lisp_Object ns_mod_to_lisp (int m)
3528 /* --------------------------------------------------------------------------
3529 Convert modifier code (see lisp.h) to lisp symbol
3530 -------------------------------------------------------------------------- */
3534 else if (m == CHAR_SUPER)
3536 else if (m == CHAR_CTL)
3538 else if (m == CHAR_ALT)
3540 else if (m == CHAR_HYPER)
3542 else /* if (m == 0) */
3548 ns_set_default_prefs ()
3549 /* --------------------------------------------------------------------------
3550 Initialize preference variables to defaults
3551 -------------------------------------------------------------------------- */
3553 ns_alternate_modifier = Qmeta;
3554 ns_command_modifier = Qsuper;
3555 ns_control_modifier = Qcontrol;
3556 ns_function_modifier = Qnone;
3557 ns_expand_space = make_float (0.0);
3558 ns_antialias_text = Qt;
3559 ns_antialias_threshold = 10.0; /* not exposed to lisp side */
3560 ns_use_qd_smoothing = Qnil;
3561 ns_use_system_highlight_color = Qt;
3566 ns_default (const char *parameter, Lisp_Object *result,
3567 Lisp_Object yesval, Lisp_Object noval,
3568 BOOL is_float, BOOL is_modstring)
3569 /* --------------------------------------------------------------------------
3570 Check a parameter value in user's preferences
3571 -------------------------------------------------------------------------- */
3575 if ( (value =[[[NSUserDefaults standardUserDefaults]
3576 stringForKey: [NSString stringWithUTF8String: parameter]]
3581 if (strcasecmp (value, "YES") == 0)
3583 else if (strcasecmp (value, "NO") == 0)
3585 else if (is_float && (f = strtod (value, &pos), pos != value))
3586 *result = make_float (f);
3587 else if (is_modstring && value)
3588 *result = ns_string_to_lispmod (value);
3589 else fprintf (stderr,
3590 "Bad value for default \"%s\": \"%s\"\n", parameter, value);
3596 ns_initialize_display_info (struct ns_display_info *dpyinfo)
3597 /* --------------------------------------------------------------------------
3598 Initialize global info and storage for display.
3599 -------------------------------------------------------------------------- */
3601 NSScreen *screen = [NSScreen mainScreen];
3602 NSWindowDepth depth = [screen depth];
3604 dpyinfo->width = [screen frame].size.width;
3605 dpyinfo->height = [screen frame].size.height;
3606 dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
3607 dpyinfo->resy = 72.27;
3608 dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
3609 NSColorSpaceFromDepth (depth)]
3610 && ![NSCalibratedWhiteColorSpace isEqualToString:
3611 NSColorSpaceFromDepth (depth)];
3612 dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
3613 dpyinfo->image_cache = make_image_cache ();
3614 dpyinfo->color_table
3615 = (struct ns_color_table *)xmalloc (sizeof (struct ns_color_table));
3616 dpyinfo->color_table->colors = NULL;
3617 dpyinfo->root_window = 42; /* a placeholder.. */
3619 dpyinfo->mouse_face_mouse_frame = NULL;
3620 dpyinfo->mouse_face_deferred_gc = 0;
3621 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
3622 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
3623 dpyinfo->mouse_face_face_id = DEFAULT_FACE_ID;
3624 dpyinfo->mouse_face_window = dpyinfo->mouse_face_overlay = Qnil;
3625 dpyinfo->mouse_face_hidden = 0;
3627 dpyinfo->mouse_face_mouse_x = dpyinfo->mouse_face_mouse_y = 0;
3628 dpyinfo->mouse_face_defer = 0;
3630 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
3632 dpyinfo->n_fonts = 0;
3633 dpyinfo->smallest_font_height = 1;
3634 dpyinfo->smallest_char_width = 1;
3638 /* 23: Needed as new part of display engine; this and next define public
3639 functions in this file (well, many of them, anyway). */
3640 /* x_... are generic versions in xdisp.c that we, and other terms, get away
3641 with using despite presence in the "system dependent" redisplay
3642 interface. In addition, many of the ns_ methods have code that is
3643 shared with all terms, indicating need for further refactoring. */
3644 extern frame_parm_handler ns_frame_parm_handlers[];
3645 static struct redisplay_interface ns_redisplay_interface =
3647 ns_frame_parm_handlers,
3648 x_produce_glyphs, /*generic OK */
3649 x_write_glyphs, /*generic OK */
3650 x_insert_glyphs, /*generic OK */
3651 x_clear_end_of_line, /*generic OK */
3652 ns_scroll_run, /*23 */
3653 ns_after_update_window_line, /*23: added */
3654 ns_update_window_begin, /*23: split from update_begin */
3655 ns_update_window_end, /*23: split from update_end */
3656 x_cursor_to, /*generic OK */
3658 0, /* flush_display_optional */
3659 x_clear_window_mouse_face, /*generic OK */
3660 x_get_glyph_overhangs, /*23: generic OK */
3661 x_fix_overlapping_area, /*generic OK */
3662 ns_draw_fringe_bitmap, /*23 */
3663 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
3664 0, /* destroy_fringe_bitmap */
3665 ns_compute_glyph_string_overhangs, /*23 */
3666 ns_draw_glyph_string, /*23: interface to nsfont.m */
3667 ns_define_frame_cursor, /*23 */
3668 ns_clear_frame_area, /*23 */
3669 ns_draw_window_cursor, /*23: revamped ns_dumpcursor */
3670 ns_draw_vertical_window_border,
3671 ns_shift_glyphs_for_insert
3676 ns_delete_display (struct ns_display_info *dpyinfo)
3682 /* This function is called when the last frame on a display is deleted. */
3684 ns_delete_terminal (struct terminal *terminal)
3686 struct ns_display_info *dpyinfo = terminal->display_info.ns;
3689 /* Protect against recursive calls. Fdelete_frame in
3690 delete_terminal calls us back when it deletes our last frame. */
3691 if (!terminal->name)
3696 x_destroy_all_bitmaps (dpyinfo);
3697 ns_delete_display (dpyinfo);
3702 static struct terminal *
3703 ns_create_terminal (struct ns_display_info *dpyinfo)
3704 /* --------------------------------------------------------------------------
3705 Set up use of NS before we make the first connection.
3706 -------------------------------------------------------------------------- */
3708 struct terminal *terminal;
3710 NSTRACE (ns_create_terminal);
3712 terminal = create_terminal ();
3714 terminal->type = output_ns;
3715 terminal->display_info.ns = dpyinfo;
3716 dpyinfo->terminal = terminal;
3718 terminal->rif = &ns_redisplay_interface;
3720 terminal->clear_frame_hook = ns_clear_frame;
3721 terminal->ins_del_lines_hook = 0; /* 23: vestigial? */
3722 terminal->delete_glyphs_hook = 0; /* 23: vestigial? */
3723 terminal->ring_bell_hook = ns_ring_bell;
3724 terminal->reset_terminal_modes_hook = ns_reset_terminal_modes;
3725 terminal->set_terminal_modes_hook = ns_set_terminal_modes;
3726 terminal->update_begin_hook = ns_update_begin;
3727 terminal->update_end_hook = ns_update_end;
3728 terminal->set_terminal_window_hook = NULL; /* 23: vestigial? */
3729 terminal->read_socket_hook = ns_read_socket;
3730 terminal->frame_up_to_date_hook = ns_frame_up_to_date;
3731 terminal->mouse_position_hook = ns_mouse_position;
3732 terminal->frame_rehighlight_hook = ns_frame_rehighlight;
3733 terminal->frame_raise_lower_hook = ns_frame_raise_lower;
3735 terminal->fullscreen_hook = 0; /*XTfullscreen_hook;//23.50 */
3737 terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
3738 terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
3739 terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
3740 terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
3742 terminal->delete_frame_hook = x_destroy_window;
3743 terminal->delete_terminal_hook = ns_delete_terminal;
3745 terminal->scroll_region_ok = 1;
3746 terminal->char_ins_del_ok = 1;
3747 terminal->line_ins_del_ok = 1;
3748 terminal->fast_clear_end_of_line = 1;
3749 terminal->memory_below_frame = 0;
3757 /* --------------------------------------------------------------------------
3758 Mainly vestigial under NS now that ns_create_terminal () does most things.
3759 -------------------------------------------------------------------------- */
3762 Fset_input_interrupt_mode (Qt);
3766 struct ns_display_info *
3767 ns_term_init (Lisp_Object display_name)
3768 /* --------------------------------------------------------------------------
3769 Start the Application and get things rolling.
3770 -------------------------------------------------------------------------- */
3772 extern Lisp_Object Fset_input_mode (Lisp_Object, Lisp_Object,
3773 Lisp_Object, Lisp_Object);
3774 struct terminal *terminal;
3775 struct ns_display_info *dpyinfo;
3776 static int ns_initialized = 0;
3779 NSTRACE (ns_term_init);
3781 /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
3782 /*GSDebugAllocationActive (YES); */
3784 handling_signal = 0;
3786 if (!ns_initialized)
3792 ns_pending_files = [[NSMutableArray alloc] init];
3793 ns_pending_service_names = [[NSMutableArray alloc] init];
3794 ns_pending_service_args = [[NSMutableArray alloc] init];
3796 /* Start app and create the main menu, window, view.
3797 Needs to be here because ns_initialize_display_info () uses AppKit classes.
3798 The view will then ask the NSApp to stop and return to Emacs. */
3799 [EmacsApp sharedApplication];
3802 [NSApp setDelegate: NSApp];
3804 /* debugging: log all notifications */
3805 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
3806 selector: @selector (logNotification:)
3807 name: nil object: nil]; */
3809 dpyinfo = (struct ns_display_info *)xmalloc (sizeof (struct ns_display_info));
3810 bzero (dpyinfo, sizeof (struct ns_display_info));
3812 ns_initialize_display_info (dpyinfo);
3813 terminal = ns_create_terminal (dpyinfo);
3815 terminal->kboard = (KBOARD *) xmalloc (sizeof (KBOARD));
3816 init_kboard (terminal->kboard);
3817 terminal->kboard->Vwindow_system = Qns;
3818 terminal->kboard->next_kboard = all_kboards;
3819 all_kboards = terminal->kboard;
3820 /* Don't let the initial kboard remain current longer than necessary.
3821 That would cause problems if a file loaded on startup tries to
3822 prompt in the mini-buffer. */
3823 if (current_kboard == initial_kboard)
3824 current_kboard = terminal->kboard;
3825 terminal->kboard->reference_count++;
3827 dpyinfo->next = x_display_list;
3828 x_display_list = dpyinfo;
3830 /* Put it on ns_display_name_list */
3831 ns_display_name_list = Fcons (Fcons (display_name, Qnil),
3832 ns_display_name_list);
3833 /* ns_display_name_list = Fcons (Fcons (display_name,
3834 Fcons (Qnil, dpyinfo->xrdb)),
3835 ns_display_name_list); */
3836 dpyinfo->name_list_element = XCAR (ns_display_name_list);
3838 /* Set the name of the terminal. */
3839 terminal->name = (char *) xmalloc (SBYTES (display_name) + 1);
3840 strncpy (terminal->name, SDATA (display_name), SBYTES (display_name));
3841 terminal->name[SBYTES (display_name)] = 0;
3845 /* Read various user defaults. */
3846 ns_set_default_prefs ();
3847 ns_default ("AlternateModifier", &ns_alternate_modifier,
3848 Qnil, Qnil, NO, YES);
3849 if (NILP (ns_alternate_modifier))
3850 ns_alternate_modifier = Qmeta;
3851 ns_default ("CommandModifier", &ns_command_modifier,
3852 Qnil, Qnil, NO, YES);
3853 if (NILP (ns_command_modifier))
3854 ns_command_modifier = Qsuper;
3855 ns_default ("ControlModifier", &ns_control_modifier,
3856 Qnil, Qnil, NO, YES);
3857 if (NILP (ns_control_modifier))
3858 ns_control_modifier = Qcontrol;
3859 ns_default ("FunctionModifier", &ns_function_modifier,
3860 Qnil, Qnil, NO, YES);
3861 if (NILP (ns_function_modifier))
3862 ns_function_modifier = Qnone;
3863 ns_default ("ExpandSpace", &ns_expand_space,
3864 make_float (0.5), make_float (0.0), YES, NO);
3865 ns_default ("GSFontAntiAlias", &ns_antialias_text,
3868 ns_default ("AppleAntiAliasingThreshold", &tmp,
3869 make_float (10.0), make_float (6.0), YES, NO);
3870 ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
3871 ns_default ("UseQuickdrawSmoothing", &ns_use_qd_smoothing,
3873 ns_default ("UseSystemHighlightColor", &ns_use_system_highlight_color,
3875 if (EQ (ns_use_system_highlight_color, Qt))
3877 ns_selection_color = [[NSUserDefaults standardUserDefaults]
3878 stringForKey: @"AppleHighlightColor"];
3879 if (ns_selection_color == nil)
3880 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
3883 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
3886 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
3890 Lisp_Object color_file, color_map, color;
3895 color_file = Fexpand_file_name (build_string ("rgb.txt"),
3896 Fsymbol_value (intern ("data-directory")));
3897 if (NILP (Ffile_readable_p (color_file)))
3898 fatal ("Could not find %s.\n", SDATA (color_file));
3900 color_map = Fx_load_color_file (color_file);
3901 if (NILP (color_map))
3902 fatal ("Could not read %s.\n", SDATA (color_file));
3904 cl = [[NSColorList alloc] initWithName: @"Emacs"];
3905 for ( ; CONSP (color_map); color_map = XCDR (color_map))
3907 color = XCAR (color_map);
3908 name = SDATA (XCAR (color));
3909 c = XINT (XCDR (color));
3911 [NSColor colorWithCalibratedRed: RED_FROM_ULONG (c) / 255.0
3912 green: GREEN_FROM_ULONG (c) / 255.0
3913 blue: BLUE_FROM_ULONG (c) / 255.0
3915 forKey: [NSString stringWithUTF8String: name]];
3917 [cl writeToFile: nil];
3923 #ifdef NS_IMPL_GNUSTEP
3924 strncpy (c, gnustep_base_version, sizeof (c));
3926 /*PSnextrelease (128, c); */
3927 snprintf (c, sizeof (c), "%g", NSAppKitVersionNumber);
3929 Vwindow_system_version = build_string (c);
3932 delete_keyboard_wait_descriptor (0);
3934 /* Set up OS X app menu */
3935 #ifdef NS_IMPL_COCOA
3939 /* set up the application menu */
3940 svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
3941 [svcsMenu setAutoenablesItems: NO];
3942 appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
3943 [appMenu setAutoenablesItems: NO];
3944 mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
3945 dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
3947 [appMenu insertItemWithTitle: @"About Emacs"
3948 action: @selector (orderFrontStandardAboutPanel:)
3951 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
3952 [appMenu insertItemWithTitle: @"Preferences..."
3953 action: @selector (showPreferencesWindow:)
3956 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
3957 item = [appMenu insertItemWithTitle: @"Services"
3958 action: @selector (menuDown:)
3961 [appMenu setSubmenu: svcsMenu forItem: item];
3962 /* [svcsMenu setSupercell: item]; */
3963 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
3964 [appMenu insertItemWithTitle: @"Hide Emacs"
3965 action: @selector (hide:)
3968 item = [appMenu insertItemWithTitle: @"Hide Others"
3969 action: @selector (hideOtherApplications:)
3972 [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
3973 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
3974 [appMenu insertItemWithTitle: @"Quit Emacs"
3975 action: @selector (terminate:)
3979 item = [mainMenu insertItemWithTitle: @"Emacs"
3980 action: @selector (menuDown:)
3983 [mainMenu setSubmenu: appMenu forItem: item];
3984 [dockMenu insertItemWithTitle: @"New Frame"
3985 action: @selector (newFrame:)
3989 [NSApp setMainMenu: mainMenu];
3990 [NSApp setAppleMenu: appMenu];
3991 [NSApp setServicesMenu: svcsMenu];
3992 /* Needed at least on Cocoa, to get dock menu to show windows */
3993 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
3995 #endif /* MAC OS X menu setup */
4003 extern Lisp_Object Vauto_save_list_file_name;
4005 ns_term_shutdown (int sig)
4007 /* code not reached in emacs.c after this is called by shut_down_emacs: */
4008 if (STRINGP (Vauto_save_list_file_name))
4009 unlink (SDATA (Vauto_save_list_file_name));
4011 ns_shutdown_properly = YES;
4012 [NSApp terminate: NSApp];
4016 /* ==========================================================================
4018 EmacsApp implementation
4020 ========================================================================== */
4023 @implementation EmacsApp
4025 - (void)logNotification: (NSNotification *)notification
4027 const char *name = [[notification name] UTF8String];
4028 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4029 && !strstr (name, "WindowNumber"))
4030 NSLog (@"notification: '%@'", [notification name]);
4034 - (void)sendEvent: (NSEvent *)theEvent
4035 /* --------------------------------------------------------------------------
4036 Events posted by ns_send_appdefined interrupt the run loop here
4037 -------------------------------------------------------------------------- */
4039 int type = [theEvent type];
4040 NSWindow *window = [theEvent window];
4041 /* NSTRACE (sendEvent); */
4042 /*fprintf (stderr, "received event of type %d\n", [theEvent type]); */
4044 if (type == NSCursorUpdate && window == nil)
4046 fprintf (stderr, "Dropping external cursor update event.\n");
4050 #ifdef NS_IMPL_COCOA
4051 /* pass mouse down in resize handle and subsequent drags directly to
4052 EmacsWindow so we can generate continuous redisplays */
4055 if (type == NSLeftMouseDragged)
4057 [window mouseDragged: theEvent];
4060 else if (type == NSLeftMouseUp)
4062 [window mouseUp: theEvent];
4066 else if (type == NSLeftMouseDown)
4068 NSRect r = ns_resize_handle_rect (window);
4069 if (NSPointInRect ([theEvent locationInWindow], r))
4072 [window mouseDown: theEvent];
4078 if (type == NSApplicationDefined)
4080 last_appdefined_event = theEvent;
4084 [super sendEvent: theEvent];
4088 - (void)showPreferencesWindow: (id)sender
4090 if (prefsController == nil)
4091 prefsController = [[EmacsPrefsController alloc] init];
4092 [prefsController showForFrame: SELECTED_FRAME ()];
4096 - (void)newFrame: (id)sender
4098 struct frame *emacsframe = SELECTED_FRAME ();
4099 NSEvent *theEvent = [NSApp currentEvent];
4103 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4104 emacs_event->code = KEY_NS_NEW_FRAME;
4105 emacs_event->modifiers = 0;
4106 EV_TRAILER (theEvent);
4110 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4111 - (BOOL) openFile: (NSString *)fileName
4113 struct frame *emacsframe = SELECTED_FRAME ();
4114 NSEvent *theEvent = [NSApp currentEvent];
4119 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4120 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4121 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4122 ns_input_line = Qnil; /* can be start or cons start,end */
4123 emacs_event->modifiers =0;
4124 EV_TRAILER (theEvent);
4130 /* **************************************************************************
4132 EmacsApp delegate implementation
4134 ************************************************************************** */
4136 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4137 /* --------------------------------------------------------------------------
4138 When application is loaded, terminate event loop in ns_term_init
4139 -------------------------------------------------------------------------- */
4141 NSTRACE (applicationDidFinishLaunching);
4142 [NSApp setServicesProvider: NSApp];
4143 ns_send_appdefined (-2);
4147 - (void) terminate: (id)sender
4150 if (ns_shutdown_properly)
4151 [super terminate: sender];
4154 /* Fkill_emacs (Qnil); */
4155 ns_shutdown_properly = YES;
4156 Feval (Fcons (intern ("save-buffers-kill-emacs"), Qnil));
4162 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4164 if (ns_shutdown_properly)
4165 return NSTerminateNow;
4167 Lisp_Object contents = list3 (build_string ("Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?"),
4168 Fcons (build_string ("Cancel"), Qnil),
4169 Fcons (build_string ("Save and Exit"), Qt));
4170 Lisp_Object res = ns_popup_dialog (Qt, contents, Qnil);
4171 fprintf (stderr, "res = %d\n", EQ (res, Qt)); /* FIXME */
4174 Feval (Fcons (intern ("save-buffers-kill-emacs"), Qnil));
4175 return NSTerminateNow;
4177 return NSTerminateCancel;
4181 /* Notification from the Workspace to open a file */
4182 - (BOOL)application: sender openFile: (NSString *)file
4184 [ns_pending_files addObject: file];
4189 /* Open a file as a temporary file */
4190 - (BOOL)application: sender openTempFile: (NSString *)file
4192 [ns_pending_files addObject: file];
4197 /* Notification from the Workspace to open a file noninteractively (?) */
4198 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4200 [ns_pending_files addObject: file];
4205 /* Notification from the Workspace to open multiple files */
4206 - (void)application: sender openFiles: (NSArray *)fileList
4208 NSEnumerator *files = [fileList objectEnumerator];
4210 while ((file = [files nextObject]) != nil)
4211 [ns_pending_files addObject: file];
4213 /* TODO: when GNUstep implements this (and we require that version of
4214 GNUstep), remove. */
4215 #ifndef NS_IMPL_GNUSTEP
4216 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4217 #endif /* !NS_IMPL_GNUSTEP */
4222 /* Handle dock menu requests. */
4223 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4229 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4230 - (void)applicationDidBecomeActive: (NSNotification *)notification
4233 - (void)applicationDidResignActive: (NSNotification *)notification
4235 ns_send_appdefined (-1);
4240 /* ==========================================================================
4242 EmacsApp aux handlers for managing event loop
4244 ========================================================================== */
4247 - (void)timeout_handler: (NSTimer *)timedEntry
4248 /* --------------------------------------------------------------------------
4249 The timeout specified to ns_select has passed.
4250 -------------------------------------------------------------------------- */
4252 /*NSTRACE (timeout_handler); */
4253 ns_send_appdefined (-2);
4256 extern void update_window_cursor (struct window *w, int on);
4258 - (void)fd_handler: (NSTimer *) fdEntry
4259 /* --------------------------------------------------------------------------
4260 Check data waiting on file descriptors and terminate if so
4261 -------------------------------------------------------------------------- */
4264 /* NSTRACE (fd_handler); */
4266 if (select_nfds == 0)
4269 memcpy (&t_readfds, &select_readfds, sizeof (fd_set));
4271 select_timeout.tv_sec = select_timeout.tv_usec = 0;
4272 result = select (select_nfds, &t_readfds, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
4276 memcpy (&select_readfds, &t_readfds, sizeof (fd_set));
4277 ns_send_appdefined (result);
4283 /* ==========================================================================
4287 ========================================================================== */
4289 /* called from system: queue for next pass through event loop */
4290 - (void)requestService: (NSPasteboard *)pboard
4291 userData: (NSString *)userData
4292 error: (NSString **)error
4294 [ns_pending_service_names addObject: userData];
4295 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
4296 SDATA (ns_string_from_pasteboard (pboard))]];
4300 /* called from ns_read_socket to clear queue */
4301 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
4303 struct frame *emacsframe = SELECTED_FRAME ();
4304 NSEvent *theEvent = [NSApp currentEvent];
4309 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4310 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
4311 ns_input_spi_name = build_string ([name UTF8String]);
4312 ns_input_spi_arg = build_string ([arg UTF8String]);
4313 emacs_event->modifiers = EV_MODIFIERS (theEvent);
4314 EV_TRAILER (theEvent);
4324 /* ==========================================================================
4326 EmacsView implementation
4328 ========================================================================== */
4331 @implementation EmacsView
4333 /* needed to inform when window closed from LISP */
4334 - (void) setWindowClosing: (BOOL)closing
4336 windowClosing = closing;
4342 NSTRACE (EmacsView_dealloc);
4348 /* called on font panel selection */
4349 - (void)changeFont: (id)sender
4351 NSEvent *e =[[self window] currentEvent];
4352 struct face *face =FRAME_DEFAULT_FACE (emacsframe);
4356 NSTRACE (changeFont);
4360 if (newFont = [sender convertFont:
4361 ((struct nsfont_info *)face->font)->nsfont])
4363 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4364 emacs_event->modifiers = 0;
4365 emacs_event->code = KEY_NS_CHANGE_FONT;
4367 size = [newFont pointSize];
4368 ns_input_fontsize = make_number (lrint (size));
4369 ns_input_font = build_string ([[newFont familyName] UTF8String]);
4375 - (BOOL)acceptsFirstResponder
4377 NSTRACE (acceptsFirstResponder);
4382 - (void)resetCursorRects
4384 NSRect visible = [self visibleRect];
4385 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
4386 NSTRACE (resetCursorRects);
4388 if (currentCursor == nil)
4389 currentCursor = [NSCursor arrowCursor];
4391 if (!NSIsEmptyRect (visible))
4392 [self addCursorRect: visible cursor: currentCursor];
4393 [currentCursor setOnMouseEntered: YES];
4397 /*****************************************************************************/
4398 /* Keyboard handling. */
4401 - (void)keyDown: (NSEvent *)theEvent
4403 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4405 unsigned fnKeysym = 0;
4407 static NSMutableArray *nsEvArray;
4408 static BOOL firstTime = YES;
4412 /* Rhapsody and OS X give up and down events for the arrow keys */
4413 if ([theEvent type] != NSKeyDown)
4419 if (![[self window] isKeyWindow])
4421 /* XXX: Using NO_SOCK_SIGIO like Carbon causes a condition in which,
4422 when Emacs display updates a different frame from the current one,
4423 and temporarily selects it, then processes some interrupt-driven
4424 input (dispnew.c:3878), OS will send the event to the correct NSWindow,
4425 but for some reason that window has its first responder set to the
4426 NSView most recently updated (I guess), which is not the correct one.
4427 UPDATE: After multi-TTY merge this happens even w/o NO_SOCK_SIGIO */
4428 if ([[theEvent window] isKindOfClass: [EmacsWindow class]])
4429 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
4433 if (nsEvArray == nil)
4434 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
4436 [NSCursor setHiddenUntilMouseMoves: YES];
4438 if (dpyinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
4440 clear_mouse_face (dpyinfo);
4441 dpyinfo->mouse_face_hidden = 1;
4444 if (!processingCompose)
4446 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
4447 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
4448 /* (Carbon way: [theEvent keyCode]) */
4450 /* is it a "function key"? */
4451 fnKeysym = ns_convert_key (code);
4454 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
4455 because Emacs treats Delete and KP-Delete same (in simple.el). */
4456 if (fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
4457 code = 0xFF08; /* backspace */
4462 /* are there modifiers? */
4463 emacs_event->modifiers = 0;
4464 flags = [theEvent modifierFlags];
4466 if (flags & NSHelpKeyMask)
4467 emacs_event->modifiers |= hyper_modifier;
4469 if (flags & NSShiftKeyMask)
4470 emacs_event->modifiers |= shift_modifier;
4472 if (flags & NSCommandKeyMask)
4474 emacs_event->modifiers |= parse_solitary_modifier (ns_command_modifier);
4475 /* if super (default), take input manager's word so things like
4476 dvorak / qwerty layout work */
4477 if (EQ (ns_command_modifier, Qsuper)
4479 && [[theEvent characters] length] != 0)
4481 /* XXX: the code we get will be unshifted, so if we have
4482 a shift modifier, must convert ourselves */
4483 if (!(flags & NSShiftKeyMask))
4484 code = [[theEvent characters] characterAtIndex: 0];
4486 /* this is ugly and also requires linking w/Carbon framework
4487 (for LMGetKbdType) so for now leave this rare (?) case
4488 undealt with.. in future look into CGEvent methods */
4491 long smv = GetScriptManagerVariable (smKeyScript);
4492 Handle uchrHandle = GetResource
4493 ('uchr', GetScriptVariable (smv, smScriptKeys));
4495 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
4496 [[theEvent characters] characterAtIndex: 0],
4497 kUCKeyActionDisplay,
4498 (flags & ~NSCommandKeyMask) >> 8,
4499 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
4500 &dummy, 1, &dummy, &code);
4507 if (flags & NSControlKeyMask)
4508 emacs_event->modifiers |= parse_solitary_modifier (ns_control_modifier);
4510 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
4511 emacs_event->modifiers |= parse_solitary_modifier (ns_function_modifier);
4513 if (flags & NSAlternateKeyMask) /* default = meta */
4515 if (EQ (ns_alternate_modifier, Qnone) && !fnKeysym)
4516 { /* accept pre-interp alt comb */
4517 if ([[theEvent characters] length] > 0)
4518 code = [[theEvent characters] characterAtIndex: 0];
4519 /*HACK: clear lone shift modifier to stop next if from firing */
4520 if (emacs_event->modifiers == shift_modifier)
4521 emacs_event->modifiers = 0;
4524 emacs_event->modifiers |= parse_solitary_modifier (ns_alternate_modifier);
4527 /*fprintf (stderr,"code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",code,fnKeysym,flags,emacs_event->modifiers); */
4529 /* if it was a function key or had modifiers, pass it directly to emacs */
4530 if (fnKeysym || (emacs_event->modifiers
4531 && [[theEvent charactersIgnoringModifiers] length] > 0))
4532 /*[[theEvent characters] length] */
4534 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4536 code |= (1<<28)|(3<<16);
4537 else if (code == 0x7f)
4538 code |= (1<<28)|(3<<16);
4540 emacs_event->kind = code > 0xFF
4541 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4543 emacs_event->code = code;
4544 EV_TRAILER (theEvent);
4549 /* if we get here we should send the key for input manager processing */
4550 if (firstTime && [[NSInputManager currentInputManager]
4551 wantsToDelayTextChangeNotifications] == NO)
4553 "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
4556 if (NS_KEYLOG && !processingCompose)
4557 fprintf (stderr, "Begin compose sequence.\n");
4559 processingCompose = YES;
4560 [nsEvArray addObject: theEvent];
4561 [self interpretKeyEvents: nsEvArray];
4562 [nsEvArray removeObject: theEvent];
4566 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
4569 /* <NSTextInput>: called through when done composing */
4570 - (void)insertText: (id)aString
4573 int len = [(NSString *)aString length];
4576 if (NS_KEYLOG) NSLog (@"insertText '%@'\tlen = %d", aString, len);
4577 processingCompose = NO;
4582 /* first, clear any working text */
4583 if (workingText != nil)
4584 [self deleteWorkingText];
4586 /* now insert the string as keystrokes */
4587 for (i =0; i<len; i++)
4589 code = [aString characterAtIndex: i];
4590 /* TODO: still need this? */
4592 code = '~'; /* 0x7E */
4593 emacs_event->modifiers = 0;
4595 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4596 emacs_event->code = code;
4597 EV_TRAILER ((id)nil);
4602 /* <NSTextInput>: inserts display of composing characters */
4603 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
4605 NSString *str = [aString respondsToSelector: @selector (string)] ?
4606 [aString string] : aString;
4608 NSLog (@"setMarkedText '%@' len =%d range %d from %d", str, [str length],
4609 selRange.length, selRange.location);
4611 if (workingText != nil)
4612 [self deleteWorkingText];
4613 if ([str length] == 0)
4619 processingCompose = YES;
4620 workingText = [str copy];
4621 ns_working_text = build_string ([workingText UTF8String]);
4623 /* if in "echo area", not true minibuffer, can't show chars in interactive
4624 mode, so call using eval; otherwise we send a key event, which was the
4625 original way this was done */
4626 if (!EQ (Feval (Fcons (intern ("ns-in-echo-area"), Qnil)), Qnil))
4628 Feval (Fcons (intern ("ns-echo-working-text"), Qnil));
4629 ns_send_appdefined (-1);
4633 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4634 emacs_event->code = KEY_NS_INSERT_WORKING_TEXT;
4635 EV_TRAILER ((id)nil);
4640 /* delete display of composing characters [not in <NSTextInput>] */
4641 - (void)deleteWorkingText
4643 if (workingText == nil)
4646 fprintf (stderr, "deleteWorkingText len =%d\n", [workingText length]);
4647 [workingText release];
4649 processingCompose = NO;
4654 if (!EQ (Feval (Fcons (intern ("ns-in-echo-area"), Qnil)), Qnil))
4656 Feval (Fcons (intern ("ns-unecho-working-text"), Qnil));
4657 ns_send_appdefined (-1);
4661 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4662 emacs_event->code = KEY_NS_DELETE_WORKING_TEXT;
4663 EV_TRAILER ((id)nil);
4668 - (BOOL)hasMarkedText
4670 return workingText != nil;
4673 - (NSRange)markedRange
4675 NSRange rng = workingText != nil
4676 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
4677 if (NS_KEYLOG) NSLog (@"markedRange request");
4683 if (NS_KEYLOG) NSLog (@"unmark (accept) text");
4684 [self deleteWorkingText];
4685 processingCompose = NO;
4688 /* used to position char selection windows, etc. */
4689 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
4693 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
4694 if (NS_KEYLOG) NSLog (@"firstRectForCharRange request");
4696 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
4697 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
4698 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
4699 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
4700 +FRAME_LINE_HEIGHT (emacsframe));
4702 pt = [self convertPoint: pt toView: nil];
4703 pt = [[self window] convertBaseToScreen: pt];
4708 - (NSInteger)conversationIdentifier
4710 return (NSInteger)self;
4713 /* TODO: below here not yet implemented correctly, but may not be needed */
4715 - (void)doCommandBySelector: (SEL)aSelector
4717 if (NS_KEYLOG) NSLog (@"Do command by selector: %@",
4718 NSStringFromSelector (aSelector));
4720 if (aSelector == @selector (deleteBackward:))
4722 /* happens when user backspaces over an ongoing composition:
4723 throw a 'delete' into the event queue */
4726 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4727 emacs_event->code = 0xFF08;
4728 EV_TRAILER ((id)nil);
4732 - (NSArray *)validAttributesForMarkedText
4734 static NSArray *arr = nil;
4735 if (arr == nil) arr = [NSArray new];
4736 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
4740 - (NSRange)selectedRange
4742 if (NS_KEYLOG) NSLog (@"selectedRange request");
4743 return NSMakeRange (NSNotFound, 0);
4746 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
4748 if (NS_KEYLOG) NSLog (@"characterIndexForPoint request");
4752 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
4754 static NSAttributedString *str = nil;
4755 if (str == nil) str = [NSAttributedString new];
4756 if (NS_KEYLOG) NSLog (@"attributedSubstringFromRange request");
4760 /* End <NSTextInput> impl. */
4761 /*****************************************************************************/
4764 /* This is what happens when the user presses a mouse button. */
4765 - (void)mouseDown: (NSEvent *)theEvent
4767 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
4770 NSTRACE (mouseDown);
4772 [self deleteWorkingText];
4777 last_mouse_frame = emacsframe;
4778 /* appears to be needed to prevent spurious movement events generated on
4780 last_mouse_frame->mouse_moved = 0;
4782 if ([theEvent type] == NSScrollWheel)
4784 float delta = [theEvent deltaY];
4785 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
4788 emacs_event->kind = WHEEL_EVENT;
4789 emacs_event->code = 0;
4790 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
4791 ((delta > 0) ? up_modifier : down_modifier);
4795 emacs_event->kind = MOUSE_CLICK_EVENT;
4796 emacs_event->code = EV_BUTTON (theEvent);
4797 emacs_event->modifiers = EV_MODIFIERS (theEvent)
4798 | EV_UDMODIFIERS (theEvent);
4800 XSETINT (emacs_event->x, lrint (p.x));
4801 XSETINT (emacs_event->y, lrint (p.y));
4802 EV_TRAILER (theEvent);
4806 - (void)mouseUp: (NSEvent *)theEvent
4809 [self mouseDown: theEvent];
4813 - (void)rightMouseDown: (NSEvent *)theEvent
4815 NSTRACE (rightMouseDown);
4816 [self mouseDown: theEvent];
4820 - (void)rightMouseUp: (NSEvent *)theEvent
4822 NSTRACE (rightMouseUp);
4823 [self mouseDown: theEvent];
4827 - (void) scrollWheel: (NSEvent *)theEvent
4829 NSTRACE (scrollWheel);
4830 [self mouseDown: theEvent];
4834 /* Tell emacs the mouse has moved. */
4835 - (void)mouseMoved: (NSEvent *)e
4837 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4840 NSTRACE (mouseMoved);
4842 last_mouse_movement_time = EV_TIMESTAMP (e);
4843 last_mouse_motion_position
4844 = [self convertPoint: [e locationInWindow] fromView: nil];
4846 /* update any mouse face */
4847 if (dpyinfo->mouse_face_hidden)
4849 dpyinfo->mouse_face_hidden = 0;
4850 clear_mouse_face (dpyinfo);
4853 /* tooltip handling */
4854 previous_help_echo_string = help_echo_string;
4855 help_echo_string = Qnil;
4857 if (!note_mouse_movement (emacsframe, last_mouse_motion_position.x,
4858 last_mouse_motion_position.y))
4859 help_echo_string = previous_help_echo_string;
4861 XSETFRAME (frame, emacsframe);
4862 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
4864 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
4865 (note_mouse_highlight), which is called through the
4866 note_mouse_movement () call above */
4867 gen_help_event (help_echo_string, frame, help_echo_window,
4868 help_echo_object, help_echo_pos);
4872 help_echo_string = Qnil;
4873 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
4876 if (emacsframe->mouse_moved && send_appdefined)
4877 ns_send_appdefined (-1);
4881 - (void)mouseDragged: (NSEvent *)e
4883 NSTRACE (mouseDragged);
4884 [self mouseMoved: e];
4888 - (void)rightMouseDragged: (NSEvent *)e
4890 NSTRACE (rightMouseDragged);
4891 [self mouseMoved: e];
4895 - (BOOL)windowShouldClose: (id)sender
4897 NSEvent *e =[[self window] currentEvent];
4899 NSTRACE (windowShouldClose);
4900 windowClosing = YES;
4903 emacs_event->kind = DELETE_WINDOW_EVENT;
4904 emacs_event->modifiers = 0;
4905 emacs_event->code = 0;
4907 /* Don't close this window, let this be done from lisp code. */
4912 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
4913 /* normalize frame to gridded text size */
4915 NSTRACE (windowWillResize);
4916 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
4918 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe,
4919 #ifdef NS_IMPL_GNUSTEP
4920 frameSize.width + 3);
4924 if (cols < MINWIDTH)
4926 frameSize.width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (emacsframe, cols);
4928 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, frameSize.height
4929 #ifdef NS_IMPL_GNUSTEP
4930 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe) + 3
4931 - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
4933 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
4934 - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
4936 if (rows < MINHEIGHT)
4938 frameSize.height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows)
4939 + FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
4940 + FRAME_NS_TOOLBAR_HEIGHT (emacsframe);
4941 #ifdef NS_IMPL_COCOA
4943 /* this sets window title to have size in it; the wm does this under GS */
4944 NSRect r = [[self window] frame];
4945 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
4956 NSWindow *window = [self window];
4959 const char *t = [[[self window] title] UTF8String];
4960 char *pos = strstr (t, " — ");
4963 old_title = (char *) xmalloc (strlen (t) + 1);
4964 strcpy (old_title, t);
4966 size_title = xmalloc (strlen (old_title) + 40);
4967 sprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
4968 [window setTitle: [NSString stringWithUTF8String: size_title]];
4973 #endif /* NS_IMPL_COCOA */
4974 /*fprintf (stderr," ...size became %.0f x %.0f (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
4980 - (void)windowDidResize: (NSNotification *)notification
4982 NSWindow *theWindow = [notification object];
4984 #ifdef NS_IMPL_GNUSTEP
4985 /* in GNUstep, at least currently, it's possible to get a didResize
4986 without getting a willResize.. therefore we need to act as if we got
4987 the willResize now */
4988 NSSize sz = [theWindow frame].size;
4989 sz = [self windowWillResize: theWindow toSize: sz];
4990 #endif /* NS_IMPL_GNUSTEP */
4992 NSTRACE (windowDidResize);
4993 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
4995 #ifdef NS_IMPL_COCOA
5001 #endif /* NS_IMPL_COCOA */
5003 if (cols > 0 && rows > 0)
5004 x_set_window_size (emacsframe, 0, cols, rows);
5006 ns_send_appdefined (-1);
5008 /* The following line causes a crash on GNUstep. Adrian Robert
5009 says he doesn't remember why he added this line, but removing it
5010 doesn't seem to cause problems on OSX, either. */
5017 - (void)windowDidBecomeKey: (NSNotification *)notification
5019 int val = ns_lisp_to_cursor_type (get_frame_param (emacsframe, Qcursor_type));
5020 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5021 struct frame *old_focus = dpyinfo->x_focus_frame;
5023 NSTRACE (windowDidBecomeKey);
5025 if (emacsframe != old_focus)
5026 dpyinfo->x_focus_frame = emacsframe;
5027 /*/last_mouse_frame = emacsframe;? */
5031 FRAME_NEW_CURSOR (emacsframe) = val;
5032 /* x_update_cursor (emacsframe, 1); // will happen in ns_frame_rehighlight */
5035 ns_frame_rehighlight (emacsframe);
5039 emacs_event->kind = FOCUS_IN_EVENT;
5040 EV_TRAILER ((id)nil);
5045 - (void)windowDidResignKey: (NSNotification *)notification
5047 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5048 NSTRACE (windowDidResignKey);
5050 if (!windowClosing && [[self window] isVisible] == YES)
5052 FRAME_NEW_CURSOR (emacsframe) = hollow_box;
5053 x_update_cursor (emacsframe, 1);
5054 FRAME_LAST_INACTIVE (emacsframe) = YES;
5057 if (dpyinfo->x_highlight_frame == emacsframe)
5058 dpyinfo->x_highlight_frame = 0;
5059 if (dpyinfo->x_focus_frame == emacsframe)
5060 dpyinfo->x_focus_frame = 0;
5062 if (dpyinfo->mouse_face_mouse_frame == emacsframe)
5064 clear_mouse_face (dpyinfo);
5065 dpyinfo->mouse_face_mouse_frame = 0;
5070 [self deleteWorkingText];
5071 emacs_event->kind = FOCUS_IN_EVENT;
5072 EV_TRAILER ((id)nil);
5077 - (void)windowWillMiniaturize: sender
5079 NSTRACE (windowWillMiniaturize);
5095 - initFrameFromEmacs: (struct frame *)f
5100 NSButton *toggleButton;
5101 int vbextra = NS_SCROLL_BAR_WIDTH (f);
5106 NSTRACE (initFrameFromEmacs);
5109 processingCompose = NO;
5110 scrollbarsNeedingUpdate = 0;
5112 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
5114 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
5115 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
5116 [self initWithFrame: r];
5118 FRAME_NS_VIEW (f) = self;
5122 win = [[EmacsWindow alloc]
5123 initWithContentRect: r
5124 styleMask: (NSResizableWindowMask |
5125 NSMiniaturizableWindowMask |
5126 NSClosableWindowMask)
5127 backing: NSBackingStoreBuffered
5131 f->border_width = wr.size.width - r.size.width;
5132 FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
5134 [win setAcceptsMouseMovedEvents: YES];
5135 [win setDelegate: self];
5136 [win useOptimizedDrawing: YES];
5138 sz.width = FRAME_COLUMN_WIDTH (f);
5139 sz.height = FRAME_LINE_HEIGHT (f);
5140 [win setResizeIncrements: sz];
5142 [[win contentView] addSubview: self];
5145 [self registerForDraggedTypes: ns_drag_types];
5148 name = [NSString stringWithUTF8String:
5149 NILP (tem) ? (unsigned char *)"Emacs" : SDATA (tem)];
5150 [win setTitle: name];
5152 /* toolbar support */
5153 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
5154 [NSString stringWithFormat: @"Emacs Frame %d",
5156 [win setToolbar: toolbar];
5157 [toolbar setVisible: NO];
5158 #ifdef NS_IMPL_COCOA
5159 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
5160 [toggleButton setTarget: self];
5161 [toggleButton setAction: @selector (toggleToolbar: )];
5163 FRAME_NS_TOOLBAR_HEIGHT (f) = 0;
5167 [win setMiniwindowTitle:
5168 [NSString stringWithUTF8String: SDATA (tem)]];
5171 NSScreen *screen = [win screen];
5174 [win setFrameTopLeftPoint: NSMakePoint
5175 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
5176 IN_BOUND (-SCREENMAX,
5177 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
5180 [win makeFirstResponder: self];
5182 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5183 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
5184 [win setBackgroundColor: col];
5185 if ([col alphaComponent] != 1.0)
5186 [win setOpaque: NO];
5188 [self allocateGState];
5195 - (void)windowDidMove: sender
5197 NSWindow *win = [self window];
5198 NSRect r = [win frame];
5199 NSScreen *screen = [win screen];
5200 NSRect sr = [screen frame];
5202 NSTRACE (windowDidMove);
5204 if (!emacsframe->output_data.ns)
5208 emacsframe->left_pos = r.origin.x; /* - sr.origin.x; */
5209 emacsframe->top_pos = sr.size.height -
5210 (r.origin.y + r.size.height); /* + sr.origin.y; */
5214 #ifdef NS_IMPL_COCOA
5215 /* if we don't do this manually, the window will resize but not move */
5216 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
5218 [[self window] setFrame: newFrame display: NO];
5223 /* Implement this to control size of frame on zoom.
5224 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
5225 defaultFrame:(NSRect)defaultFrame; */
5228 - (void)windowDidDeminiaturize: sender
5230 NSTRACE (windowDidDeminiaturize);
5231 if (!emacsframe->output_data.ns)
5233 emacsframe->async_visible = 1;
5234 emacsframe->async_iconified = 0;
5235 windows_or_buffers_changed++;
5239 emacs_event->kind = ICONIFY_EVENT;
5240 EV_TRAILER ((id)nil);
5245 - (void)windowDidExpose: sender
5247 NSTRACE (windowDidExpose);
5248 if (!emacsframe->output_data.ns)
5250 emacsframe->async_visible = 1;
5251 SET_FRAME_GARBAGED (emacsframe);
5253 if (send_appdefined)
5254 ns_send_appdefined (-1);
5258 - (void)windowDidMiniaturize: sender
5260 NSTRACE (windowDidMiniaturize);
5261 if (!emacsframe->output_data.ns)
5264 emacsframe->async_iconified = 1;
5268 emacs_event->kind = ICONIFY_EVENT;
5269 EV_TRAILER ((id)nil);
5274 - (void)mouseEntered: (NSEvent *)theEvent
5276 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5277 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5278 NSTRACE (mouseEntered);
5280 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5284 - (void)mouseExited: (NSEvent *)theEvent
5286 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5288 struct ns_display_info *dpyinfo
5289 = emacsframe ? FRAME_NS_DISPLAY_INFO (emacsframe) : NULL;
5291 NSTRACE (mouseExited);
5293 if (dpyinfo || !emacsframe)
5296 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5298 if (emacsframe == dpyinfo->mouse_face_mouse_frame)
5300 clear_mouse_face (dpyinfo);
5301 dpyinfo->mouse_face_mouse_frame = 0;
5309 if (context_menu_value == -1)
5310 context_menu_value = [sender tag];
5312 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
5313 emacsframe->menu_bar_vector,
5314 (void *)[sender tag]);
5315 ns_send_appdefined (-1);
5320 - (EmacsToolbar *)toolbar
5326 /* this gets called on toolbar button click */
5327 - toolbarClicked: (id)item
5330 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
5332 NSTRACE (toolbarClicked);
5337 /* send first event (for some reason two needed) */
5338 theEvent =[[self window] currentEvent];
5339 emacs_event->kind = TOOL_BAR_EVENT;
5340 XSETFRAME (emacs_event->arg, emacsframe);
5341 EV_TRAILER (theEvent);
5343 emacs_event->kind = TOOL_BAR_EVENT;
5344 /* XSETINT (emacs_event->code, 0); */
5345 emacs_event->arg = AREF (emacsframe->tool_bar_items,
5346 idx + TOOL_BAR_ITEM_KEY);
5347 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5348 EV_TRAILER (theEvent);
5353 - toggleToolbar: (id)sender
5355 Lisp_Object lispFrame;
5356 XSETFRAME (lispFrame, emacsframe);
5357 Feval (Fcons (intern ("ns-toggle-toolbar"), Fcons (lispFrame, Qnil)));
5358 SET_FRAME_GARBAGED (emacsframe);
5359 ns_send_appdefined (-1);
5363 - (void)drawRect: (NSRect)rect
5365 int x = NSMinX (rect), y = NSMinY (rect);
5366 int width = NSWidth (rect), height = NSHeight (rect);
5370 if (!emacsframe || !emacsframe->output_data.ns)
5374 ns_clear_frame_area (emacsframe, x, y, width, height);
5375 expose_frame (emacsframe, x, y, width, height);
5377 emacsframe->async_visible = 1;
5378 emacsframe->async_iconified = 0;
5380 /* SET_FRAME_GARBAGED (emacsframe);
5381 ns_send_appdefined (-1); */
5385 /* NSDraggingDestination protocol methods. Actually this is not really a
5386 protocol, but a category of Object. O well... */
5388 -(unsigned int) draggingEntered: (id <NSDraggingInfo>) sender
5390 NSTRACE (draggingEntered);
5391 return NSDragOperationGeneric;
5395 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
5401 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
5406 NSEvent *theEvent = [[self window] currentEvent];
5409 NSTRACE (performDragOperation);
5414 position = [self convertPoint: [sender draggingLocation] fromView: nil];
5415 x = lrint (position.x); y = lrint (position.y);
5417 pb = [sender draggingPasteboard];
5418 type = [pb availableTypeFromArray: ns_drag_types];
5423 else if ([type isEqualToString: NSFilenamesPboardType])
5426 NSEnumerator *fenum;
5429 if (!(files = [pb propertyListForType: type]))
5432 fenum = [files objectEnumerator];
5433 while ( (file = [fenum nextObject]) )
5435 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5436 emacs_event->code = KEY_NS_DRAG_FILE;
5437 XSETINT (emacs_event->x, x);
5438 XSETINT (emacs_event->y, y);
5439 ns_input_file = append2 (ns_input_file,
5440 build_string ([file UTF8String]));
5441 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5442 EV_TRAILER (theEvent);
5446 else if ([type isEqualToString: NSURLPboardType])
5451 if (!(fileURL = [NSURL URLFromPasteboard: pb]) ||
5452 [fileURL isFileURL] == NO)
5455 file = [fileURL path];
5456 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5457 emacs_event->code = KEY_NS_DRAG_FILE;
5458 XSETINT (emacs_event->x, x);
5459 XSETINT (emacs_event->y, y);
5460 ns_input_file = append2 (ns_input_file, build_string ([file UTF8String]));
5461 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5462 EV_TRAILER (theEvent);
5465 else if ([type isEqualToString: NSStringPboardType]
5466 || [type isEqualToString: NSTabularTextPboardType])
5470 if (! (data = [pb stringForType: type]))
5473 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5474 emacs_event->code = KEY_NS_DRAG_TEXT;
5475 XSETINT (emacs_event->x, x);
5476 XSETINT (emacs_event->y, y);
5477 ns_input_text = build_string ([data UTF8String]);
5478 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5479 EV_TRAILER (theEvent);
5482 else if ([type isEqualToString: NSColorPboardType])
5484 NSColor *c = [NSColor colorFromPasteboard: pb];
5485 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5486 emacs_event->code = KEY_NS_DRAG_COLOR;
5487 XSETINT (emacs_event->x, x);
5488 XSETINT (emacs_event->y, y);
5489 ns_input_color = ns_color_to_lisp (c);
5490 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5491 EV_TRAILER (theEvent);
5494 else if ([type isEqualToString: NSFontPboardType])
5496 /* impl based on GNUstep NSTextView.m */
5497 NSData *data = [pb dataForType: NSFontPboardType];
5498 NSDictionary *dict = [NSUnarchiver unarchiveObjectWithData: data];
5499 NSFont *font = [dict objectForKey: NSFontAttributeName];
5505 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5506 emacs_event->code = KEY_NS_CHANGE_FONT;
5507 XSETINT (emacs_event->x, x);
5508 XSETINT (emacs_event->y, y);
5509 ns_input_font = build_string ([[font fontName] UTF8String]);
5510 snprintf (fontSize, 10, "%f", [font pointSize]);
5511 ns_input_fontsize = build_string (fontSize);
5512 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5513 EV_TRAILER (theEvent);
5518 error ("Invalid data type in dragging pasteboard.");
5524 - validRequestorForSendType: (NSString *)typeSent
5525 returnType: (NSString *)typeReturned
5527 NSTRACE (validRequestorForSendType);
5528 if ([ns_send_types indexOfObjectIdenticalTo: typeSent] != NSNotFound &&
5529 [ns_return_types indexOfObjectIdenticalTo: typeSent] != NSNotFound)
5532 return [super validRequestorForSendType: typeSent
5533 returnType: typeReturned];
5537 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
5538 (gives a miniaturized version of the window); currently we use the latter for
5539 frames whose active buffer doesn't correspond to any file
5540 (e.g., '*scratch*') */
5541 - setMiniwindowImage: (BOOL) setMini
5543 id image = [[self window] miniwindowImage];
5544 NSTRACE (setMiniwindowImage);
5546 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
5547 about "AppleDockIconEnabled" notwithstanding, however the set message
5548 below has its effect nonetheless. */
5549 if (image != emacsframe->output_data.ns->miniimage)
5551 if (image && [image isKindOfClass: [EmacsImage class]])
5553 [[self window] setMiniwindowImage:
5554 setMini ? emacsframe->output_data.ns->miniimage : nil];
5561 - (void) setRows: (int) r andColumns: (int) c
5567 @end /* EmacsView */
5571 /* ==========================================================================
5573 EmacsWindow implementation
5575 ========================================================================== */
5577 @implementation EmacsWindow
5579 /* called only on resize clicks by special case in EmacsApp-sendEvent */
5580 - (void)mouseDown: (NSEvent *)theEvent
5584 NSSize size = [[theEvent window] frame].size;
5585 grabOffset = [theEvent locationInWindow];
5586 grabOffset.x = size.width - grabOffset.x;
5589 [super mouseDown: theEvent];
5594 - (void)mouseUp: (NSEvent *)theEvent
5598 struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
5600 ns_set_name_as_filename (f);
5602 ns_send_appdefined (-1);
5605 [super mouseUp: theEvent];
5609 /* send resize events */
5610 - (void)mouseDragged: (NSEvent *)theEvent
5614 NSPoint p = [theEvent locationInWindow];
5615 NSSize size, vettedSize, origSize = [self frame].size;
5617 size.width = p.x + grabOffset.x;
5618 size.height = origSize.height - p.y + grabOffset.y;
5620 if (size.width == origSize.width && size.height == origSize.height)
5623 vettedSize = [[self delegate] windowWillResize: self toSize: size];
5624 if (vettedSize.width != size.width || vettedSize.height != size.height)
5626 [[NSNotificationCenter defaultCenter]
5627 postNotificationName: NSWindowDidResizeNotification
5632 [super mouseDragged: theEvent];
5635 @end /* EmacsWindow */
5638 /* ==========================================================================
5640 EmacsScroller implementation
5642 ========================================================================== */
5645 @implementation EmacsScroller
5647 /* for repeat button push */
5648 #define SCROLL_BAR_FIRST_DELAY 0.5
5649 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
5651 + (float) scrollerWidth
5653 /* TODO: if we want to allow variable widths, this is the place to do it,
5654 however neither GNUstep nor Cocoa support it very well */
5655 return [NSScroller scrollerWidth];
5659 - initFrame: (NSRect )r window: (Lisp_Object)nwin
5661 NSTRACE (EmacsScroller_initFrame);
5663 r.size.width = [EmacsScroller scrollerWidth];
5664 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
5665 [self setContinuous: YES];
5666 [self setEnabled: YES];
5668 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
5669 locked against the right, top and bottom edges. */
5670 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
5674 pixel_height = NSHeight (r);
5675 min_portion = 20 / pixel_height;
5677 frame = XFRAME (XWINDOW (win)->frame);
5678 if (FRAME_LIVE_P (frame))
5681 EmacsView *view = FRAME_NS_VIEW (frame);
5682 NSView *sview = [[view window] contentView];
5683 NSArray *subs = [sview subviews];
5685 /* disable optimization stopping redraw of other scrollbars */
5686 view->scrollbarsNeedingUpdate = 0;
5687 for (i =[subs count]-1; i >= 0; i--)
5688 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
5689 view->scrollbarsNeedingUpdate++;
5690 [sview addSubview: self];
5693 /* [self setFrame: r]; */
5699 - (void)setFrame: (NSRect)newRect
5701 NSTRACE (EmacsScroller_setFrame);
5703 pixel_height = NSHeight (newRect);
5704 min_portion = 20 / pixel_height;
5705 [super setFrame: newRect];
5707 /* UNBLOCK_INPUT; */
5713 NSTRACE (EmacsScroller_dealloc);
5715 XWINDOW (win)->vertical_scroll_bar = Qnil;
5742 /* ensure other scrollbar updates after deletion */
5743 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
5745 view->scrollbarsNeedingUpdate++;
5746 [self removeFromSuperview];
5754 - (void)resetCursorRects
5756 NSRect visible = [self visibleRect];
5757 NSTRACE (resetCursorRects);
5759 if (!NSIsEmptyRect (visible))
5760 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
5761 [[NSCursor arrowCursor] setOnMouseEntered: YES];
5765 - (int) checkSamePosition: (int) position portion: (int) portion
5768 return em_position ==position && em_portion ==portion && em_whole ==whole
5769 && portion != whole; /* needed for resize empty buf */
5773 - setPosition: (int)position portion: (int)portion whole: (int)whole
5775 NSTRACE (setPosition);
5777 em_position = position;
5778 em_portion = portion;
5781 if (portion >= whole)
5782 [self setFloatValue: 0.0 knobProportion: 1.0];
5786 portion = max ((float)whole*min_portion/pixel_height, portion);
5787 pos = (float)position / (whole - portion);
5788 por = (float)portion/whole;
5789 [self setFloatValue: pos knobProportion: por];
5791 #ifdef NS_IMPL_GNUSTEP
5797 /* FIXME: unused at moment (see ns_mouse_position) at the moment because
5798 drag events will go directly to the EmacsScroller. Leaving in for now. */
5799 -(void)getMouseMotionPart: (int *)part window: (Lisp_Object *)window
5800 x: (Lisp_Object *)x y: ( Lisp_Object *)y
5802 *part = last_hit_part;
5804 XSETINT (*y, pixel_height);
5805 if ([self floatValue] > 0.999)
5806 XSETINT (*x, pixel_height);
5808 XSETINT (*x, pixel_height * [self floatValue]);
5812 /* set up emacs_event */
5813 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
5818 emacs_event->part = last_hit_part;
5819 emacs_event->code = 0;
5820 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
5821 emacs_event->frame_or_window = win;
5822 emacs_event->timestamp = EV_TIMESTAMP (e);
5823 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
5824 emacs_event->arg = Qnil;
5825 XSETINT (emacs_event->x, loc * pixel_height);
5826 XSETINT (emacs_event->y, pixel_height-20);
5828 n_emacs_events_pending++;
5829 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
5830 EVENT_INIT (*emacs_event);
5831 ns_send_appdefined (-1);
5835 /* called manually thru timer to implement repeated button action w/hold-down */
5836 - repeatScroll: (NSTimer *)scrollEntry
5838 NSEvent *e = [[self window] currentEvent];
5839 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
5840 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
5842 /* clear timer if need be */
5843 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
5845 [scroll_repeat_entry invalidate];
5846 [scroll_repeat_entry release];
5847 scroll_repeat_entry = nil;
5853 = [[NSTimer scheduledTimerWithTimeInterval:
5854 SCROLL_BAR_CONTINUOUS_DELAY
5856 selector: @selector (repeatScroll:)
5862 [self sendScrollEventAtLoc: 0 fromEvent: e];
5867 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
5868 mouseDragged events without going into a modal loop. */
5869 - (void)mouseDown: (NSEvent *)e
5872 /* hitPart is only updated AFTER event is passed on */
5873 NSScrollerPart part = [self testPart: [e locationInWindow]];
5874 double inc = 0.0, loc, kloc, pos;
5877 NSTRACE (EmacsScroller_mouseDown);
5881 case NSScrollerDecrementPage:
5882 last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
5883 case NSScrollerIncrementPage:
5884 last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
5885 case NSScrollerDecrementLine:
5886 last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
5887 case NSScrollerIncrementLine:
5888 last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
5889 case NSScrollerKnob:
5890 last_hit_part = scroll_bar_handle; break;
5891 case NSScrollerKnobSlot: /* GNUstep-only */
5892 last_hit_part = scroll_bar_move_ratio; break;
5893 default: /* NSScrollerNoPart? */
5894 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %d\n", part);
5900 pos = 0; /* ignored */
5902 /* set a timer to repeat, as we can't let superclass do this modally */
5904 = [[NSTimer scheduledTimerWithTimeInterval: 0.5
5906 selector: @selector (repeatScroll:)
5913 /* handle, or on GNUstep possibly slot */
5914 NSEvent *fake_event;
5916 /* compute float loc in slot and mouse offset on knob */
5917 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
5919 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
5925 else if (loc >= NSHeight (sr))
5927 loc = NSHeight (sr);
5935 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
5937 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
5939 last_mouse_offset = kloc;
5941 /* if knob, tell emacs a location offset by knob pos
5942 (to indicate top of handle) */
5943 if (part == NSScrollerKnob)
5944 pos = (loc - last_mouse_offset) / NSHeight (sr);
5946 /* else this is a slot click on GNUstep: go straight there */
5947 pos = loc / NSHeight (sr);
5949 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
5950 fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
5951 location: [e locationInWindow]
5952 modifierFlags: [e modifierFlags]
5953 timestamp: [e timestamp]
5954 windowNumber: [e windowNumber]
5955 context: [e context]
5956 eventNumber: [e eventNumber]
5957 clickCount: [e clickCount]
5958 pressure: [e pressure]];
5959 [super mouseUp: fake_event];
5962 if (part != NSScrollerKnob)
5963 [self sendScrollEventAtLoc: pos fromEvent: e];
5967 /* Called as we manually track scroller drags, rather than superclass. */
5968 - (void)mouseDragged: (NSEvent *)e
5974 NSTRACE (EmacsScroller_mouseDragged);
5976 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
5978 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
5985 else if (loc >= NSHeight (sr) + last_mouse_offset)
5987 loc = NSHeight (sr) + last_mouse_offset;
5991 pos = /*(edge ? loc :*/ (loc - last_mouse_offset) / NSHeight (sr);
5992 [self sendScrollEventAtLoc: pos fromEvent: e];
5996 - (void)mouseUp: (NSEvent *)e
5998 if (scroll_repeat_entry)
6000 [scroll_repeat_entry invalidate];
6001 [scroll_repeat_entry release];
6002 scroll_repeat_entry = nil;
6008 /* treat scrollwheel events in the bar as though they were in the main window */
6009 - (void) scrollWheel: (NSEvent *)theEvent
6011 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
6012 [view mouseDown: theEvent];
6015 @end /* EmacsScroller */
6019 /* ==========================================================================
6021 EmacsPrefsController implementation
6023 ========================================================================== */
6026 @implementation EmacsPrefsController
6028 /* in Tiger+, can just do [popup selectItemWithTag: tag]; */
6029 static void selectItemWithTag (NSPopUpButton *popup, int tag)
6031 NSEnumerator *items = [[popup itemArray] objectEnumerator];
6033 while (item = [items nextObject])
6035 if ([item tag] == tag)
6037 [popup selectItem: item];
6045 [NSBundle loadNibNamed: @"preferences" owner: self];
6050 - (void) showForFrame: (struct frame *)f
6053 [self setPanelFromValues];
6054 [prefsWindow makeKeyAndOrderFront: self];
6055 [prefsWindow display];
6059 - (void) setPanelFromValues
6062 = ns_lisp_to_cursor_type (get_frame_param (frame, Qcursor_type));
6063 prevExpandSpace = XFLOATINT (ns_expand_space);
6065 #ifdef NS_IMPL_COCOA
6066 prevUseHighlightColor = ns_use_system_highlight_color;
6069 [expandSpaceSlider setFloatValue: prevExpandSpace];
6070 [cursorTypeMatrix selectCellWithTag: (cursorType == filled_box ? 1 :
6071 (cursorType == bar ? 2 :
6072 (cursorType == underscore ? 3 : 4)))];
6073 selectItemWithTag (alternateModMenu,
6074 parse_solitary_modifier (ns_alternate_modifier));
6075 selectItemWithTag (commandModMenu,
6076 parse_solitary_modifier (ns_command_modifier));
6077 #ifdef NS_IMPL_COCOA
6078 selectItemWithTag (controlModMenu,
6079 parse_solitary_modifier (ns_control_modifier));
6080 selectItemWithTag (functionModMenu,
6081 parse_solitary_modifier (ns_function_modifier));
6082 [smoothFontsCheck setState: (NILP (ns_antialias_text) ? NO : YES)];
6083 [useQuickdrawCheck setState: (NILP (ns_use_qd_smoothing) ? NO : YES)];
6084 [useSysHiliteCheck setState: (NILP (prevUseHighlightColor) ? NO : YES)];
6089 - (void) setValuesFromPanel
6091 int cursorTag = [[cursorTypeMatrix selectedCell] tag];
6092 int altTag = [[alternateModMenu selectedItem] tag];
6093 int cmdTag = [[commandModMenu selectedItem] tag];
6094 #ifdef NS_IMPL_COCOA
6095 int ctrlTag = [[controlModMenu selectedItem] tag];
6096 int fnTag = [[functionModMenu selectedItem] tag];
6098 float expandSpace = [expandSpaceSlider floatValue];
6100 if (expandSpace != prevExpandSpace)
6102 ns_expand_space = make_float (expandSpace);
6103 /* TODO: more needed: store needed metrics in nsfont_info, update
6104 frame default font max_bounds and fontp, recompute faces */
6105 /* FRAME_LINE_HEIGHT (frame) *= (expandSpace / prevExpandSpace);
6106 x_set_window_size (frame, 0, frame->text_cols, frame->text_lines); */
6107 prevExpandSpace = expandSpace;
6109 FRAME_NEW_CURSOR (frame)
6110 = (cursorTag == 1 ? filled_box
6111 : cursorTag == 2 ? bar
6112 : cursorTag == 3 ? underscore : hollow_box);
6113 store_frame_param (frame, Qcursor_type,
6114 ns_cursor_type_to_lisp (FRAME_NEW_CURSOR (frame)));
6115 ns_alternate_modifier = ns_mod_to_lisp (altTag);
6116 ns_command_modifier = ns_mod_to_lisp (cmdTag);
6117 #ifdef NS_IMPL_COCOA
6118 ns_control_modifier = ns_mod_to_lisp (ctrlTag);
6119 ns_function_modifier = ns_mod_to_lisp (fnTag);
6120 ns_antialias_text = [smoothFontsCheck state] ? Qt : Qnil;
6121 ns_use_qd_smoothing = [useQuickdrawCheck state] ? Qt : Qnil;
6122 ns_use_system_highlight_color = [useSysHiliteCheck state] ? Qt : Qnil;
6123 if (! EQ (ns_use_system_highlight_color, prevUseHighlightColor))
6125 prevUseHighlightColor = ns_use_system_highlight_color;
6126 if (EQ (ns_use_system_highlight_color, Qt))
6128 ns_selection_color = [[NSUserDefaults standardUserDefaults]
6129 stringForKey: @"AppleHighlightColor"];
6130 if (ns_selection_color == nil)
6131 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
6134 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
6136 #endif /* NS_IMPL_COCOA */
6137 Fcall_interactively (intern ("ns-save-preferences"), Qnil, Qnil);
6142 - (IBAction)cancel: (id)sender
6144 [prefsWindow close];
6148 - (IBAction)ok: (id)sender
6150 [self setValuesFromPanel];
6151 [prefsWindow close];
6155 - (IBAction)resetToDefaults: (id)sender
6157 ns_set_default_prefs ();
6158 [self setPanelFromValues];
6162 - (IBAction)runHelp: (id)sender
6164 Feval (Fcons (intern ("info"),
6165 Fcons (build_string ("(ns-emacs)Preferences Panel"), Qnil)));
6166 SET_FRAME_GARBAGED (frame);
6167 ns_send_appdefined (-1);
6171 - (IBAction)setColors: (id)sender
6173 Lisp_Object lispFrame;
6174 XSETFRAME (lispFrame, frame);
6175 Fns_popup_color_panel (lispFrame);
6179 - (IBAction)setDefaultFont: (id)sender
6181 Lisp_Object lispFrame;
6182 XSETFRAME (lispFrame, frame);
6183 Fns_popup_font_panel (lispFrame);
6186 @end /* EmacsPrefsController */
6191 /* ==========================================================================
6193 Font-related functions; these used to be in nsfaces.m
6194 The XLFD functions (115 lines) are an abomination that should be removed.
6196 ========================================================================== */
6200 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
6202 struct font *font = XFONT_OBJECT (font_object);
6205 fontset = fontset_from_font (font_object);
6206 FRAME_FONTSET (f) = fontset;
6208 if (FRAME_FONT (f) == font)
6209 /* This font is already set in frame F. There's nothing more to
6213 FRAME_FONT (f) = font;
6215 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
6216 FRAME_COLUMN_WIDTH (f) = font->average_width;
6217 FRAME_SPACE_WIDTH (f) = font->space_width;
6218 FRAME_LINE_HEIGHT (f) = font->height;
6220 compute_fringe_widths (f, 1);
6222 /* Compute the scroll bar width in character columns. */
6223 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
6225 int wid = FRAME_COLUMN_WIDTH (f);
6226 FRAME_CONFIG_SCROLL_BAR_COLS (f)
6227 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
6231 int wid = FRAME_COLUMN_WIDTH (f);
6232 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
6235 /* Now make the frame display the given font. */
6236 if (FRAME_NS_WINDOW (f) != 0)
6237 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
6243 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
6246 ns_font_to_xlfd (NSFont *nsfont)
6247 /* --------------------------------------------------------------------------
6248 Convert an NS font name to an X font name (XLFD).
6249 The string returned is temporarily allocated.
6250 -------------------------------------------------------------------------- */
6252 NSFontManager *mgr = [NSFontManager sharedFontManager];
6253 NSString *sname = [nsfont /*familyName*/fontName];
6254 char *famName = (char *)[sname UTF8String];
6255 char *weightStr = [mgr fontNamed: sname hasTraits: NSBoldFontMask] ?
6257 char *slantStr = [mgr fontNamed: sname hasTraits: NSItalicFontMask] ?
6259 int size = [nsfont pointSize];
6260 int aWidth = lrint (10.0 * [nsfont widthOfString: @"a"]);
6264 /* change '-' to '$' to avoid messing w/XLFD separator */
6265 for (len = strlen (famName), i =0; i<len; i++)
6266 if (famName[i] == '-')
6272 xlfd = [[NSString stringWithFormat:
6273 @"-apple-%s-%s-%s-normal--%d-%d-75-75-m-%d-iso10646-1",
6274 famName, weightStr, slantStr, size, 10*size, aWidth]
6276 /*fprintf (stderr, "converted '%s' to '%s'\n",name,xlfd); */
6281 ns_fontname_to_xlfd (const char *name)
6282 /* --------------------------------------------------------------------------
6283 Convert an NS font name to an X font name (XLFD).
6285 The string returned is temporarily allocated.
6286 -------------------------------------------------------------------------- */
6289 char *weightStr = strcasestr (name, "bold") ? "bold" : "medium";
6290 char *slantStr = strcasestr (name, "italic") || strcasestr (name, "oblique")
6291 || strcasestr (name, "synthital") ? "i" : "r";
6295 /* change '-' to '$' to avoid messing w/XLFD separator, and ' ' to '_' */
6296 bzero (famName, 180);
6297 bcopy (name, famName, max (strlen (name), 179));
6298 for (len =strlen (famName), i =0; i<len; i++)
6300 if (famName[i] == '-')
6302 else if (famName[i] == ' ')
6306 xlfd = [[NSString stringWithFormat:
6307 @"-apple-%s-%s-%s-normal--0-0-75-75-m-0-iso10646-1",
6308 famName, weightStr, slantStr]
6310 /*fprintf (stderr, "converted '%s' to '%s'\n",name,xlfd); */
6316 ns_xlfd_to_fontname (const char *xlfd)
6317 /* --------------------------------------------------------------------------
6318 Convert an X font name (XLFD) to an NS font name.
6319 Only family is used.
6320 The string returned is temporarily allocated.
6321 -------------------------------------------------------------------------- */
6323 char *name = xmalloc (180);
6327 if (!strncmp (xlfd, "--", 2))
6328 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
6330 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
6332 /* stopgap for malformed XLFD input */
6333 if (strlen (name) == 0)
6334 strcpy (name, "Monaco");
6336 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
6337 also uppercase after '-' or ' ' */
6338 name[0] = toupper (name[0]);
6339 for (len =strlen (name), i =0; i<len; i++)
6345 name[i+1] = toupper (name[i+1]);
6347 else if (name[i] == '_')
6351 name[i+1] = toupper (name[i+1]);
6354 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
6355 ret = [[NSString stringWithUTF8String: name] UTF8String];
6364 NSTRACE (syms_of_nsterm);
6365 DEFVAR_LISP ("ns-input-file", &ns_input_file,
6366 "The file specified in the last NS event.");
6367 ns_input_file =Qnil;
6369 DEFVAR_LISP ("ns-input-text", &ns_input_text,
6370 "The data received in the last NS text drag event.");
6371 ns_input_text =Qnil;
6373 DEFVAR_LISP ("ns-working-text", &ns_working_text,
6374 "String for visualizing working composition sequence.");
6375 ns_working_text =Qnil;
6377 DEFVAR_LISP ("ns-input-font", &ns_input_font,
6378 "The font specified in the last NS event.");
6379 ns_input_font =Qnil;
6381 DEFVAR_LISP ("ns-input-fontsize", &ns_input_fontsize,
6382 "The fontsize specified in the last NS event.");
6383 ns_input_fontsize =Qnil;
6385 DEFVAR_LISP ("ns-input-line", &ns_input_line,
6386 "The line specified in the last NS event.");
6387 ns_input_line =Qnil;
6389 DEFVAR_LISP ("ns-input-color", &ns_input_color,
6390 "The color specified in the last NS event.");
6391 ns_input_color =Qnil;
6393 DEFVAR_LISP ("ns-input-spi-name", &ns_input_spi_name,
6394 "The service name specified in the last NS event.");
6395 ns_input_spi_name =Qnil;
6397 DEFVAR_LISP ("ns-input-spi-arg", &ns_input_spi_arg,
6398 "The service argument specified in the last NS event.");
6399 ns_input_spi_arg =Qnil;
6401 DEFVAR_LISP ("ns-alternate-modifier", &ns_alternate_modifier,
6402 "This variable describes the behavior of the alternate or option key.\n\
6403 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6404 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6405 at all, allowing it to be used at a lower level for accented character entry.");
6407 DEFVAR_LISP ("ns-command-modifier", &ns_command_modifier,
6408 "This variable describes the behavior of the command key.\n\
6409 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6411 DEFVAR_LISP ("ns-control-modifier", &ns_control_modifier,
6412 "This variable describes the behavior of the control key.\n\
6413 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6415 DEFVAR_LISP ("ns-function-modifier", &ns_function_modifier,
6416 "This variable describes the behavior of the function key (on laptops).\n\
6417 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6418 Set to none means that the function key is not interpreted by Emacs at all,\n\
6419 allowing it to be used at a lower level for accented character entry.");
6421 DEFVAR_LISP ("ns-expand-space", &ns_expand_space,
6422 "Amount by which spacing between lines is expanded (positive)\n\
6423 or shrunk (negative). Zero (the default) means standard line height.\n\
6424 (This variable should only be read, never set.)");
6426 DEFVAR_LISP ("ns-antialias-text", &ns_antialias_text,
6427 "Non-nil (the default) means to render text antialiased. Only has an effect on OS X Panther and above.");
6429 DEFVAR_LISP ("ns-use-qd-smoothing", &ns_use_qd_smoothing,
6430 "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).");
6432 DEFVAR_LISP ("ns-use-system-highlight-color",
6433 &ns_use_system_highlight_color,
6434 "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'.");
6436 staticpro (&ns_display_name_list);
6437 ns_display_name_list = Qnil;
6439 staticpro (&last_mouse_motion_frame);
6440 last_mouse_motion_frame = Qnil;
6442 /*23: now apparently we need to tell emacs what modifiers there are.. */
6443 Qmodifier_value = intern ("modifier-value");
6444 Qalt = intern ("alt");
6445 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
6446 Qhyper = intern ("hyper");
6447 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
6448 Qmeta = intern ("meta");
6449 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
6450 Qsuper = intern ("super");
6451 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
6452 Qcontrol = intern ("control");
6453 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
6455 /* TODO: move to common code */
6456 DEFVAR_LISP ("x-toolkit-scroll-bars", &Vx_toolkit_scroll_bars,
6457 doc: /* If not nil, Emacs uses toolkit scroll bars. */);
6458 #ifdef USE_TOOLKIT_SCROLL_BARS
6459 Vx_toolkit_scroll_bars = Qt;
6461 Vx_toolkit_scroll_bars = Qnil;
6464 /* these are unsupported but we need the declarations to avoid whining
6465 messages from cus-start.el */
6466 DEFVAR_BOOL ("x-use-underline-position-properties",
6467 &x_use_underline_position_properties,
6468 doc: /* NOT SUPPORTED UNDER NS.
6469 *Non-nil means make use of UNDERLINE_POSITION font properties.
6470 A value of nil means ignore them. If you encounter fonts with bogus
6471 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
6472 to 4.1, set this to nil.
6474 NOTE: Not supported on Mac yet. */);
6475 x_use_underline_position_properties = 0;
6477 DEFVAR_BOOL ("x-underline-at-descent-line",
6478 &x_underline_at_descent_line,
6479 doc: /* NOT SUPPORTED UNDER NS.
6480 *Non-nil means to draw the underline at the same place as the descent line.
6481 A value of nil means to draw the underline according to the value of the
6482 variable `x-use-underline-position-properties', which is usually at the
6483 baseline level. The default value is nil. */);
6484 x_underline_at_descent_line = 0;
6486 /* Tell emacs about this window system. */
6487 Fprovide (intern ("ns"), Qnil);
6488 /* TODO: try to move this back into lisp, ns-win.el loaded too late
6491 Lisp_Object args[3] = { intern ("ns-version-string"), build_string ("9.0"),
6492 build_string ("NS Window system port version number.") };
6493 Fdefconst (Flist (3, args));
6498 // arch-tag: 6eaa8f7d-a69b-4e1c-b43d-ab31defbe0d2