1 /* NeXT/Open/GNUstep / MacOSX communication module.
2 Copyright (C) 1989, 1993, 1994, 2005, 2006, 2008, 2009, 2010
3 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 Originally by Carl Edman
22 Updated by Christian Limpach (chris@nice.ch)
23 OpenStep/Rhapsody port by Scott Bender (sbender@harmony-ds.com)
24 MacOSX/Aqua port by Christophe de Dinechin (descubes@earthlink.net)
25 GNUstep port and post-20 update by Adrian Robert (arobert@cogsci.ucsd.edu)
28 /* This should be the first include, as it may set up #defines affecting
29 interpretation of even the system includes. */
33 #include <sys/types.h>
40 #include "blockinput.h"
41 #include "sysselect.h"
44 #include "character.h"
46 #include "composite.h"
49 #include "termhooks.h"
60 int term_trace_num = 0;
61 #define NSTRACE(x) fprintf (stderr, "%s:%d: [%d] " #x "\n", \
62 __FILE__, __LINE__, ++term_trace_num)
68 /* ==========================================================================
72 ========================================================================== */
74 /* Convert a symbol indexed with an NSxxx value to a value as defined
75 in keyboard.c (lispy_function_key). I hope this is a correct way
77 static unsigned convert_ns_to_X_keysym[] =
79 NSHomeFunctionKey, 0x50,
80 NSLeftArrowFunctionKey, 0x51,
81 NSUpArrowFunctionKey, 0x52,
82 NSRightArrowFunctionKey, 0x53,
83 NSDownArrowFunctionKey, 0x54,
84 NSPageUpFunctionKey, 0x55,
85 NSPageDownFunctionKey, 0x56,
86 NSEndFunctionKey, 0x57,
87 NSBeginFunctionKey, 0x58,
88 NSSelectFunctionKey, 0x60,
89 NSPrintFunctionKey, 0x61,
90 NSExecuteFunctionKey, 0x62,
91 NSInsertFunctionKey, 0x63,
92 NSUndoFunctionKey, 0x65,
93 NSRedoFunctionKey, 0x66,
94 NSMenuFunctionKey, 0x67,
95 NSFindFunctionKey, 0x68,
96 NSHelpFunctionKey, 0x6A,
97 NSBreakFunctionKey, 0x6B,
99 NSF1FunctionKey, 0xBE,
100 NSF2FunctionKey, 0xBF,
101 NSF3FunctionKey, 0xC0,
102 NSF4FunctionKey, 0xC1,
103 NSF5FunctionKey, 0xC2,
104 NSF6FunctionKey, 0xC3,
105 NSF7FunctionKey, 0xC4,
106 NSF8FunctionKey, 0xC5,
107 NSF9FunctionKey, 0xC6,
108 NSF10FunctionKey, 0xC7,
109 NSF11FunctionKey, 0xC8,
110 NSF12FunctionKey, 0xC9,
111 NSF13FunctionKey, 0xCA,
112 NSF14FunctionKey, 0xCB,
113 NSF15FunctionKey, 0xCC,
114 NSF16FunctionKey, 0xCD,
115 NSF17FunctionKey, 0xCE,
116 NSF18FunctionKey, 0xCF,
117 NSF19FunctionKey, 0xD0,
118 NSF20FunctionKey, 0xD1,
119 NSF21FunctionKey, 0xD2,
120 NSF22FunctionKey, 0xD3,
121 NSF23FunctionKey, 0xD4,
122 NSF24FunctionKey, 0xD5,
124 NSBackspaceCharacter, 0x08, /* 8: Not on some KBs. */
125 NSDeleteCharacter, 0xFF, /* 127: Big 'delete' key upper right. */
126 NSDeleteFunctionKey, 0x9F, /* 63272: Del forw key off main array. */
128 NSTabCharacter, 0x09,
129 0x19, 0x09, /* left tab->regular since pass shift */
130 NSCarriageReturnCharacter, 0x0D,
131 NSNewlineCharacter, 0x0D,
132 NSEnterCharacter, 0x8D,
134 0x1B, 0x1B /* escape */
138 /* Lisp communications */
139 Lisp_Object ns_input_file, ns_input_font, ns_input_fontsize, ns_input_line;
140 Lisp_Object ns_input_color, ns_input_text, ns_working_text;
141 Lisp_Object ns_input_spi_name, ns_input_spi_arg;
142 Lisp_Object Vx_toolkit_scroll_bars;
143 static Lisp_Object Qmodifier_value;
144 Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper, Qnone;
145 extern Lisp_Object Qcursor_color, Qcursor_type, Qns, Qleft;
147 /* Specifies which emacs modifier should be generated when NS receives
148 the Alternate modifier. May be Qnone or any of the modifier lisp symbols. */
149 Lisp_Object ns_alternate_modifier;
151 /* Specifies which emacs modifier should be generated when NS receives
152 the right Alternate modifier. Has same values as ns_alternate_modifier plus
153 the value Qleft which means whatever value ns_alternate_modifier has. */
154 Lisp_Object ns_right_alternate_modifier;
156 /* Specifies which emacs modifier should be generated when NS receives
157 the Command modifier. May be any of the modifier lisp symbols. */
158 Lisp_Object ns_command_modifier;
160 /* Specifies which emacs modifier should be generated when NS receives
161 the right Command modifier. Has same values as ns_command_modifier plus
162 the value Qleft which means whatever value ns_command_modifier has. */
163 Lisp_Object ns_right_command_modifier;
165 /* Specifies which emacs modifier should be generated when NS receives
166 the Control modifier. May be any of the modifier lisp symbols. */
167 Lisp_Object ns_control_modifier;
169 /* Specifies which emacs modifier should be generated when NS receives
170 the right Control modifier. Has same values as ns_control_modifier plus
171 the value Qleft which means whatever value ns_control_modifier has. */
172 Lisp_Object ns_right_control_modifier;
174 /* Specifies which emacs modifier should be generated when NS receives
175 the Function modifier (laptops). May be any of the modifier lisp symbols. */
176 Lisp_Object ns_function_modifier;
178 /* Control via default 'GSFontAntiAlias' on OS X and GNUstep. */
179 Lisp_Object ns_antialias_text;
181 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
182 the maximum font size to NOT antialias. On GNUstep there is currently
183 no way to control this behavior. */
184 float ns_antialias_threshold;
186 /* Used to pick up AppleHighlightColor on OS X */
187 NSString *ns_selection_color;
189 /* Confirm on exit. */
190 Lisp_Object ns_confirm_quit;
192 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
193 NSString *ns_app_name = @"Emacs"; /* default changed later */
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 static BOOL ns_fake_keydown = NO;
213 int ns_tmp_flags; /* FIXME */
214 struct nsfont_info *ns_tmp_font; /* FIXME */
215 /*static int debug_lock = 0; */
218 static BOOL send_appdefined = YES;
219 static NSEvent *last_appdefined_event = 0;
220 static NSTimer *timed_entry = 0;
221 static NSTimer *fd_entry = nil;
222 static NSTimer *scroll_repeat_entry = nil;
223 static fd_set select_readfds, t_readfds;
224 static struct timeval select_timeout;
225 static int select_nfds;
226 static NSAutoreleasePool *outerpool;
227 static struct input_event *emacs_event = NULL;
228 static struct input_event *q_event_ptr = NULL;
229 static int n_emacs_events_pending = 0;
230 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
231 *ns_pending_service_args;
232 static BOOL inNsSelect = 0;
234 /* Convert modifiers in a NeXTSTEP event to emacs style modifiers. */
235 #define NS_FUNCTION_KEY_MASK 0x800000
236 #define NSLeftControlKeyMask (0x000001 | NSControlKeyMask)
237 #define NSRightControlKeyMask (0x002000 | NSControlKeyMask)
238 #define NSLeftCommandKeyMask (0x000008 | NSCommandKeyMask)
239 #define NSRightCommandKeyMask (0x000010 | NSCommandKeyMask)
240 #define NSLeftAlternateKeyMask (0x000020 | NSAlternateKeyMask)
241 #define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
242 #define EV_MODIFIERS(e) \
243 ((([e modifierFlags] & NSHelpKeyMask) ? \
244 hyper_modifier : 0) \
245 | (!EQ (ns_right_alternate_modifier, Qleft) && \
246 (([e modifierFlags] & NSRightAlternateKeyMask) \
247 == NSRightAlternateKeyMask) ? \
248 parse_solitary_modifier (ns_right_alternate_modifier) : 0) \
249 | (([e modifierFlags] & NSAlternateKeyMask) ? \
250 parse_solitary_modifier (ns_alternate_modifier) : 0) \
251 | (([e modifierFlags] & NSShiftKeyMask) ? \
252 shift_modifier : 0) \
253 | (!EQ (ns_right_control_modifier, Qleft) && \
254 (([e modifierFlags] & NSRightControlKeyMask) \
255 == NSRightControlKeyMask) ? \
256 parse_solitary_modifier (ns_right_control_modifier) : 0) \
257 | (([e modifierFlags] & NSControlKeyMask) ? \
258 parse_solitary_modifier (ns_control_modifier) : 0) \
259 | (([e modifierFlags] & NS_FUNCTION_KEY_MASK) ? \
260 parse_solitary_modifier (ns_function_modifier) : 0) \
261 | (!EQ (ns_right_command_modifier, Qleft) && \
262 (([e modifierFlags] & NSRightCommandKeyMask) \
263 == NSRightCommandKeyMask) ? \
264 parse_solitary_modifier (ns_right_command_modifier) : 0) \
265 | (([e modifierFlags] & NSCommandKeyMask) ? \
266 parse_solitary_modifier (ns_command_modifier):0))
268 #define EV_UDMODIFIERS(e) \
269 ((([e type] == NSLeftMouseDown) ? down_modifier : 0) \
270 | (([e type] == NSRightMouseDown) ? down_modifier : 0) \
271 | (([e type] == NSOtherMouseDown) ? down_modifier : 0) \
272 | (([e type] == NSLeftMouseDragged) ? down_modifier : 0) \
273 | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
274 | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
275 | (([e type] == NSLeftMouseUp) ? up_modifier : 0) \
276 | (([e type] == NSRightMouseUp) ? up_modifier : 0) \
277 | (([e type] == NSOtherMouseUp) ? up_modifier : 0))
279 #define EV_BUTTON(e) \
280 ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 : \
281 (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
282 [e buttonNumber] - 1)
284 /* Convert the time field to a timestamp in milliseconds. */
285 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
287 /* This is a piece of code which is common to all the event handling
288 methods. Maybe it should even be a function. */
289 #define EV_TRAILER(e) \
291 XSETFRAME (emacs_event->frame_or_window, emacsframe); \
292 if (e) emacs_event->timestamp = EV_TIMESTAMP (e); \
293 n_emacs_events_pending++; \
294 kbd_buffer_store_event_hold (emacs_event, q_event_ptr); \
295 EVENT_INIT (*emacs_event); \
296 ns_send_appdefined (-1); \
299 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
301 /* TODO: get rid of need for these forward declarations */
302 static void ns_condemn_scroll_bars (struct frame *f);
303 static void ns_judge_scroll_bars (struct frame *f);
304 void x_set_frame_alpha (struct frame *f);
306 /* unused variables needed for compatibility reasons */
307 int x_use_underline_position_properties, x_underline_at_descent_line;
308 /* FIXME: figure out what to do with underline_minimum_offset. */
311 /* ==========================================================================
315 ========================================================================== */
319 append2 (Lisp_Object list, Lisp_Object item)
320 /* --------------------------------------------------------------------------
321 Utility to append to a list
322 -------------------------------------------------------------------------- */
324 Lisp_Object array[2];
326 array[1] = Fcons (item, Qnil);
327 return Fnconc (2, &array[0]);
333 /* --------------------------------------------------------------------------
334 Used to allow emacs to find its resources under Emacs.app
335 Called from emacs.c at startup.
336 -------------------------------------------------------------------------- */
338 NSBundle *bundle = [NSBundle mainBundle];
339 NSString *binDir = [bundle bundlePath], *resourceDir = [bundle resourcePath];
340 NSString *resourcePath, *resourcePaths;
342 BOOL onWindows = NO; /* how do I determine this? */
343 NSString *pathSeparator = onWindows ? @";" : @":";
344 NSFileManager *fileManager = [NSFileManager defaultManager];
346 /*NSLog (@"ns_init_paths: '%@'\n%@\n", [[NSBundle mainBundle] bundlePath], [[NSBundle mainBundle] resourcePath]); */
348 /* get bindir from base */
349 range = [resourceDir rangeOfString: @"Contents"];
350 if (range.location != NSNotFound)
352 binDir = [binDir stringByAppendingPathComponent: @"Contents"];
354 binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
358 /* the following based on Andrew Choi's init_mac_osx_environment () */
359 if (!getenv ("EMACSLOADPATH"))
361 NSArray *paths = [resourceDir stringsByAppendingPaths:
362 [NSArray arrayWithObjects:
363 @"site-lisp", @"lisp", @"leim", nil]];
364 NSEnumerator *pathEnum = [paths objectEnumerator];
366 while (resourcePath = [pathEnum nextObject])
368 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
371 if ([resourcePaths length] > 0)
373 = [resourcePaths stringByAppendingString: pathSeparator];
375 = [resourcePaths stringByAppendingString: resourcePath];
378 if ([resourcePaths length] > 0)
379 setenv ("EMACSLOADPATH", [resourcePaths UTF8String], 1);
380 /*NSLog (@"loadPath: '%@'\n", resourcePaths); */
383 if (!getenv ("EMACSPATH"))
385 NSArray *paths = [binDir stringsByAppendingPaths:
386 [NSArray arrayWithObjects: @"bin",
388 NSEnumerator *pathEnum = [paths objectEnumerator];
390 while (resourcePath = [pathEnum nextObject])
392 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
395 if ([resourcePaths length] > 0)
397 = [resourcePaths stringByAppendingString: pathSeparator];
399 = [resourcePaths stringByAppendingString: resourcePath];
402 if ([resourcePaths length] > 0)
403 setenv ("EMACSPATH", [resourcePaths UTF8String], 1);
406 resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
407 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
411 if (!getenv ("EMACSDATA"))
412 setenv ("EMACSDATA", [resourcePath UTF8String], 1);
413 if (!getenv ("EMACSDOC"))
414 setenv ("EMACSDOC", [resourcePath UTF8String], 1);
418 if (!getenv ("INFOPATH"))
420 resourcePath = [resourceDir stringByAppendingPathComponent: @"info"];
421 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
423 setenv ("INFOPATH", [[resourcePath stringByAppendingString: @":"]
425 /* Note, extra colon needed to cause merge w/later user additions. */
431 timeval_subtract (struct timeval *result, struct timeval x, struct timeval y)
432 /* --------------------------------------------------------------------------
433 Subtract the `struct timeval' values X and Y, storing the result in RESULT.
434 Return 1 if the difference is negative, otherwise 0.
435 -------------------------------------------------------------------------- */
437 /* Perform the carry for the later subtraction by updating y.
438 This is safer because on some systems
439 the tv_sec member is unsigned. */
440 if (x.tv_usec < y.tv_usec)
442 int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
443 y.tv_usec -= 1000000 * nsec;
446 if (x.tv_usec - y.tv_usec > 1000000)
448 int nsec = (y.tv_usec - x.tv_usec) / 1000000;
449 y.tv_usec += 1000000 * nsec;
453 /* Compute the time remaining to wait. tv_usec is certainly positive. */
454 result->tv_sec = x.tv_sec - y.tv_sec;
455 result->tv_usec = x.tv_usec - y.tv_usec;
457 /* Return indication of whether the result should be considered negative. */
458 return x.tv_sec < y.tv_sec;
462 ns_timeout (int usecs)
463 /* --------------------------------------------------------------------------
464 Blocking timer utility used by ns_ring_bell
465 -------------------------------------------------------------------------- */
467 struct timeval wakeup;
469 EMACS_GET_TIME (wakeup);
471 /* Compute time to wait until, propagating carry from usecs. */
472 wakeup.tv_usec += usecs;
473 wakeup.tv_sec += (wakeup.tv_usec / 1000000);
474 wakeup.tv_usec %= 1000000;
476 /* Keep waiting until past the time wakeup. */
479 struct timeval timeout;
481 EMACS_GET_TIME (timeout);
483 /* In effect, timeout = wakeup - timeout.
484 Break if result would be negative. */
485 if (timeval_subtract (&timeout, wakeup, timeout))
488 /* Try to wait that long--but we might wake up sooner. */
489 select (0, NULL, NULL, NULL, &timeout);
495 ns_release_object (void *obj)
496 /* --------------------------------------------------------------------------
497 Release an object (callable from C)
498 -------------------------------------------------------------------------- */
505 ns_retain_object (void *obj)
506 /* --------------------------------------------------------------------------
507 Retain an object (callable from C)
508 -------------------------------------------------------------------------- */
515 ns_alloc_autorelease_pool (void)
516 /* --------------------------------------------------------------------------
517 Allocate a pool for temporary objects (callable from C)
518 -------------------------------------------------------------------------- */
520 return [[NSAutoreleasePool alloc] init];
525 ns_release_autorelease_pool (void *pool)
526 /* --------------------------------------------------------------------------
527 Free a pool and temporary objects it refers to (callable from C)
528 -------------------------------------------------------------------------- */
530 ns_release_object (pool);
535 /* ==========================================================================
537 Focus (clipping) and screen update
539 ========================================================================== */
542 ns_resize_handle_rect (NSWindow *window)
544 NSRect r = [window frame];
545 r.origin.x = r.size.width - RESIZE_HANDLE_SIZE;
547 r.size.width = r.size.height = RESIZE_HANDLE_SIZE;
553 ns_update_begin (struct frame *f)
554 /* --------------------------------------------------------------------------
555 Prepare for a grouped sequence of drawing calls
556 external (RIF) call; whole frame, called before update_window_begin
557 -------------------------------------------------------------------------- */
559 NSView *view = FRAME_NS_VIEW (f);
560 NSTRACE (ns_update_begin);
562 ns_updating_frame = f;
565 #ifdef NS_IMPL_GNUSTEP
566 uRect = NSMakeRect (0, 0, 0, 0);
572 ns_update_window_begin (struct window *w)
573 /* --------------------------------------------------------------------------
574 Prepare for a grouped sequence of drawing calls
575 external (RIF) call; for one window, called after update_begin
576 -------------------------------------------------------------------------- */
578 struct frame *f = XFRAME (WINDOW_FRAME (w));
579 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
580 NSTRACE (ns_update_window_begin);
583 set_output_cursor (&w->cursor);
587 if (f == hlinfo->mouse_face_mouse_frame)
589 /* Don't do highlighting for mouse motion during the update. */
590 hlinfo->mouse_face_defer = 1;
592 /* If the frame needs to be redrawn,
593 simply forget about any prior mouse highlighting. */
594 if (FRAME_GARBAGED_P (f))
595 hlinfo->mouse_face_window = Qnil;
597 /* (further code for mouse faces ifdef'd out in other terms elided) */
605 ns_update_window_end (struct window *w, int cursor_on_p,
606 int mouse_face_overwritten_p)
607 /* --------------------------------------------------------------------------
608 Finished a grouped sequence of drawing calls
609 external (RIF) call; for one window called before update_end
610 -------------------------------------------------------------------------- */
612 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (XFRAME (w->frame));
614 /* note: this fn is nearly identical in all terms */
615 if (!w->pseudo_window_p)
620 display_and_set_cursor (w, 1,
621 output_cursor.hpos, output_cursor.vpos,
622 output_cursor.x, output_cursor.y);
624 if (draw_window_fringes (w, 1))
625 x_draw_vertical_border (w);
630 /* If a row with mouse-face was overwritten, arrange for
631 frame_up_to_date to redisplay the mouse highlight. */
632 if (mouse_face_overwritten_p)
634 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
635 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
636 hlinfo->mouse_face_window = Qnil;
639 updated_window = NULL;
640 NSTRACE (update_window_end);
645 ns_update_end (struct frame *f)
646 /* --------------------------------------------------------------------------
647 Finished a grouped sequence of drawing calls
648 external (RIF) call; for whole frame, called after update_window_end
649 -------------------------------------------------------------------------- */
651 NSView *view = FRAME_NS_VIEW (f);
653 /* if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
654 MOUSE_HL_INFO (f)->mouse_face_defer = 0;
658 #ifdef NS_IMPL_GNUSTEP
659 /* trigger flush only in the rectangle we tracked as being drawn */
660 [view unlockFocusNeedsFlush: NO];
661 /*fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", uRect.origin.x, uRect.origin.y, uRect.size.width, uRect.size.height); */
662 [view lockFocusInRect: uRect];
666 [[view window] flushWindow];
669 ns_updating_frame = NULL;
670 NSTRACE (ns_update_end);
675 ns_flush (struct frame *f)
676 /* --------------------------------------------------------------------------
678 NS impl is no-op since currently we flush in ns_update_end and elsewhere
679 -------------------------------------------------------------------------- */
686 ns_focus (struct frame *f, NSRect *r, int n)
687 /* --------------------------------------------------------------------------
688 Internal: Focus on given frame. During small local updates this is used to
689 draw, however during large updates, ns_update_begin and ns_update_end are
690 called to wrap the whole thing, in which case these calls are stubbed out.
691 Except, on GNUstep, we accumulate the rectangle being drawn into, because
692 the back end won't do this automatically, and will just end up flushing
694 -------------------------------------------------------------------------- */
696 // NSTRACE (ns_focus);
697 #ifdef NS_IMPL_GNUSTEP
700 u = NSUnionRect (r[0], r[1]);
705 fprintf (stderr, "focus: %d", c++);
706 if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
707 fprintf (stderr, "\n"); */
709 if (f != ns_updating_frame)
711 NSView *view = FRAME_NS_VIEW (f);
712 if (view != focus_view)
714 if (focus_view != NULL)
716 [focus_view unlockFocus];
717 [[focus_view window] flushWindow];
722 #ifdef NS_IMPL_GNUSTEP
723 r ? [view lockFocusInRect: u] : [view lockFocus];
728 /*if (view) debug_lock++; */
730 #ifdef NS_IMPL_GNUSTEP
733 /* more than one rect being drawn into */
736 [view unlockFocus]; /* add prev rect to redraw list */
737 [view lockFocusInRect: u]; /* focus for draw in new rect */
742 #ifdef NS_IMPL_GNUSTEP
745 /* in batch mode, but in GNUstep must still track rectangles explicitly */
746 uRect = (r ? NSUnionRect (uRect, u) : [FRAME_NS_VIEW (f) visibleRect]);
753 [[NSGraphicsContext currentContext] saveGraphicsState];
755 NSRectClipList (r, 2);
764 ns_unfocus (struct frame *f)
765 /* --------------------------------------------------------------------------
766 Internal: Remove focus on given frame
767 -------------------------------------------------------------------------- */
769 // NSTRACE (ns_unfocus);
773 [[NSGraphicsContext currentContext] restoreGraphicsState];
777 if (f != ns_updating_frame)
779 if (focus_view != NULL)
781 [focus_view unlockFocus];
782 [[focus_view window] flushWindow];
791 ns_clip_to_row (struct window *w, struct glyph_row *row, int area, BOOL gc)
792 /* --------------------------------------------------------------------------
793 Internal (but parallels other terms): Focus drawing on given row
794 -------------------------------------------------------------------------- */
796 struct frame *f = XFRAME (WINDOW_FRAME (w));
798 int window_x, window_y, window_width;
800 window_box (w, area, &window_x, &window_y, &window_width, 0);
802 clip_rect.origin.x = window_x - FRAME_INTERNAL_BORDER_WIDTH (f);
803 clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
804 clip_rect.origin.y = max (clip_rect.origin.y, window_y);
805 clip_rect.size.width = window_width + 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
806 clip_rect.size.height = row->visible_height;
808 /* allow a full-height row at the top when requested
809 (used to draw fringe all the way through internal border area) */
810 if (gc && clip_rect.origin.y < 5)
812 clip_rect.origin.y -= FRAME_INTERNAL_BORDER_WIDTH (f);
813 clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
816 /* likewise at bottom */
818 FRAME_PIXEL_HEIGHT (f) - (clip_rect.origin.y + clip_rect.size.height) < 5)
819 clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
821 ns_focus (f, &clip_rect, 1);
826 ns_ring_bell (struct frame *f)
827 /* --------------------------------------------------------------------------
829 -------------------------------------------------------------------------- */
831 NSTRACE (ns_ring_bell);
834 NSAutoreleasePool *pool;
835 struct frame *frame = SELECTED_FRAME ();
839 pool = [[NSAutoreleasePool alloc] init];
841 view = FRAME_NS_VIEW (frame);
845 NSPoint dim = NSMakePoint (128, 128);
848 r.origin.x += (r.size.width - dim.x) / 2;
849 r.origin.y += (r.size.height - dim.y) / 2;
850 r.size.width = dim.x;
851 r.size.height = dim.y;
852 surr = NSInsetRect (r, -2, -2);
853 ns_focus (frame, &surr, 1);
854 [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
855 [ns_lookup_indexed_color (NS_FACE_FOREGROUND
856 (FRAME_DEFAULT_FACE (frame)), frame) set];
858 [[view window] flushWindow];
860 [[view window] restoreCachedImage];
861 [[view window] flushWindow];
875 ns_reset_terminal_modes (struct terminal *terminal)
876 /* Externally called as hook */
878 NSTRACE (ns_reset_terminal_modes);
883 ns_set_terminal_modes (struct terminal *terminal)
884 /* Externally called as hook */
886 NSTRACE (ns_set_terminal_modes);
891 /* ==========================================================================
893 Frame / window manager related functions
895 ========================================================================== */
899 ns_raise_frame (struct frame *f)
900 /* --------------------------------------------------------------------------
901 Bring window to foreground and make it active
902 -------------------------------------------------------------------------- */
904 NSView *view = FRAME_NS_VIEW (f);
907 FRAME_SAMPLE_VISIBILITY (f);
908 if (FRAME_VISIBLE_P (f))
910 [[view window] makeKeyAndOrderFront: NSApp];
917 ns_lower_frame (struct frame *f)
918 /* --------------------------------------------------------------------------
920 -------------------------------------------------------------------------- */
922 NSView *view = FRAME_NS_VIEW (f);
925 [[view window] orderBack: NSApp];
931 ns_frame_raise_lower (struct frame *f, int raise)
932 /* --------------------------------------------------------------------------
934 -------------------------------------------------------------------------- */
936 NSTRACE (ns_frame_raise_lower);
946 ns_frame_rehighlight (struct frame *frame)
947 /* --------------------------------------------------------------------------
948 External (hook): called on things like window switching within frame
949 -------------------------------------------------------------------------- */
951 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
952 struct frame *old_highlight = dpyinfo->x_highlight_frame;
954 NSTRACE (ns_frame_rehighlight);
955 if (dpyinfo->x_focus_frame)
957 dpyinfo->x_highlight_frame
958 = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
959 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
960 : dpyinfo->x_focus_frame);
961 if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
963 FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
964 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
968 dpyinfo->x_highlight_frame = 0;
970 if (dpyinfo->x_highlight_frame &&
971 dpyinfo->x_highlight_frame != old_highlight)
975 x_update_cursor (old_highlight, 1);
976 x_set_frame_alpha (old_highlight);
978 if (dpyinfo->x_highlight_frame)
980 x_update_cursor (dpyinfo->x_highlight_frame, 1);
981 x_set_frame_alpha (dpyinfo->x_highlight_frame);
988 x_make_frame_visible (struct frame *f)
989 /* --------------------------------------------------------------------------
990 External: Show the window (X11 semantics)
991 -------------------------------------------------------------------------- */
993 NSTRACE (x_make_frame_visible);
994 /* XXX: at some points in past this was not needed, as the only place that
995 called this (frame.c:Fraise_frame ()) also called raise_lower;
996 if this ends up the case again, comment this out again. */
997 if (!FRAME_VISIBLE_P (f))
999 f->async_visible = 1;
1006 x_make_frame_invisible (struct frame *f)
1007 /* --------------------------------------------------------------------------
1008 External: Hide the window (X11 semantics)
1009 -------------------------------------------------------------------------- */
1011 NSView * view = FRAME_NS_VIEW (f);
1012 NSTRACE (x_make_frame_invisible);
1014 [[view window] orderOut: NSApp];
1015 f->async_visible = 0;
1016 f->async_iconified = 0;
1021 x_iconify_frame (struct frame *f)
1022 /* --------------------------------------------------------------------------
1023 External: Iconify window
1024 -------------------------------------------------------------------------- */
1026 NSView * view = FRAME_NS_VIEW (f);
1027 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1028 NSTRACE (x_iconify_frame);
1031 if (dpyinfo->x_highlight_frame == f)
1032 dpyinfo->x_highlight_frame = 0;
1034 if ([[view window] windowNumber] <= 0)
1036 /* the window is still deferred. Make it very small, bring it
1037 on screen and order it out. */
1038 NSRect s = { { 100, 100}, {0, 0} };
1040 t = [[view window] frame];
1041 [[view window] setFrame: s display: NO];
1042 [[view window] orderBack: NSApp];
1043 [[view window] orderOut: NSApp];
1044 [[view window] setFrame: t display: NO];
1046 [[view window] miniaturize: NSApp];
1051 x_destroy_window (struct frame *f)
1052 /* --------------------------------------------------------------------------
1053 External: Delete the window
1054 -------------------------------------------------------------------------- */
1056 NSView *view = FRAME_NS_VIEW (f);
1057 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1058 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1059 NSTRACE (x_destroy_window);
1062 [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1066 free_frame_menubar (f);
1068 if (FRAME_FACE_CACHE (f))
1069 free_frame_faces (f);
1071 if (f == dpyinfo->x_focus_frame)
1072 dpyinfo->x_focus_frame = 0;
1073 if (f == dpyinfo->x_highlight_frame)
1074 dpyinfo->x_highlight_frame = 0;
1075 if (f == hlinfo->mouse_face_mouse_frame)
1077 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
1078 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
1079 hlinfo->mouse_face_window = Qnil;
1080 hlinfo->mouse_face_deferred_gc = 0;
1081 hlinfo->mouse_face_mouse_frame = 0;
1084 xfree (f->output_data.ns);
1086 [[view window] close];
1095 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1096 /* --------------------------------------------------------------------------
1097 External: Position the window
1098 -------------------------------------------------------------------------- */
1101 NSView *view = FRAME_NS_VIEW (f);
1103 NSTRACE (x_set_offset);
1109 #ifdef NS_IMPL_GNUSTEP
1111 f->left_pos = 100; /* don't overlap menu */
1114 if (view != nil && (screen = [[view window] screen]))
1115 [[view window] setFrameTopLeftPoint:
1116 NSMakePoint (SCREENMAXBOUND (f->left_pos),
1117 SCREENMAXBOUND ([screen frame].size.height
1118 - NS_TOP_POS (f)))];
1124 x_set_window_size (struct frame *f, int change_grav, int cols, int rows)
1125 /* --------------------------------------------------------------------------
1126 Adjust window pixel size based on given character grid size
1127 Impl is a bit more complex than other terms, need to do some
1128 internal clipping and also pay attention to screen constraints.
1129 -------------------------------------------------------------------------- */
1131 EmacsView *view = FRAME_NS_VIEW (f);
1132 EmacsToolbar *toolbar = [view toolbar];
1133 NSWindow *window = [view window];
1134 NSScreen *screen = [window screen];
1135 NSRect wr = [window frame];
1136 int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1137 int pixelwidth, pixelheight;
1138 static int oldRows, oldCols, oldFontWidth, oldFontHeight;
1140 static struct frame *oldF;
1142 NSTRACE (x_set_window_size);
1146 && rows == oldRows && cols == oldCols
1147 && oldFontWidth == FRAME_COLUMN_WIDTH (f)
1148 && oldFontHeight == FRAME_LINE_HEIGHT (f)
1152 /*fprintf (stderr, "\tsetWindowSize: %d x %d, font size %d x %d\n", cols, rows, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f)); */
1156 check_frame_size (f, &rows, &cols);
1160 oldFontWidth = FRAME_COLUMN_WIDTH (f);
1161 oldFontHeight = FRAME_LINE_HEIGHT (f);
1164 f->scroll_bar_actual_width = NS_SCROLL_BAR_WIDTH (f);
1165 compute_fringe_widths (f, 0);
1167 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols);
1168 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
1170 /* If we have a toolbar, take its height into account. */
1172 /* NOTE: previously this would generate wrong result if toolbar not
1173 yet displayed and fixing toolbar_height=32 helped, but
1174 now (200903) seems no longer needed */
1175 FRAME_TOOLBAR_HEIGHT (f) =
1176 NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1177 - FRAME_NS_TITLEBAR_HEIGHT (f);
1179 FRAME_TOOLBAR_HEIGHT (f) = 0;
1181 wr.size.width = pixelwidth + f->border_width;
1182 wr.size.height = pixelheight + FRAME_NS_TITLEBAR_HEIGHT (f)
1183 + FRAME_TOOLBAR_HEIGHT (f);
1185 /* constrain to screen if we can */
1188 NSSize sz = [screen visibleFrame].size;
1189 NSSize ez = { wr.size.width - sz.width, wr.size.height - sz.height };
1192 int cr = ez.width / FRAME_COLUMN_WIDTH (f) + 1;
1195 wr.size.width -= cr * FRAME_COLUMN_WIDTH (f);
1196 pixelwidth -= cr * FRAME_COLUMN_WIDTH (f);
1200 int rr = ez.height / FRAME_LINE_HEIGHT (f) + 1;
1203 wr.size.height -= rr * FRAME_LINE_HEIGHT (f);
1204 pixelheight -= rr * FRAME_LINE_HEIGHT (f);
1206 wr.origin.x = f->left_pos;
1207 wr.origin.y = [screen frame].size.height - NS_TOP_POS (f)
1211 [view setRows: rows andColumns: cols];
1212 [window setFrame: wr display: YES];
1214 /*fprintf (stderr, "\tx_set_window_size %d, %d\t%d, %d\n", cols, rows, pixelwidth, pixelheight); */
1216 /* This is a trick to compensate for Emacs' managing the scrollbar area
1217 as a fixed number of standard character columns. Instead of leaving
1218 blank space for the extra, we chopped it off above. Now for
1219 left-hand scrollbars, we shift all rendering to the left by the
1220 difference between the real width and Emacs' imagined one. For
1221 right-hand bars, don't worry about it since the extra is never used.
1222 (Obviously doesn't work for vertically split windows tho..) */
1224 NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1225 ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1226 - NS_SCROLL_BAR_WIDTH (f), 0)
1227 : NSMakePoint (0, 0);
1228 [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1229 [view setBoundsOrigin: origin];
1232 change_frame_size (f, rows, cols, 0, 1, 0); /* pretend, delay, safe */
1233 FRAME_PIXEL_WIDTH (f) = pixelwidth;
1234 FRAME_PIXEL_HEIGHT (f) = pixelheight;
1235 /* SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */
1237 mark_window_cursors_off (XWINDOW (f->root_window));
1238 cancel_mouse_face (f);
1245 /* ==========================================================================
1249 ========================================================================== */
1253 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1255 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1256 if (idx < 1 || idx >= color_table->avail)
1258 return color_table->colors[idx];
1263 ns_index_color (NSColor *color, struct frame *f)
1265 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1269 if (!color_table->colors)
1271 color_table->size = NS_COLOR_CAPACITY;
1272 color_table->avail = 1; /* skip idx=0 as marker */
1274 = (NSColor **)xmalloc (color_table->size * sizeof (NSColor *));
1275 color_table->colors[0] = nil;
1276 color_table->empty_indices = [[NSMutableSet alloc] init];
1279 /* do we already have this color ? */
1282 for (i = 1; i < color_table->avail; i++)
1284 if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1286 [color_table->colors[i] retain];
1292 if ([color_table->empty_indices count] > 0)
1294 index = [color_table->empty_indices anyObject];
1295 [color_table->empty_indices removeObject: index];
1296 idx = [index unsignedIntValue];
1300 if (color_table->avail == color_table->size)
1302 color_table->size += NS_COLOR_CAPACITY;
1304 = (NSColor **)xrealloc (color_table->colors,
1305 color_table->size * sizeof (NSColor *));
1307 idx = color_table->avail++;
1310 color_table->colors[idx] = color;
1312 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1318 ns_free_indexed_color (unsigned long idx, struct frame *f)
1320 struct ns_color_table *color_table;
1327 color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1329 if (idx <= 0 || idx >= color_table->size) {
1330 message1("ns_free_indexed_color: Color index out of range.\n");
1334 index = [NSNumber numberWithUnsignedInt: idx];
1335 if ([color_table->empty_indices containsObject: index]) {
1336 message1("ns_free_indexed_color: attempt to free already freed color.\n");
1340 color = color_table->colors[idx];
1342 color_table->colors[idx] = nil;
1343 [color_table->empty_indices addObject: [NSNumber numberWithUnsignedInt: idx]];
1344 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1349 ns_get_color (const char *name, NSColor **col)
1350 /* --------------------------------------------------------------------------
1352 -------------------------------------------------------------------------- */
1353 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1354 X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1355 See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1358 static char hex[20];
1360 float r = -1.0, g, b;
1361 NSString *nsname = [NSString stringWithUTF8String: name];
1363 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1366 if ([nsname isEqualToString: @"ns_selection_color"])
1368 nsname = ns_selection_color;
1369 name = [ns_selection_color UTF8String];
1372 /* First, check for some sort of numeric specification. */
1375 if (name[0] == '0' || name[0] == '1' || name[0] == '.') /* RGB decimal */
1377 NSScanner *scanner = [NSScanner scannerWithString: nsname];
1378 [scanner scanFloat: &r];
1379 [scanner scanFloat: &g];
1380 [scanner scanFloat: &b];
1382 else if (!strncmp(name, "rgb:", 4)) /* A newer X11 format -- rgb:r/g/b */
1384 strncpy (hex, name + 4, 19);
1386 scaling = (strlen(hex) - 2) / 3;
1388 else if (name[0] == '#') /* An old X11 format; convert to newer */
1390 int len = (strlen(name) - 1);
1391 int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1393 scaling = strlen(name+start) / 3;
1394 for (i=0; i<3; i++) {
1395 strncpy(hex + i * (scaling + 1), name + start + i * scaling, scaling);
1396 hex[(i+1) * (scaling + 1) - 1] = '/';
1398 hex[3 * (scaling + 1) - 1] = '\0';
1404 float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1405 if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1415 *col = [NSColor colorWithCalibratedRed: r green: g blue: b alpha: 1.0];
1420 /* Otherwise, color is expected to be from a list */
1422 NSEnumerator *lenum, *cenum;
1426 #ifdef NS_IMPL_GNUSTEP
1427 /* XXX: who is wrong, the requestor or the implementation? */
1428 if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1430 nsname = @"highlightColor";
1433 lenum = [[NSColorList availableColorLists] objectEnumerator];
1434 while ( (clist = [lenum nextObject]) && new == nil)
1436 cenum = [[clist allKeys] objectEnumerator];
1437 while ( (name = [cenum nextObject]) && new == nil )
1439 if ([name compare: nsname
1440 options: NSCaseInsensitiveSearch] == NSOrderedSame )
1441 new = [clist colorWithKey: name];
1447 *col = [new colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1454 ns_get_color_default (const char *name, NSColor *dflt)
1455 /* --------------------------------------------------------------------------
1456 Parse a color or use a default value
1457 -------------------------------------------------------------------------- */
1461 if (ns_get_color (name, &col))
1469 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1470 /* --------------------------------------------------------------------------
1471 Convert a Lisp string object to a NS color
1472 -------------------------------------------------------------------------- */
1474 NSTRACE (ns_lisp_to_color);
1475 if (STRINGP (color))
1476 return ns_get_color (SDATA (color), col);
1477 else if (SYMBOLP (color))
1478 return ns_get_color (SDATA (SYMBOL_NAME (color)), col);
1484 ns_color_to_lisp (NSColor *col)
1485 /* --------------------------------------------------------------------------
1486 Convert a color to a lisp string with the RGB equivalent
1487 -------------------------------------------------------------------------- */
1489 CGFloat red, green, blue, alpha, gray;
1492 NSTRACE (ns_color_to_lisp);
1495 if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1497 if ((str =[[col colorNameComponent] UTF8String]))
1500 return build_string ((char *)str);
1503 [[col colorUsingColorSpaceName: NSCalibratedRGBColorSpace]
1504 getRed: &red green: &green blue: &blue alpha: &alpha];
1505 if (red ==green && red ==blue)
1507 [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1508 getWhite: &gray alpha: &alpha];
1509 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1510 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1512 return build_string (buf);
1515 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1516 lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1519 return build_string (buf);
1524 ns_query_color(void *col, XColor *color_def, int setPixel)
1525 /* --------------------------------------------------------------------------
1526 Get ARGB values out of NSColor col and put them into color_def.
1527 If setPixel, set the pixel to a concatenated version.
1528 and set color_def pixel to the resulting index.
1529 -------------------------------------------------------------------------- */
1533 [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1534 color_def->red = r * 65535;
1535 color_def->green = g * 65535;
1536 color_def->blue = b * 65535;
1538 if (setPixel == YES)
1540 = ARGB_TO_ULONG((int)(a*255),
1541 (int)(r*255), (int)(g*255), (int)(b*255));
1546 ns_defined_color (struct frame *f,
1551 /* --------------------------------------------------------------------------
1552 Return 1 if named color found, and set color_def rgb accordingly.
1553 If makeIndex and alloc are nonzero put the color in the color_table,
1554 and set color_def pixel to the resulting index.
1555 If makeIndex is zero, set color_def pixel to ARGB.
1556 Return 0 if not found
1557 -------------------------------------------------------------------------- */
1560 NSTRACE (ns_defined_color);
1563 if (ns_get_color (name, &col) != 0) /* Color not found */
1568 if (makeIndex && alloc)
1569 color_def->pixel = ns_index_color (col, f);
1570 ns_query_color (col, color_def, !makeIndex);
1577 ns_get_rgb_color (struct frame *f, float r, float g, float b, float a)
1578 /* --------------------------------------------------------------------------
1579 return an autoreleased RGB color
1580 -------------------------------------------------------------------------- */
1582 /*static int c = 1; fprintf (stderr, "color request %d\n", c++); */
1583 if (r < 0.0) r = 0.0;
1584 else if (r > 1.0) r = 1.0;
1585 if (g < 0.0) g = 0.0;
1586 else if (g > 1.0) g = 1.0;
1587 if (b < 0.0) b = 0.0;
1588 else if (b > 1.0) b = 1.0;
1589 if (a < 0.0) a = 0.0;
1590 else if (a > 1.0) a = 1.0;
1591 return (unsigned long) ns_index_color(
1592 [NSColor colorWithCalibratedRed: r green: g blue: b alpha: a], f);
1597 x_set_frame_alpha (struct frame *f)
1598 /* --------------------------------------------------------------------------
1599 change the entire-frame transparency
1600 -------------------------------------------------------------------------- */
1602 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1603 EmacsView *view = FRAME_NS_VIEW (f);
1605 double alpha_min = 1.0;
1607 if (dpyinfo->x_highlight_frame == f)
1608 alpha = f->alpha[0];
1610 alpha = f->alpha[1];
1612 if (FLOATP (Vframe_alpha_lower_limit))
1613 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1614 else if (INTEGERP (Vframe_alpha_lower_limit))
1615 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1619 else if (1.0 < alpha)
1621 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1624 #ifdef NS_IMPL_COCOA
1625 [[view window] setAlphaValue: alpha];
1630 /* ==========================================================================
1634 ========================================================================== */
1638 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1639 /* --------------------------------------------------------------------------
1640 Programmatically reposition mouse pointer in pixel coordinates
1641 -------------------------------------------------------------------------- */
1643 NSTRACE (x_set_mouse_pixel_position);
1646 /* FIXME: this does not work, and what about GNUstep? */
1647 #ifdef NS_IMPL_COCOA
1648 [FRAME_NS_VIEW (f) lockFocus];
1649 PSsetmouse ((float)pix_x, (float)pix_y);
1650 [FRAME_NS_VIEW (f) unlockFocus];
1657 x_set_mouse_position (struct frame *f, int h, int v)
1658 /* --------------------------------------------------------------------------
1659 Programmatically reposition mouse pointer in character coordinates
1660 -------------------------------------------------------------------------- */
1664 pix_x = FRAME_COL_TO_PIXEL_X (f, h) + FRAME_COLUMN_WIDTH (f) / 2;
1665 pix_y = FRAME_LINE_TO_PIXEL_Y (f, v) + FRAME_LINE_HEIGHT (f) / 2;
1667 if (pix_x < 0) pix_x = 0;
1668 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
1670 if (pix_y < 0) pix_y = 0;
1671 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
1673 x_set_mouse_pixel_position (f, pix_x, pix_y);
1678 note_mouse_movement (struct frame *frame, float x, float y)
1679 /* ------------------------------------------------------------------------
1680 Called by EmacsView on mouseMovement events. Passes on
1681 to emacs mainstream code if we moved off of a rect of interest
1682 known as last_mouse_glyph.
1683 ------------------------------------------------------------------------ */
1685 // NSTRACE (note_mouse_movement);
1687 XSETFRAME (last_mouse_motion_frame, frame);
1689 /* Note, this doesn't get called for enter/leave, since we don't have a
1690 position. Those are taken care of in the corresponding NSView methods. */
1692 /* has movement gone beyond last rect we were tracking? */
1693 if (x < last_mouse_glyph.origin.x ||
1694 x >= (last_mouse_glyph.origin.x + last_mouse_glyph.size.width) ||
1695 y < last_mouse_glyph.origin.y ||
1696 y >= (last_mouse_glyph.origin.y + last_mouse_glyph.size.height))
1698 ns_update_begin(frame);
1699 frame->mouse_moved = 1;
1700 note_mouse_highlight (frame, x, y);
1701 remember_mouse_glyph (frame, x, y, &last_mouse_glyph);
1702 ns_update_end(frame);
1711 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1712 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1713 unsigned long *time)
1714 /* --------------------------------------------------------------------------
1715 External (hook): inform emacs about mouse position and hit parts.
1716 If a scrollbar is being dragged, set bar_window, part, x, y, time.
1717 x & y should be position in the scrollbar (the whole bar, not the handle)
1718 and length of scrollbar respectively
1719 -------------------------------------------------------------------------- */
1724 Lisp_Object frame, tail;
1726 struct ns_display_info *dpyinfo;
1728 NSTRACE (ns_mouse_position);
1732 fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1736 dpyinfo = FRAME_NS_DISPLAY_INFO (*fp);
1740 if (last_mouse_scroll_bar != nil && insist == 0)
1742 /* TODO: we do not use this path at the moment because drag events will
1743 go directly to the EmacsScroller. Leaving code in for now. */
1744 [last_mouse_scroll_bar getMouseMotionPart: (int *)part window: bar_window
1746 if (time) *time = last_mouse_movement_time;
1747 last_mouse_scroll_bar = nil;
1751 /* Clear the mouse-moved flag for every frame on this display. */
1752 FOR_EACH_FRAME (tail, frame)
1753 if (FRAME_NS_P (XFRAME (frame))
1754 && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1755 XFRAME (frame)->mouse_moved = 0;
1757 last_mouse_scroll_bar = nil;
1758 if (last_mouse_frame && FRAME_LIVE_P (last_mouse_frame))
1759 f = last_mouse_frame;
1761 f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame
1762 : SELECTED_FRAME ();
1764 if (f && f->output_data.ns) /* TODO: 2nd check no longer needed? */
1766 view = FRAME_NS_VIEW (*fp);
1768 position = [[view window] mouseLocationOutsideOfEventStream];
1769 position = [view convertPoint: position fromView: nil];
1770 remember_mouse_glyph (f, position.x, position.y, &last_mouse_glyph);
1771 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1773 if (bar_window) *bar_window = Qnil;
1774 if (part) *part = 0; /*scroll_bar_handle; */
1776 if (x) XSETINT (*x, lrint (position.x));
1777 if (y) XSETINT (*y, lrint (position.y));
1778 if (time) *time = last_mouse_movement_time;
1788 ns_frame_up_to_date (struct frame *f)
1789 /* --------------------------------------------------------------------------
1790 External (hook): Fix up mouse highlighting right after a full update.
1791 Some highlighting was deferred if GC was happening during
1792 note_mouse_highlight (), while other highlighting was deferred for update.
1793 -------------------------------------------------------------------------- */
1795 NSTRACE (ns_frame_up_to_date);
1799 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1800 if ((hlinfo->mouse_face_deferred_gc || f ==hlinfo->mouse_face_mouse_frame)
1801 /*&& hlinfo->mouse_face_mouse_frame*/)
1805 if (hlinfo->mouse_face_mouse_frame)
1806 note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
1807 hlinfo->mouse_face_mouse_x,
1808 hlinfo->mouse_face_mouse_y);
1809 hlinfo->mouse_face_deferred_gc = 0;
1818 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1819 /* --------------------------------------------------------------------------
1820 External (RIF): set frame mouse pointer type.
1821 -------------------------------------------------------------------------- */
1823 NSTRACE (ns_define_frame_cursor);
1824 if (FRAME_POINTER_TYPE (f) != cursor)
1826 EmacsView *view = FRAME_NS_VIEW (f);
1827 FRAME_POINTER_TYPE (f) = cursor;
1828 [[view window] invalidateCursorRectsForView: view];
1829 /* Redisplay assumes this function also draws the changed frame
1830 cursor, but this function doesn't, so do it explicitly. */
1831 x_update_cursor (f, 1);
1837 /* ==========================================================================
1841 ========================================================================== */
1845 ns_convert_key (unsigned code)
1846 /* --------------------------------------------------------------------------
1847 Internal call used by NSView-keyDown.
1848 -------------------------------------------------------------------------- */
1850 const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym)
1851 / sizeof (convert_ns_to_X_keysym[0]));
1853 /* An array would be faster, but less easy to read. */
1854 for (keysym = 0; keysym < last_keysym; keysym += 2)
1855 if (code == convert_ns_to_X_keysym[keysym])
1856 return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
1858 /* if decide to use keyCode and Carbon table, use this line:
1859 return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
1864 x_get_keysym_name (int keysym)
1865 /* --------------------------------------------------------------------------
1866 Called by keyboard.c. Not sure if the return val is important, except
1868 -------------------------------------------------------------------------- */
1870 static char value[16];
1871 NSTRACE (x_get_keysym_name);
1872 sprintf (value, "%d", keysym);
1878 /* ==========================================================================
1880 Block drawing operations
1882 ========================================================================== */
1886 ns_redraw_scroll_bars (struct frame *f)
1890 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
1891 NSTRACE (ns_judge_scroll_bars);
1892 for (i =[subviews count]-1; i >= 0; i--)
1894 view = [subviews objectAtIndex: i];
1895 if (![view isKindOfClass: [EmacsScroller class]]) continue;
1902 ns_clear_frame (struct frame *f)
1903 /* --------------------------------------------------------------------------
1904 External (hook): Erase the entire frame
1905 -------------------------------------------------------------------------- */
1907 NSView *view = FRAME_NS_VIEW (f);
1910 NSTRACE (ns_clear_frame);
1914 /* comes on initial frame because we have
1915 after-make-frame-functions = select-frame */
1916 if (!FRAME_DEFAULT_FACE (f))
1919 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
1921 output_cursor.hpos = output_cursor.vpos = 0;
1922 output_cursor.x = -1;
1927 ns_focus (f, &r, 1);
1928 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
1932 #ifdef NS_IMPL_COCOA
1933 [[view window] display]; /* redraw resize handle */
1936 /* as of 2006/11 or so this is now needed */
1937 ns_redraw_scroll_bars (f);
1943 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
1944 /* --------------------------------------------------------------------------
1945 External (RIF): Clear section of frame
1946 -------------------------------------------------------------------------- */
1948 NSRect r = NSMakeRect (x, y, width, height);
1949 NSView *view = FRAME_NS_VIEW (f);
1950 struct face *face = FRAME_DEFAULT_FACE (f);
1955 NSTRACE (ns_clear_frame_area);
1957 r = NSIntersectionRect (r, [view frame]);
1958 ns_focus (f, &r, 1);
1959 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
1961 #ifdef NS_IMPL_COCOA
1963 /* clip out the resize handle */
1964 NSWindow *window = [FRAME_NS_VIEW (f) window];
1966 = [view convertRect: ns_resize_handle_rect (window) fromView: nil];
1968 ir = NSIntersectionRect (r, ir);
1969 if (NSIsEmptyRect (ir))
1975 #ifdef NS_IMPL_COCOA
1979 NSRect r1 = r, r2 = r; /* upper and lower non-intersecting */
1980 r1.size.height -= ir.size.height;
1981 r2.origin.y += r1.size.height;
1982 r2.size.width -= ir.size.width;
1983 r2.size.height = ir.size.height;
1996 ns_scroll_run (struct window *w, struct run *run)
1997 /* --------------------------------------------------------------------------
1998 External (RIF): Insert or delete n lines at line vpos
1999 -------------------------------------------------------------------------- */
2001 struct frame *f = XFRAME (w->frame);
2002 int x, y, width, height, from_y, to_y, bottom_y;
2004 NSTRACE (ns_scroll_run);
2006 /* begin copy from other terms */
2007 /* Get frame-relative bounding box of the text display area of W,
2008 without mode lines. Include in this box the left and right
2010 window_box (w, -1, &x, &y, &width, &height);
2012 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2013 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2014 bottom_y = y + height;
2018 /* Scrolling up. Make sure we don't copy part of the mode
2019 line at the bottom. */
2020 if (from_y + run->height > bottom_y)
2021 height = bottom_y - from_y;
2023 height = run->height;
2027 /* Scolling down. Make sure we don't copy over the mode line.
2029 if (to_y + run->height > bottom_y)
2030 height = bottom_y - to_y;
2032 height = run->height;
2034 /* end copy from other terms */
2045 NSRect srcRect = NSMakeRect (x, from_y, width, height);
2046 NSRect dstRect = NSMakeRect (x, to_y, width, height);
2047 NSPoint dstOrigin = NSMakePoint (x, to_y);
2049 ns_focus (f, &dstRect, 1);
2050 NSCopyBits (0, srcRect , dstOrigin);
2059 ns_after_update_window_line (struct glyph_row *desired_row)
2060 /* --------------------------------------------------------------------------
2061 External (RIF): preparatory to fringe update after text was updated
2062 -------------------------------------------------------------------------- */
2064 struct window *w = updated_window;
2068 NSTRACE (ns_after_update_window_line);
2070 /* begin copy from other terms */
2073 if (!desired_row->mode_line_p && !w->pseudo_window_p)
2074 desired_row->redraw_fringe_bitmaps_p = 1;
2076 /* When a window has disappeared, make sure that no rest of
2077 full-width rows stays visible in the internal border.
2078 Under NS this is drawn inside the fringes. */
2079 if (windows_or_buffers_changed
2080 && (f = XFRAME (w->frame),
2081 width = FRAME_INTERNAL_BORDER_WIDTH (f),
2083 && (height = desired_row->visible_height,
2086 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2088 /* Internal border is drawn below the tool bar. */
2089 if (WINDOWP (f->tool_bar_window)
2090 && w == XWINDOW (f->tool_bar_window))
2092 /* end copy from other terms */
2095 if (!desired_row->full_width_p)
2097 int x1 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2098 + WINDOW_LEFT_FRINGE_WIDTH (w);
2099 int x2 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2100 + FRAME_PIXEL_WIDTH (f) - NS_SCROLL_BAR_WIDTH (f)
2101 - WINDOW_RIGHT_FRINGE_WIDTH (w)
2102 - FRAME_INTERNAL_BORDER_WIDTH (f);
2103 ns_clear_frame_area (f, x1, y, width, height);
2104 ns_clear_frame_area (f, x2, y, width, height);
2112 ns_shift_glyphs_for_insert (struct frame *f,
2113 int x, int y, int width, int height,
2115 /* --------------------------------------------------------------------------
2116 External (RIF): copy an area horizontally, don't worry about clearing src
2117 -------------------------------------------------------------------------- */
2119 NSRect srcRect = NSMakeRect (x, y, width, height);
2120 NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2121 NSPoint dstOrigin = dstRect.origin;
2123 NSTRACE (ns_shift_glyphs_for_insert);
2125 ns_focus (f, &dstRect, 1);
2126 NSCopyBits (0, srcRect, dstOrigin);
2132 /* ==========================================================================
2134 Character encoding and metrics
2136 ========================================================================== */
2140 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2141 /* --------------------------------------------------------------------------
2142 External (RIF); compute left/right overhang of whole string and set in s
2143 -------------------------------------------------------------------------- */
2145 struct face *face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2146 struct font *font = s->font; /*face->font; */
2150 struct font_metrics metrics;
2151 unsigned int codes[2];
2152 codes[0] = *(s->char2b);
2153 codes[1] = *(s->char2b + s->nchars - 1);
2155 font->driver->text_extents (font, codes, 2, &metrics);
2156 s->left_overhang = -metrics.lbearing;
2158 = metrics.rbearing > metrics.width
2159 ? metrics.rbearing - metrics.width : 0;
2163 s->left_overhang = 0;
2164 s->right_overhang = ((struct nsfont_info *)font)->ital ?
2165 FONT_HEIGHT (font) * 0.2 : 0;
2171 /* ==========================================================================
2173 Fringe and cursor drawing
2175 ========================================================================== */
2178 extern int max_used_fringe_bitmap;
2180 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2181 struct draw_fringe_bitmap_params *p)
2182 /* --------------------------------------------------------------------------
2183 External (RIF); fringe-related
2184 -------------------------------------------------------------------------- */
2186 struct frame *f = XFRAME (WINDOW_FRAME (w));
2187 struct face *face = p->face;
2189 static EmacsImage **bimgs = NULL;
2190 static int nBimgs = 0;
2191 /* NS-specific: move internal border inside fringe */
2192 int x = p->bx < 0 ? p->x : p->bx;
2193 int wd = p->bx < 0 ? p->wd : p->nx;
2194 BOOL fringeOnVeryLeft
2195 = x - WINDOW_LEFT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w)
2196 - FRAME_INTERNAL_BORDER_WIDTH (f) < 10;
2197 BOOL fringeOnVeryRight
2198 = FRAME_PIXEL_WIDTH (f) - x - wd - FRAME_INTERNAL_BORDER_WIDTH (f)
2199 - WINDOW_RIGHT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w) < 10;
2200 int xAdjust = FRAME_INTERNAL_BORDER_WIDTH (f) *
2201 (fringeOnVeryLeft ? -1 : (fringeOnVeryRight ? 1 : 0));
2203 /* grow bimgs if needed */
2204 if (nBimgs < max_used_fringe_bitmap)
2206 EmacsImage **newBimgs
2207 = xmalloc (max_used_fringe_bitmap * sizeof (EmacsImage *));
2208 memset (newBimgs, 0, max_used_fringe_bitmap * sizeof (EmacsImage *));
2212 memcpy (newBimgs, bimgs, nBimgs * sizeof (EmacsImage *));
2217 nBimgs = max_used_fringe_bitmap;
2220 /* Must clip because of partially visible lines. */
2221 rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
2222 ns_clip_to_row (w, row, -1, YES);
2224 if (p->bx >= 0 && !p->overlay_p)
2226 int yAdjust = rowY - FRAME_INTERNAL_BORDER_WIDTH (f) < 5 ?
2227 -FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2228 int yIncr = FRAME_PIXEL_HEIGHT (f) - (p->by+yAdjust + p->ny) < 5 ?
2229 FRAME_INTERNAL_BORDER_WIDTH (f) : 0
2230 + (yAdjust ? FRAME_INTERNAL_BORDER_WIDTH (f) : 0);
2231 NSRect r = NSMakeRect (p->bx+xAdjust, p->by+yAdjust, p->nx, p->ny+yIncr);
2233 [ns_lookup_indexed_color(face->background, f) set];
2239 NSRect r = NSMakeRect (p->x+xAdjust, p->y, p->wd, p->h);
2240 NSPoint pt = r.origin;
2241 EmacsImage *img = bimgs[p->which - 1];
2245 unsigned short *bits = p->bits + p->dh;
2246 int len = 8 * p->h/8;
2248 unsigned char *cbits = xmalloc (len);
2250 for (i =0; i<len; i++)
2251 cbits[i] = ~(bits[i] & 0xff);
2252 img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2254 bimgs[p->which - 1] = img;
2259 /* Since we composite the bitmap instead of just blitting it, we need
2260 to erase the whole background. */
2261 [ns_lookup_indexed_color(face->background, f) set];
2264 [img setXBMColor: ns_lookup_indexed_color(face->foreground, f)];
2265 [img compositeToPoint: pt operation: NSCompositeSourceOver];
2272 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2273 int x, int y, int cursor_type, int cursor_width,
2274 int on_p, int active_p)
2275 /* --------------------------------------------------------------------------
2276 External call (RIF): draw cursor
2277 (modeled after x_draw_window_cursor
2278 FIXME: cursor_width is effectively bogus -- it sometimes gets set
2279 in xdisp.c set_frame_cursor_types, sometimes left uninitialized;
2280 DON'T USE IT (no other terms do)
2281 -------------------------------------------------------------------------- */
2285 struct frame *f = WINDOW_XFRAME (w);
2286 struct glyph *phys_cursor_glyph;
2288 struct glyph *cursor_glyph;
2290 /* If cursor is out of bounds, don't draw garbage. This can happen
2291 in mini-buffer windows when switching between echo area glyphs
2294 NSTRACE (dumpcursor);
2295 //fprintf(stderr, "drawcursor (%d,%d) activep = %d\tonp = %d\tc_type = %d\twidth = %d\n",x,y, active_p,on_p,cursor_type,cursor_width);
2300 w->phys_cursor_type = cursor_type;
2301 w->phys_cursor_on_p = on_p;
2303 if (cursor_type == NO_CURSOR)
2305 w->phys_cursor_width = 0;
2309 if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2311 if (glyph_row->exact_window_width_line_p
2312 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2314 glyph_row->cursor_in_fringe_p = 1;
2315 draw_fringe_bitmap (w, glyph_row, 0);
2320 get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2322 r.origin.x = fx, r.origin.y = fy;
2324 r.size.width = w->phys_cursor_width;
2326 /* FIXME: if we overwrite the internal border area, it does not get erased;
2327 fix by truncating cursor, but better would be to erase properly */
2328 overspill = r.origin.x + r.size.width -
2329 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, WINDOW_BOX_RIGHT_EDGE_X (w)
2330 - WINDOW_TOTAL_FRINGE_WIDTH (w) - FRAME_INTERNAL_BORDER_WIDTH (f));
2332 r.size.width -= overspill;
2334 /* TODO: only needed in rare cases with last-resort font in HELLO..
2335 should we do this more efficiently? */
2336 ns_clip_to_row (w, glyph_row, -1, NO); /* do ns_focus(f, &r, 1); if remove */
2337 [FRAME_CURSOR_COLOR (f) set];
2339 #ifdef NS_IMPL_COCOA
2340 /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2341 atomic. Cleaner ways of doing this should be investigated.
2342 One way would be to set a global variable DRAWING_CURSOR
2343 when making the call to draw_phys..(), don't focus in that
2344 case, then move the ns_unfocus() here after that call. */
2345 NSDisableScreenUpdates ();
2348 switch (cursor_type)
2352 case FILLED_BOX_CURSOR:
2355 case HOLLOW_BOX_CURSOR:
2357 [FRAME_BACKGROUND_COLOR (f) set];
2358 NSRectFill (NSInsetRect (r, 1, 1));
2359 [FRAME_CURSOR_COLOR (f) set];
2363 s.origin.y += lrint (0.75 * s.size.height);
2364 s.size.height = lrint (s.size.height * 0.25);
2369 s.size.width = min (cursor_width, 2); //FIXME(see above)
2371 /* If the character under cursor is R2L, draw the bar cursor
2372 on the right of its glyph, rather than on the left. */
2373 cursor_glyph = get_phys_cursor_glyph (w);
2374 if ((cursor_glyph->resolved_level & 1) != 0)
2375 s.origin.x += cursor_glyph->pixel_width - s.size.width;
2382 /* draw the character under the cursor */
2383 if (cursor_type != NO_CURSOR)
2384 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2386 #ifdef NS_IMPL_COCOA
2387 NSEnableScreenUpdates ();
2394 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2395 /* --------------------------------------------------------------------------
2396 External (RIF): Draw a vertical line.
2397 -------------------------------------------------------------------------- */
2399 struct frame *f = XFRAME (WINDOW_FRAME (w));
2401 NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2403 NSTRACE (ns_draw_vertical_window_border);
2405 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2407 [ns_lookup_indexed_color(face->foreground, f) set];
2409 ns_focus (f, &r, 1);
2416 show_hourglass (struct atimer *timer)
2418 if (hourglass_shown_p)
2423 /* TODO: add NSProgressIndicator to selected frame (see macfns.c) */
2425 hourglass_shown_p = 1;
2431 hide_hourglass (void)
2433 if (!hourglass_shown_p)
2438 /* TODO: remove NSProgressIndicator from all frames */
2440 hourglass_shown_p = 0;
2446 /* ==========================================================================
2448 Glyph drawing operations
2450 ========================================================================== */
2453 static inline NSRect
2454 ns_fix_rect_ibw (NSRect r, int fibw, int frame_pixel_width)
2455 /* --------------------------------------------------------------------------
2456 Under NS we draw internal borders inside fringes, and want full-width
2457 rendering to go all the way to edge. This function makes that correction.
2458 -------------------------------------------------------------------------- */
2460 if (r.origin.y <= fibw+1)
2462 r.size.height += r.origin.y;
2465 if (r.origin.x <= fibw+1)
2467 r.size.width += r.origin.x;
2470 if (frame_pixel_width - (r.origin.x+r.size.width) <= fibw+1)
2471 r.size.width += fibw;
2478 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2479 /* --------------------------------------------------------------------------
2480 Wrapper utility to account for internal border width on full-width lines,
2481 and allow top full-width rows to hit the frame top. nr should be pointer
2482 to two successive NSRects. Number of rects actually used is returned.
2483 -------------------------------------------------------------------------- */
2485 int n = get_glyph_string_clip_rects (s, nr, 2);
2486 if (s->row->full_width_p)
2488 *nr = ns_fix_rect_ibw (*nr, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2489 FRAME_PIXEL_WIDTH (s->f));
2491 *nr = ns_fix_rect_ibw (*(nr+1), FRAME_INTERNAL_BORDER_WIDTH (s->f),
2492 FRAME_PIXEL_WIDTH (s->f));
2499 ns_draw_box (NSRect r, float thickness, NSColor *col, char left_p, char right_p)
2500 /* --------------------------------------------------------------------------
2501 Draw an unfilled rect inside r, optionally leaving left and/or right open.
2502 Note we can't just use an NSDrawRect command, because of the possibility
2503 of some sides not being drawn, and because the rect will be filled.
2504 -------------------------------------------------------------------------- */
2510 s.size.height = thickness;
2512 s.origin.y += r.size.height - thickness;
2515 s.size.height = r.size.height;
2516 s.origin.y = r.origin.y;
2518 /* left, right (optional) */
2519 s.size.width = thickness;
2524 s.origin.x += r.size.width - thickness;
2531 ns_draw_relief (NSRect r, int thickness, char raised_p,
2532 char top_p, char bottom_p, char left_p, char right_p,
2533 struct glyph_string *s)
2534 /* --------------------------------------------------------------------------
2535 Draw a relief rect inside r, optionally leaving some sides open.
2536 Note we can't just use an NSDrawBezel command, because of the possibility
2537 of some sides not being drawn, and because the rect will be filled.
2538 -------------------------------------------------------------------------- */
2540 static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2541 NSColor *newBaseCol = nil;
2544 NSTRACE (ns_draw_relief);
2548 if (s->face->use_box_color_for_shadows_p)
2550 newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2552 /* else if (s->first_glyph->type == IMAGE_GLYPH
2554 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2556 newBaseCol = IMAGE_BACKGROUND (s->img, s->f, 0);
2560 newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2563 if (newBaseCol == nil)
2564 newBaseCol = [NSColor grayColor];
2566 if (newBaseCol != baseCol) /* TODO: better check */
2569 baseCol = [newBaseCol retain];
2571 lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2573 darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2576 [(raised_p ? lightCol : darkCol) set];
2578 /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2581 sr.size.height = thickness;
2582 if (top_p) NSRectFill (sr);
2585 sr.size.height = r.size.height;
2586 sr.size.width = thickness;
2587 if (left_p) NSRectFill (sr);
2589 [(raised_p ? darkCol : lightCol) set];
2592 sr.size.width = r.size.width;
2593 sr.size.height = thickness;
2594 sr.origin.y += r.size.height - thickness;
2595 if (bottom_p) NSRectFill (sr);
2598 sr.size.height = r.size.height;
2599 sr.origin.y = r.origin.y;
2600 sr.size.width = thickness;
2601 sr.origin.x += r.size.width - thickness;
2602 if (right_p) NSRectFill (sr);
2607 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2608 /* --------------------------------------------------------------------------
2609 Function modeled after x_draw_glyph_string_box ().
2610 Sets up parameters for drawing.
2611 -------------------------------------------------------------------------- */
2613 int right_x, last_x;
2614 char left_p, right_p;
2615 struct glyph *last_glyph;
2620 if (s->hl == DRAW_MOUSE_FACE)
2622 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2624 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2629 thickness = face->box_line_width;
2631 NSTRACE (ns_dumpglyphs_box_or_relief);
2633 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2634 ? WINDOW_RIGHT_EDGE_X (s->w)
2635 : window_box_right (s->w, s->area));
2636 last_glyph = (s->cmp || s->img
2637 ? s->first_glyph : s->first_glyph + s->nchars-1);
2639 right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2640 ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2642 left_p = (s->first_glyph->left_box_line_p
2643 || (s->hl == DRAW_MOUSE_FACE
2644 && (s->prev == NULL || s->prev->hl != s->hl)));
2645 right_p = (last_glyph->right_box_line_p
2646 || (s->hl == DRAW_MOUSE_FACE
2647 && (s->next == NULL || s->next->hl != s->hl)));
2649 r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2651 /* expand full-width row over internal borders */
2652 if (s->row->full_width_p)
2653 r = ns_fix_rect_ibw (r, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2654 FRAME_PIXEL_WIDTH (s->f));
2656 /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
2657 if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
2659 ns_draw_box (r, abs (thickness),
2660 ns_lookup_indexed_color (face->box_color, s->f),
2665 ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2666 1, 1, left_p, right_p, s);
2672 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2673 /* --------------------------------------------------------------------------
2674 Modeled after x_draw_glyph_string_background, which draws BG in
2675 certain cases. Others are left to the text rendering routine.
2676 -------------------------------------------------------------------------- */
2678 NSTRACE (ns_maybe_dumpglyphs_background);
2680 if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2682 int box_line_width = max (s->face->box_line_width, 0);
2683 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2684 || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2687 if (s->hl == DRAW_MOUSE_FACE)
2689 face = FACE_FROM_ID (s->f,
2690 MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2692 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2695 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2697 [(NS_FACE_BACKGROUND (face) != 0
2698 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2699 : FRAME_BACKGROUND_COLOR (s->f)) set];
2702 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (s->f);
2703 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2706 if (s->hl != DRAW_CURSOR)
2708 NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2709 s->background_width,
2710 s->height-2*box_line_width);
2712 /* expand full-width row over internal borders */
2713 if (s->row->full_width_p)
2715 int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2716 if (r.origin.y <= fibw+1 + box_line_width)
2718 r.size.height += r.origin.y;
2721 if (r.origin.x <= fibw+1)
2723 r.size.width += 2*r.origin.x;
2726 if (FRAME_PIXEL_WIDTH (s->f) - (r.origin.x + r.size.width)
2728 r.size.width += fibw;
2734 s->background_filled_p = 1;
2741 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2742 /* --------------------------------------------------------------------------
2743 Renders an image and associated borders.
2744 -------------------------------------------------------------------------- */
2746 EmacsImage *img = s->img->pixmap;
2747 int box_line_vwidth = max (s->face->box_line_width, 0);
2748 int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2749 int bg_x, bg_y, bg_height;
2755 NSTRACE (ns_dumpglyphs_image);
2757 if (s->face->box != FACE_NO_BOX
2758 && s->first_glyph->left_box_line_p && s->slice.x == 0)
2759 x += abs (s->face->box_line_width);
2762 bg_y = s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2763 bg_height = s->height;
2764 /* other terms have this, but was causing problems w/tabbar mode */
2765 /* - 2 * box_line_vwidth; */
2767 if (s->slice.x == 0) x += s->img->hmargin;
2768 if (s->slice.y == 0) y += s->img->vmargin;
2770 /* Draw BG: if we need larger area than image itself cleared, do that,
2771 otherwise, since we composite the image under NS (instead of mucking
2772 with its background color), we must clear just the image area. */
2773 if (s->hl == DRAW_MOUSE_FACE)
2775 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2777 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2780 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2782 if (s->hl == DRAW_CURSOR)
2783 [FRAME_CURSOR_COLOR (s->f) set];
2785 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
2787 if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
2788 || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
2790 br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
2791 s->background_filled_p = 1;
2795 br = NSMakeRect (x, y, s->slice.width, s->slice.height);
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 (br.origin.y <= fibw+1 + box_line_vwidth)
2804 br.size.height += br.origin.y;
2807 if (br.origin.x <= fibw+1 + box_line_vwidth)
2809 br.size.width += br.origin.x;
2812 if (FRAME_PIXEL_WIDTH (s->f) - (br.origin.x + br.size.width) <= fibw+1)
2813 br.size.width += fibw;
2818 /* Draw the image.. do we need to draw placeholder if img ==nil? */
2820 [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
2821 operation: NSCompositeSourceOver];
2823 /* Draw relief, if requested */
2824 if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
2826 if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
2828 th = tool_bar_button_relief >= 0 ?
2829 tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2830 raised_p = (s->hl == DRAW_IMAGE_RAISED);
2834 th = abs (s->img->relief);
2835 raised_p = (s->img->relief > 0);
2838 r.origin.x = x - th;
2839 r.origin.y = y - th;
2840 r.size.width = s->slice.width + 2*th-1;
2841 r.size.height = s->slice.height + 2*th-1;
2842 ns_draw_relief (r, th, raised_p,
2844 s->slice.y + s->slice.height == s->img->height,
2846 s->slice.x + s->slice.width == s->img->width, s);
2849 /* If there is no mask, the background won't be seen,
2850 so draw a rectangle on the image for the cursor.
2851 Do this for all images, getting trancparency right is not reliable. */
2852 if (s->hl == DRAW_CURSOR)
2854 int thickness = abs (s->img->relief);
2855 if (thickness == 0) thickness = 1;
2856 ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
2862 ns_dumpglyphs_stretch (struct glyph_string *s)
2868 if (!s->background_filled_p)
2870 n = ns_get_glyph_string_clip_rect (s, r);
2871 *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
2875 if (!s->row->full_width_p)
2877 /* truncate to avoid overwriting fringe and/or scrollbar */
2878 int overrun = max (0, (s->x + s->background_width)
2879 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
2880 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
2881 r[i].size.width -= overrun;
2883 /* XXX: Try to work between problem where a stretch glyph on
2884 a partially-visible bottom row will clear part of the
2885 modeline, and another where list-buffers headers and similar
2886 rows erroneously have visible_height set to 0. Not sure
2887 where this is coming from as other terms seem not to show. */
2888 r[i].size.height = min (s->height, s->row->visible_height);
2891 /* expand full-width rows over internal borders */
2894 r[i] = ns_fix_rect_ibw (r[i], FRAME_INTERNAL_BORDER_WIDTH (s->f),
2895 FRAME_PIXEL_WIDTH (s->f));
2898 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
2899 overwriting cursor (usually when cursor on a tab) */
2900 if (s->hl == DRAW_CURSOR)
2902 r[i].origin.x += s->width;
2903 r[i].size.width -= s->width;
2907 ns_focus (s->f, r, n);
2909 if (s->hl == DRAW_MOUSE_FACE)
2911 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2913 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2916 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2918 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
2923 s->background_filled_p = 1;
2929 ns_draw_glyph_string (struct glyph_string *s)
2930 /* --------------------------------------------------------------------------
2931 External (RIF): Main draw-text call.
2932 -------------------------------------------------------------------------- */
2934 /* TODO (optimize): focus for box and contents draw */
2937 char box_drawn_p = 0;
2939 NSTRACE (ns_draw_glyph_string);
2941 if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
2944 struct glyph_string *next;
2946 for (width = 0, next = s->next;
2947 next && width < s->right_overhang;
2948 width += next->width, next = next->next)
2949 if (next->first_glyph->type != IMAGE_GLYPH)
2951 if (next->first_glyph->type != STRETCH_GLYPH)
2953 n = ns_get_glyph_string_clip_rect (s->next, r);
2954 ns_focus (s->f, r, n);
2955 ns_maybe_dumpglyphs_background (s->next, 1);
2960 ns_dumpglyphs_stretch (s->next);
2962 next->num_clips = 0;
2966 if (!s->for_overlaps && s->face->box != FACE_NO_BOX
2967 && (s->first_glyph->type == CHAR_GLYPH
2968 || s->first_glyph->type == COMPOSITE_GLYPH))
2970 n = ns_get_glyph_string_clip_rect (s, r);
2971 ns_focus (s->f, r, n);
2972 ns_maybe_dumpglyphs_background (s, 1);
2973 ns_dumpglyphs_box_or_relief (s);
2978 switch (s->first_glyph->type)
2982 n = ns_get_glyph_string_clip_rect (s, r);
2983 ns_focus (s->f, r, n);
2984 ns_dumpglyphs_image (s, r[0]);
2989 ns_dumpglyphs_stretch (s);
2993 case COMPOSITE_GLYPH:
2994 n = ns_get_glyph_string_clip_rect (s, r);
2995 ns_focus (s->f, r, n);
2997 if (s->for_overlaps || (s->cmp_from > 0
2998 && ! s->first_glyph->u.cmp.automatic))
2999 s->background_filled_p = 1;
3001 ns_maybe_dumpglyphs_background
3002 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3004 ns_tmp_flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3005 (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3006 (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3007 NS_DUMPGLYPH_NORMAL));
3008 ns_tmp_font = (struct nsfont_info *)s->face->font;
3009 if (ns_tmp_font == NULL)
3010 ns_tmp_font = (struct nsfont_info *)FRAME_FONT (s->f);
3012 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3014 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3015 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3016 NS_FACE_FOREGROUND (s->face) = tmp;
3019 ns_tmp_font->font.driver->draw
3020 (s, 0, s->nchars, s->x, s->y,
3021 (ns_tmp_flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3022 || ns_tmp_flags == NS_DUMPGLYPH_MOUSEFACE);
3024 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3026 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3027 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3028 NS_FACE_FOREGROUND (s->face) = tmp;
3034 case GLYPHLESS_GLYPH:
3035 n = ns_get_glyph_string_clip_rect (s, r);
3036 ns_focus (s->f, r, n);
3038 if (s->for_overlaps || (s->cmp_from > 0
3039 && ! s->first_glyph->u.cmp.automatic))
3040 s->background_filled_p = 1;
3042 ns_maybe_dumpglyphs_background
3043 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3045 /* Not yet implemented. */
3054 /* Draw box if not done already. */
3055 if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3057 n = ns_get_glyph_string_clip_rect (s, r);
3058 ns_focus (s->f, r, n);
3059 ns_dumpglyphs_box_or_relief (s);
3068 /* ==========================================================================
3072 ========================================================================== */
3076 ns_send_appdefined (int value)
3077 /* --------------------------------------------------------------------------
3078 Internal: post an appdefined event which EmacsApp-sendEvent will
3079 recognize and take as a command to halt the event loop.
3080 -------------------------------------------------------------------------- */
3082 /*NSTRACE (ns_send_appdefined); */
3084 /* Only post this event if we haven't already posted one. This will end
3085 the [NXApp run] main loop after having processed all events queued at
3087 if (send_appdefined)
3091 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
3092 send_appdefined = NO;
3094 /* Don't need wakeup timer any more */
3097 [timed_entry invalidate];
3098 [timed_entry release];
3102 /* Ditto for file descriptor poller */
3105 [fd_entry invalidate];
3110 nxev = [NSEvent otherEventWithType: NSApplicationDefined
3111 location: NSMakePoint (0, 0)
3114 windowNumber: [[NSApp mainWindow] windowNumber]
3115 context: [NSApp context]
3120 /* Post an application defined event on the event queue. When this is
3121 received the [NXApp run] will return, thus having processed all
3122 events which are currently queued. */
3123 [NSApp postEvent: nxev atStart: NO];
3129 ns_read_socket (struct terminal *terminal, int expected,
3130 struct input_event *hold_quit)
3131 /* --------------------------------------------------------------------------
3132 External (hook): Post an event to ourself and keep reading events until
3133 we read it back again. In effect process all events which were waiting.
3134 From 21+ we have to manage the event buffer ourselves.
3135 -------------------------------------------------------------------------- */
3137 struct input_event ev;
3140 /* NSTRACE (ns_read_socket); */
3142 if (interrupt_input_blocked)
3144 interrupt_input_pending = 1;
3146 pending_signals = 1;
3151 interrupt_input_pending = 0;
3153 pending_signals = pending_atimers;
3157 n_emacs_events_pending = 0;
3160 q_event_ptr = hold_quit;
3162 /* we manage autorelease pools by allocate/reallocate each time around
3163 the loop; strict nesting is occasionally violated but seems not to
3164 matter.. earlier methods using full nesting caused major memory leaks */
3165 [outerpool release];
3166 outerpool = [[NSAutoreleasePool alloc] init];
3168 /* If have pending open-file requests, attend to the next one of those. */
3169 if (ns_pending_files && [ns_pending_files count] != 0
3170 && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3172 [ns_pending_files removeObjectAtIndex: 0];
3174 /* Deal with pending service requests. */
3175 else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3177 NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3178 withArg: [ns_pending_service_args objectAtIndex: 0]])
3180 [ns_pending_service_names removeObjectAtIndex: 0];
3181 [ns_pending_service_args removeObjectAtIndex: 0];
3185 /* Run and wait for events. We must always send one NX_APPDEFINED event
3186 to ourself, otherwise [NXApp run] will never exit. */
3187 send_appdefined = YES;
3189 /* If called via ns_select, this is called once with expected=1,
3190 because we expect either the timeout or file descriptor activity.
3191 In this case the first event through will either be real input or
3192 one of these. read_avail_input() then calls once more with expected=0
3193 and in that case we need to return quickly if there is nothing.
3194 If we're being called outside of that, it's also OK to return quickly
3195 after one iteration through the event loop, since other terms do
3196 this and emacs expects it. */
3197 if (!(inNsSelect && expected))
3199 /* Post an application defined event on the event queue. When this is
3200 received the [NXApp run] will return, thus having processed all
3201 events which are currently queued, if any. */
3202 ns_send_appdefined (-1);
3208 nevents = n_emacs_events_pending;
3209 n_emacs_events_pending = 0;
3210 emacs_event = q_event_ptr = NULL;
3218 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3219 fd_set *exceptfds, struct timeval *timeout)
3220 /* --------------------------------------------------------------------------
3221 Replacement for select, checking for events
3222 -------------------------------------------------------------------------- */
3227 /* NSTRACE (ns_select); */
3229 if (NSApp == nil || inNsSelect == 1 /* || ([NSApp isActive] == NO &&
3230 [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
3231 inMode:NSDefaultRunLoopMode dequeue:NO] == nil) */)
3232 return select (nfds, readfds, writefds, exceptfds, timeout);
3234 /* Save file descriptor set, which gets overwritten in calls to select ()
3235 Note, this is called from process.c, and only readfds is ever set */
3238 memcpy (&select_readfds, readfds, sizeof (fd_set));
3244 /* Try an initial select for pending data on input files */
3245 select_timeout.tv_sec = select_timeout.tv_usec = 0;
3246 result = select (nfds, readfds, writefds, exceptfds, &select_timeout);
3250 /* if (!timeout || timed_entry || fd_entry)
3251 fprintf (stderr, "assertion failed: timeout null or timed_entry/fd_entry non-null in ns_select\n"); */
3253 /* set a timeout and run the main AppKit event loop while continuing
3254 to monitor the files */
3255 time = ((double) timeout->tv_sec) + ((double) timeout->tv_usec)/1000000.0;
3256 timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3258 selector: @selector (timeout_handler:)
3260 repeats: YES] /* for safe removal */
3263 /* set a periodic task to try the select () again */
3264 fd_entry = [[NSTimer scheduledTimerWithTimeInterval: 0.1
3266 selector: @selector (fd_handler:)
3271 /* Let Application dispatch events until it receives an event of the type
3272 NX_APPDEFINED, which should only be sent by timeout_handler.
3273 We tell read_avail_input() that input is "expected" because we do expect
3274 either the timeout or fd handler to fire, and if they don't, the original
3275 call from process.c that got us here expects us to wait until some input
3279 ev = last_appdefined_event;
3285 if ([ev type] != NSApplicationDefined)
3289 last_appdefined_event = 0;
3293 /* The NX_APPDEFINED event we received was a timeout. */
3298 /* The NX_APPDEFINED event we received was the result of
3299 at least one real input event arriving. */
3305 /* Received back from select () in fd_handler; copy the results */
3307 memcpy (readfds, &select_readfds, sizeof (fd_set));
3311 /* never reached, shut compiler up */
3317 /* ==========================================================================
3321 ========================================================================== */
3325 ns_set_vertical_scroll_bar (struct window *window,
3326 int portion, int whole, int position)
3327 /* --------------------------------------------------------------------------
3328 External (hook): Update or add scrollbar
3329 -------------------------------------------------------------------------- */
3333 struct frame *f = XFRAME (WINDOW_FRAME (window));
3334 EmacsView *view = FRAME_NS_VIEW (f);
3335 int window_y, window_height;
3336 BOOL barOnVeryLeft, barOnVeryRight;
3337 int top, left, height, width, sb_width, sb_left;
3339 static int count = 0;
3341 /* optimization; display engine sends WAY too many of these.. */
3342 if (!NILP (window->vertical_scroll_bar))
3344 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3345 if ([bar checkSamePosition: position portion: portion whole: whole])
3347 if (view->scrollbarsNeedingUpdate == 0)
3349 if (!windows_or_buffers_changed)
3353 view->scrollbarsNeedingUpdate--;
3357 NSTRACE (ns_set_vertical_scroll_bar);
3359 /* Get dimensions. */
3360 window_box (window, -1, 0, &window_y, 0, &window_height);
3362 height = window_height;
3363 width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3364 left = WINDOW_SCROLL_BAR_AREA_X (window);
3366 if (top < 5) /* top scrollbar adjustment */
3368 top -= FRAME_INTERNAL_BORDER_WIDTH (f);
3369 height += FRAME_INTERNAL_BORDER_WIDTH (f);
3372 /* allow for displaying a skinnier scrollbar than char area allotted */
3373 sb_width = (WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) > 0) ?
3374 WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) : width;
3376 barOnVeryLeft = left < 5;
3377 barOnVeryRight = FRAME_PIXEL_WIDTH (f) - left - width < 5;
3378 sb_left = left + FRAME_INTERNAL_BORDER_WIDTH (f)
3379 * (barOnVeryLeft ? -1 : (barOnVeryRight ? 1 : 0));
3381 r = NSMakeRect (sb_left, top, sb_width, height);
3382 /* the parent view is flipped, so we need to flip y value */
3384 r.origin.y = (v.size.height - r.size.height - r.origin.y);
3386 XSETWINDOW (win, window);
3389 /* we want at least 5 lines to display a scrollbar */
3390 if (WINDOW_TOTAL_LINES (window) < 5)
3392 if (!NILP (window->vertical_scroll_bar))
3394 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3395 [bar removeFromSuperview];
3396 window->vertical_scroll_bar = Qnil;
3398 ns_clear_frame_area (f, sb_left, top, width, height);
3403 if (NILP (window->vertical_scroll_bar))
3405 ns_clear_frame_area (f, sb_left, top, width, height);
3406 bar = [[EmacsScroller alloc] initFrame: r window: win];
3407 window->vertical_scroll_bar = make_save_value (bar, 0);
3412 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3413 oldRect = [bar frame];
3414 r.size.width = oldRect.size.width;
3415 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3417 if (oldRect.origin.x != r.origin.x)
3418 ns_clear_frame_area (f, sb_left, top, width, height);
3423 [bar setPosition: position portion: portion whole: whole];
3429 ns_condemn_scroll_bars (struct frame *f)
3430 /* --------------------------------------------------------------------------
3431 External (hook): arrange for all frame's scrollbars to be removed
3432 at next call to judge_scroll_bars, except for those redeemed.
3433 -------------------------------------------------------------------------- */
3437 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3439 NSTRACE (ns_condemn_scroll_bars);
3441 for (i =[subviews count]-1; i >= 0; i--)
3443 view = [subviews objectAtIndex: i];
3444 if ([view isKindOfClass: [EmacsScroller class]])
3451 ns_redeem_scroll_bar (struct window *window)
3452 /* --------------------------------------------------------------------------
3453 External (hook): arrange to spare this window's scrollbar
3454 at next call to judge_scroll_bars.
3455 -------------------------------------------------------------------------- */
3458 NSTRACE (ns_redeem_scroll_bar);
3459 if (!NILP (window->vertical_scroll_bar))
3461 bar =XNS_SCROLL_BAR (window->vertical_scroll_bar);
3468 ns_judge_scroll_bars (struct frame *f)
3469 /* --------------------------------------------------------------------------
3470 External (hook): destroy all scrollbars on frame that weren't
3471 redeemed after call to condemn_scroll_bars.
3472 -------------------------------------------------------------------------- */
3476 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3477 NSTRACE (ns_judge_scroll_bars);
3478 for (i =[subviews count]-1; i >= 0; i--)
3480 view = [subviews objectAtIndex: i];
3481 if (![view isKindOfClass: [EmacsScroller class]]) continue;
3488 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
3490 /* XXX irrelevant under NS */
3495 /* ==========================================================================
3499 ========================================================================== */
3502 x_display_pixel_height (struct ns_display_info *dpyinfo)
3504 NSScreen *screen = [NSScreen mainScreen];
3505 return [screen frame].size.height;
3509 x_display_pixel_width (struct ns_display_info *dpyinfo)
3511 NSScreen *screen = [NSScreen mainScreen];
3512 return [screen frame].size.width;
3516 static Lisp_Object ns_string_to_lispmod (const char *s)
3517 /* --------------------------------------------------------------------------
3518 Convert modifier name to lisp symbol
3519 -------------------------------------------------------------------------- */
3521 if (!strncmp (SDATA (SYMBOL_NAME (Qmeta)), s, 10))
3523 else if (!strncmp (SDATA (SYMBOL_NAME (Qsuper)), s, 10))
3525 else if (!strncmp (SDATA (SYMBOL_NAME (Qcontrol)), s, 10))
3527 else if (!strncmp (SDATA (SYMBOL_NAME (Qalt)), s, 10))
3529 else if (!strncmp (SDATA (SYMBOL_NAME (Qhyper)), s, 10))
3531 else if (!strncmp (SDATA (SYMBOL_NAME (Qnone)), s, 10))
3538 static Lisp_Object ns_mod_to_lisp (int m)
3539 /* --------------------------------------------------------------------------
3540 Convert modifier code (see lisp.h) to lisp symbol
3541 -------------------------------------------------------------------------- */
3545 else if (m == CHAR_SUPER)
3547 else if (m == CHAR_CTL)
3549 else if (m == CHAR_ALT)
3551 else if (m == CHAR_HYPER)
3553 else /* if (m == 0) */
3559 ns_default (const char *parameter, Lisp_Object *result,
3560 Lisp_Object yesval, Lisp_Object noval,
3561 BOOL is_float, BOOL is_modstring)
3562 /* --------------------------------------------------------------------------
3563 Check a parameter value in user's preferences
3564 -------------------------------------------------------------------------- */
3568 if ( (value =[[[NSUserDefaults standardUserDefaults]
3569 stringForKey: [NSString stringWithUTF8String: parameter]]
3574 if (strcasecmp (value, "YES") == 0)
3576 else if (strcasecmp (value, "NO") == 0)
3578 else if (is_float && (f = strtod (value, &pos), pos != value))
3579 *result = make_float (f);
3580 else if (is_modstring && value)
3581 *result = ns_string_to_lispmod (value);
3582 else fprintf (stderr,
3583 "Bad value for default \"%s\": \"%s\"\n", parameter, value);
3589 ns_initialize_display_info (struct ns_display_info *dpyinfo)
3590 /* --------------------------------------------------------------------------
3591 Initialize global info and storage for display.
3592 -------------------------------------------------------------------------- */
3594 NSScreen *screen = [NSScreen mainScreen];
3595 NSWindowDepth depth = [screen depth];
3596 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
3598 dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
3599 dpyinfo->resy = 72.27;
3600 dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
3601 NSColorSpaceFromDepth (depth)]
3602 && ![NSCalibratedWhiteColorSpace isEqualToString:
3603 NSColorSpaceFromDepth (depth)];
3604 dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
3605 dpyinfo->image_cache = make_image_cache ();
3606 dpyinfo->color_table
3607 = (struct ns_color_table *)xmalloc (sizeof (struct ns_color_table));
3608 dpyinfo->color_table->colors = NULL;
3609 dpyinfo->root_window = 42; /* a placeholder.. */
3611 hlinfo->mouse_face_mouse_frame = NULL;
3612 hlinfo->mouse_face_deferred_gc = 0;
3613 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
3614 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
3615 hlinfo->mouse_face_face_id = DEFAULT_FACE_ID;
3616 hlinfo->mouse_face_window = hlinfo->mouse_face_overlay = Qnil;
3617 hlinfo->mouse_face_hidden = 0;
3619 hlinfo->mouse_face_mouse_x = hlinfo->mouse_face_mouse_y = 0;
3620 hlinfo->mouse_face_defer = 0;
3622 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
3624 dpyinfo->n_fonts = 0;
3625 dpyinfo->smallest_font_height = 1;
3626 dpyinfo->smallest_char_width = 1;
3630 /* This and next define (many of the) public functions in this file. */
3631 /* x_... are generic versions in xdisp.c that we, and other terms, get away
3632 with using despite presence in the "system dependent" redisplay
3633 interface. In addition, many of the ns_ methods have code that is
3634 shared with all terms, indicating need for further refactoring. */
3635 extern frame_parm_handler ns_frame_parm_handlers[];
3636 static struct redisplay_interface ns_redisplay_interface =
3638 ns_frame_parm_handlers,
3642 x_clear_end_of_line,
3644 ns_after_update_window_line,
3645 ns_update_window_begin,
3646 ns_update_window_end,
3649 0, /* flush_display_optional */
3650 x_clear_window_mouse_face,
3651 x_get_glyph_overhangs,
3652 x_fix_overlapping_area,
3653 ns_draw_fringe_bitmap,
3654 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
3655 0, /* destroy_fringe_bitmap */
3656 ns_compute_glyph_string_overhangs,
3657 ns_draw_glyph_string, /* interface to nsfont.m */
3658 ns_define_frame_cursor,
3659 ns_clear_frame_area,
3660 ns_draw_window_cursor,
3661 ns_draw_vertical_window_border,
3662 ns_shift_glyphs_for_insert
3667 ns_delete_display (struct ns_display_info *dpyinfo)
3673 /* This function is called when the last frame on a display is deleted. */
3675 ns_delete_terminal (struct terminal *terminal)
3677 struct ns_display_info *dpyinfo = terminal->display_info.ns;
3680 /* Protect against recursive calls. delete_frame in
3681 delete_terminal calls us back when it deletes our last frame. */
3682 if (!terminal->name)
3687 x_destroy_all_bitmaps (dpyinfo);
3688 ns_delete_display (dpyinfo);
3693 static struct terminal *
3694 ns_create_terminal (struct ns_display_info *dpyinfo)
3695 /* --------------------------------------------------------------------------
3696 Set up use of NS before we make the first connection.
3697 -------------------------------------------------------------------------- */
3699 struct terminal *terminal;
3701 NSTRACE (ns_create_terminal);
3703 terminal = create_terminal ();
3705 terminal->type = output_ns;
3706 terminal->display_info.ns = dpyinfo;
3707 dpyinfo->terminal = terminal;
3709 terminal->rif = &ns_redisplay_interface;
3711 terminal->clear_frame_hook = ns_clear_frame;
3712 terminal->ins_del_lines_hook = 0; /* XXX vestigial? */
3713 terminal->delete_glyphs_hook = 0; /* XXX vestigial? */
3714 terminal->ring_bell_hook = ns_ring_bell;
3715 terminal->reset_terminal_modes_hook = ns_reset_terminal_modes;
3716 terminal->set_terminal_modes_hook = ns_set_terminal_modes;
3717 terminal->update_begin_hook = ns_update_begin;
3718 terminal->update_end_hook = ns_update_end;
3719 terminal->set_terminal_window_hook = NULL; /* XXX vestigial? */
3720 terminal->read_socket_hook = ns_read_socket;
3721 terminal->frame_up_to_date_hook = ns_frame_up_to_date;
3722 terminal->mouse_position_hook = ns_mouse_position;
3723 terminal->frame_rehighlight_hook = ns_frame_rehighlight;
3724 terminal->frame_raise_lower_hook = ns_frame_raise_lower;
3726 terminal->fullscreen_hook = 0; /* see XTfullscreen_hook */
3728 terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
3729 terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
3730 terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
3731 terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
3733 terminal->delete_frame_hook = x_destroy_window;
3734 terminal->delete_terminal_hook = ns_delete_terminal;
3736 terminal->scroll_region_ok = 1;
3737 terminal->char_ins_del_ok = 1;
3738 terminal->line_ins_del_ok = 1;
3739 terminal->fast_clear_end_of_line = 1;
3740 terminal->memory_below_frame = 0;
3746 struct ns_display_info *
3747 ns_term_init (Lisp_Object display_name)
3748 /* --------------------------------------------------------------------------
3749 Start the Application and get things rolling.
3750 -------------------------------------------------------------------------- */
3752 struct terminal *terminal;
3753 struct ns_display_info *dpyinfo;
3754 static int ns_initialized = 0;
3757 NSTRACE (ns_term_init);
3759 /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
3760 /*GSDebugAllocationActive (YES); */
3762 handling_signal = 0;
3764 if (!ns_initialized)
3767 Fset_input_interrupt_mode (Qnil);
3771 ns_pending_files = [[NSMutableArray alloc] init];
3772 ns_pending_service_names = [[NSMutableArray alloc] init];
3773 ns_pending_service_args = [[NSMutableArray alloc] init];
3775 /* Start app and create the main menu, window, view.
3776 Needs to be here because ns_initialize_display_info () uses AppKit classes.
3777 The view will then ask the NSApp to stop and return to Emacs. */
3778 [EmacsApp sharedApplication];
3781 [NSApp setDelegate: NSApp];
3783 /* debugging: log all notifications */
3784 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
3785 selector: @selector (logNotification:)
3786 name: nil object: nil]; */
3788 dpyinfo = (struct ns_display_info *)xmalloc (sizeof (struct ns_display_info));
3789 memset (dpyinfo, 0, sizeof (struct ns_display_info));
3791 ns_initialize_display_info (dpyinfo);
3792 terminal = ns_create_terminal (dpyinfo);
3794 terminal->kboard = (KBOARD *) xmalloc (sizeof (KBOARD));
3795 init_kboard (terminal->kboard);
3796 terminal->kboard->Vwindow_system = Qns;
3797 terminal->kboard->next_kboard = all_kboards;
3798 all_kboards = terminal->kboard;
3799 /* Don't let the initial kboard remain current longer than necessary.
3800 That would cause problems if a file loaded on startup tries to
3801 prompt in the mini-buffer. */
3802 if (current_kboard == initial_kboard)
3803 current_kboard = terminal->kboard;
3804 terminal->kboard->reference_count++;
3806 dpyinfo->next = x_display_list;
3807 x_display_list = dpyinfo;
3809 /* Put it on ns_display_name_list */
3810 ns_display_name_list = Fcons (Fcons (display_name, Qnil),
3811 ns_display_name_list);
3812 dpyinfo->name_list_element = XCAR (ns_display_name_list);
3814 /* Set the name of the terminal. */
3815 terminal->name = (char *) xmalloc (SBYTES (display_name) + 1);
3816 strncpy (terminal->name, SDATA (display_name), SBYTES (display_name));
3817 terminal->name[SBYTES (display_name)] = 0;
3821 if (!inhibit_x_resources)
3823 ns_default ("GSFontAntiAlias", &ns_antialias_text,
3826 /* this is a standard variable */
3827 ns_default ("AppleAntiAliasingThreshold", &tmp,
3828 make_float (10.0), make_float (6.0), YES, NO);
3829 ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
3832 ns_selection_color = [[NSUserDefaults standardUserDefaults]
3833 stringForKey: @"AppleHighlightColor"];
3834 if (ns_selection_color == nil)
3835 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
3838 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
3842 Lisp_Object color_file, color_map, color;
3847 color_file = Fexpand_file_name (build_string ("rgb.txt"),
3848 Fsymbol_value (intern ("data-directory")));
3849 if (NILP (Ffile_readable_p (color_file)))
3850 fatal ("Could not find %s.\n", SDATA (color_file));
3852 color_map = Fx_load_color_file (color_file);
3853 if (NILP (color_map))
3854 fatal ("Could not read %s.\n", SDATA (color_file));
3856 cl = [[NSColorList alloc] initWithName: @"Emacs"];
3857 for ( ; CONSP (color_map); color_map = XCDR (color_map))
3859 color = XCAR (color_map);
3860 name = SDATA (XCAR (color));
3861 c = XINT (XCDR (color));
3863 [NSColor colorWithCalibratedRed: RED_FROM_ULONG (c) / 255.0
3864 green: GREEN_FROM_ULONG (c) / 255.0
3865 blue: BLUE_FROM_ULONG (c) / 255.0
3867 forKey: [NSString stringWithUTF8String: name]];
3869 [cl writeToFile: nil];
3875 #ifdef NS_IMPL_GNUSTEP
3876 strncpy (c, gnustep_base_version, sizeof (c));
3878 /*PSnextrelease (128, c); */
3879 snprintf (c, sizeof (c), "%g", NSAppKitVersionNumber);
3881 Vwindow_system_version = build_string (c);
3884 delete_keyboard_wait_descriptor (0);
3886 ns_app_name = [[NSProcessInfo processInfo] processName];
3888 /* Set up OS X app menu */
3889 #ifdef NS_IMPL_COCOA
3893 /* set up the application menu */
3894 svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
3895 [svcsMenu setAutoenablesItems: NO];
3896 appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
3897 [appMenu setAutoenablesItems: NO];
3898 mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
3899 dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
3901 [appMenu insertItemWithTitle: @"About Emacs"
3902 action: @selector (orderFrontStandardAboutPanel:)
3905 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
3906 [appMenu insertItemWithTitle: @"Preferences..."
3907 action: @selector (showPreferencesWindow:)
3910 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
3911 item = [appMenu insertItemWithTitle: @"Services"
3912 action: @selector (menuDown:)
3915 [appMenu setSubmenu: svcsMenu forItem: item];
3916 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
3917 [appMenu insertItemWithTitle: @"Hide Emacs"
3918 action: @selector (hide:)
3921 item = [appMenu insertItemWithTitle: @"Hide Others"
3922 action: @selector (hideOtherApplications:)
3925 [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
3926 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
3927 [appMenu insertItemWithTitle: @"Quit Emacs"
3928 action: @selector (terminate:)
3932 item = [mainMenu insertItemWithTitle: ns_app_name
3933 action: @selector (menuDown:)
3936 [mainMenu setSubmenu: appMenu forItem: item];
3937 [dockMenu insertItemWithTitle: @"New Frame"
3938 action: @selector (newFrame:)
3942 [NSApp setMainMenu: mainMenu];
3943 [NSApp setAppleMenu: appMenu];
3944 [NSApp setServicesMenu: svcsMenu];
3945 /* Needed at least on Cocoa, to get dock menu to show windows */
3946 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
3948 #endif /* MAC OS X menu setup */
3956 extern Lisp_Object Vauto_save_list_file_name;
3958 ns_term_shutdown (int sig)
3960 /* code not reached in emacs.c after this is called by shut_down_emacs: */
3961 if (STRINGP (Vauto_save_list_file_name))
3962 unlink (SDATA (Vauto_save_list_file_name));
3964 if (sig == 0 || sig == SIGTERM)
3966 [NSApp terminate: NSApp];
3968 else // force a stack trace to happen
3975 /* ==========================================================================
3977 EmacsApp implementation
3979 ========================================================================== */
3982 @implementation EmacsApp
3984 - (void)logNotification: (NSNotification *)notification
3986 const char *name = [[notification name] UTF8String];
3987 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
3988 && !strstr (name, "WindowNumber"))
3989 NSLog (@"notification: '%@'", [notification name]);
3993 - (void)sendEvent: (NSEvent *)theEvent
3994 /* --------------------------------------------------------------------------
3995 Called when NSApp is running for each event received. Used to stop
3996 the loop when we choose, since there's no way to just run one iteration.
3997 -------------------------------------------------------------------------- */
3999 int type = [theEvent type];
4000 NSWindow *window = [theEvent window];
4001 /* NSTRACE (sendEvent); */
4002 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4004 if (type == NSCursorUpdate && window == nil)
4006 fprintf (stderr, "Dropping external cursor update event.\n");
4010 #ifdef NS_IMPL_COCOA
4011 /* pass mouse down in resize handle and subsequent drags directly to
4012 EmacsWindow so we can generate continuous redisplays */
4015 if (type == NSLeftMouseDragged)
4017 [window mouseDragged: theEvent];
4020 else if (type == NSLeftMouseUp)
4022 [window mouseUp: theEvent];
4026 else if (type == NSLeftMouseDown)
4028 NSRect r = ns_resize_handle_rect (window);
4029 if (NSPointInRect ([theEvent locationInWindow], r))
4032 [window mouseDown: theEvent];
4038 if (type == NSApplicationDefined)
4040 /* Events posted by ns_send_appdefined interrupt the run loop here.
4041 But, if a modal window is up, an appdefined can still come through,
4042 (e.g., from a makeKeyWindow event) but stopping self also stops the
4043 modal loop. Just defer it until later. */
4044 if ([NSApp modalWindow] == nil)
4046 last_appdefined_event = theEvent;
4051 send_appdefined = YES;
4055 [super sendEvent: theEvent];
4059 - (void)showPreferencesWindow: (id)sender
4061 struct frame *emacsframe = SELECTED_FRAME ();
4062 NSEvent *theEvent = [NSApp currentEvent];
4066 emacs_event->kind = NS_NONKEY_EVENT;
4067 emacs_event->code = KEY_NS_SHOW_PREFS;
4068 emacs_event->modifiers = 0;
4069 EV_TRAILER (theEvent);
4073 - (void)newFrame: (id)sender
4075 struct frame *emacsframe = SELECTED_FRAME ();
4076 NSEvent *theEvent = [NSApp currentEvent];
4080 emacs_event->kind = NS_NONKEY_EVENT;
4081 emacs_event->code = KEY_NS_NEW_FRAME;
4082 emacs_event->modifiers = 0;
4083 EV_TRAILER (theEvent);
4087 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4088 - (BOOL) openFile: (NSString *)fileName
4090 struct frame *emacsframe = SELECTED_FRAME ();
4091 NSEvent *theEvent = [NSApp currentEvent];
4096 emacs_event->kind = NS_NONKEY_EVENT;
4097 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4098 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4099 ns_input_line = Qnil; /* can be start or cons start,end */
4100 emacs_event->modifiers =0;
4101 EV_TRAILER (theEvent);
4107 /* **************************************************************************
4109 EmacsApp delegate implementation
4111 ************************************************************************** */
4113 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4114 /* --------------------------------------------------------------------------
4115 When application is loaded, terminate event loop in ns_term_init
4116 -------------------------------------------------------------------------- */
4118 NSTRACE (applicationDidFinishLaunching);
4119 [NSApp setServicesProvider: NSApp];
4120 ns_send_appdefined (-2);
4124 /* Termination sequences:
4127 MenuBar | File | Exit:
4128 Select Quit from App menubar:
4130 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4133 Select Quit from Dock menu:
4136 Cancel -> Nothing else
4140 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4145 - (void) terminate: (id)sender
4147 struct frame *emacsframe = SELECTED_FRAME ();
4152 emacs_event->kind = NS_NONKEY_EVENT;
4153 emacs_event->code = KEY_NS_POWER_OFF;
4154 emacs_event->arg = Qt; /* mark as non-key event */
4155 EV_TRAILER ((id)nil);
4159 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4163 if (NILP (ns_confirm_quit)) // || ns_shutdown_properly --> TO DO
4164 return NSTerminateNow;
4166 ret = NSRunAlertPanel(ns_app_name,
4167 [NSString stringWithUTF8String:"Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?"],
4168 @"Save Buffers and Exit", @"Cancel", nil);
4170 if (ret == NSAlertDefaultReturn)
4171 return NSTerminateNow;
4172 else if (ret == NSAlertAlternateReturn)
4173 return NSTerminateCancel;
4174 return NSTerminateNow; /* just in case */
4178 /* Notification from the Workspace to open a file */
4179 - (BOOL)application: sender openFile: (NSString *)file
4181 [ns_pending_files addObject: file];
4186 /* Open a file as a temporary file */
4187 - (BOOL)application: sender openTempFile: (NSString *)file
4189 [ns_pending_files addObject: file];
4194 /* Notification from the Workspace to open a file noninteractively (?) */
4195 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4197 [ns_pending_files addObject: file];
4202 /* Notification from the Workspace to open multiple files */
4203 - (void)application: sender openFiles: (NSArray *)fileList
4205 NSEnumerator *files = [fileList objectEnumerator];
4207 while ((file = [files nextObject]) != nil)
4208 [ns_pending_files addObject: file];
4210 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4215 /* Handle dock menu requests. */
4216 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4222 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4223 - (void)applicationWillBecomeActive: (NSNotification *)notification
4225 //ns_app_active=YES;
4227 - (void)applicationDidBecomeActive: (NSNotification *)notification
4229 //ns_app_active=YES;
4231 - (void)applicationDidResignActive: (NSNotification *)notification
4234 ns_send_appdefined (-1);
4239 /* ==========================================================================
4241 EmacsApp aux handlers for managing event loop
4243 ========================================================================== */
4246 - (void)timeout_handler: (NSTimer *)timedEntry
4247 /* --------------------------------------------------------------------------
4248 The timeout specified to ns_select has passed.
4249 -------------------------------------------------------------------------- */
4251 /*NSTRACE (timeout_handler); */
4252 ns_send_appdefined (-2);
4255 - (void)fd_handler: (NSTimer *) fdEntry
4256 /* --------------------------------------------------------------------------
4257 Check data waiting on file descriptors and terminate if so
4258 -------------------------------------------------------------------------- */
4261 /* NSTRACE (fd_handler); */
4263 if (select_nfds == 0)
4266 memcpy (&t_readfds, &select_readfds, sizeof (fd_set));
4268 select_timeout.tv_sec = select_timeout.tv_usec = 0;
4269 result = select (select_nfds, &t_readfds, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
4273 memcpy (&select_readfds, &t_readfds, sizeof (fd_set));
4274 ns_send_appdefined (result);
4280 /* ==========================================================================
4284 ========================================================================== */
4286 /* called from system: queue for next pass through event loop */
4287 - (void)requestService: (NSPasteboard *)pboard
4288 userData: (NSString *)userData
4289 error: (NSString **)error
4291 [ns_pending_service_names addObject: userData];
4292 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
4293 SDATA (ns_string_from_pasteboard (pboard))]];
4297 /* called from ns_read_socket to clear queue */
4298 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
4300 struct frame *emacsframe = SELECTED_FRAME ();
4301 NSEvent *theEvent = [NSApp currentEvent];
4306 emacs_event->kind = NS_NONKEY_EVENT;
4307 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
4308 ns_input_spi_name = build_string ([name UTF8String]);
4309 ns_input_spi_arg = build_string ([arg UTF8String]);
4310 emacs_event->modifiers = EV_MODIFIERS (theEvent);
4311 EV_TRAILER (theEvent);
4321 /* ==========================================================================
4323 EmacsView implementation
4325 ========================================================================== */
4328 @implementation EmacsView
4330 /* needed to inform when window closed from LISP */
4331 - (void) setWindowClosing: (BOOL)closing
4333 windowClosing = closing;
4339 NSTRACE (EmacsView_dealloc);
4345 /* called on font panel selection */
4346 - (void)changeFont: (id)sender
4348 NSEvent *e =[[self window] currentEvent];
4349 struct face *face =FRAME_DEFAULT_FACE (emacsframe);
4353 NSTRACE (changeFont);
4357 if (newFont = [sender convertFont:
4358 ((struct nsfont_info *)face->font)->nsfont])
4360 SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
4362 emacs_event->kind = NS_NONKEY_EVENT;
4363 emacs_event->modifiers = 0;
4364 emacs_event->code = KEY_NS_CHANGE_FONT;
4366 size = [newFont pointSize];
4367 ns_input_fontsize = make_number (lrint (size));
4368 ns_input_font = build_string ([[newFont familyName] UTF8String]);
4374 - (BOOL)acceptsFirstResponder
4376 NSTRACE (acceptsFirstResponder);
4381 - (void)resetCursorRects
4383 NSRect visible = [self visibleRect];
4384 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
4385 NSTRACE (resetCursorRects);
4387 if (currentCursor == nil)
4388 currentCursor = [NSCursor arrowCursor];
4390 if (!NSIsEmptyRect (visible))
4391 [self addCursorRect: visible cursor: currentCursor];
4392 [currentCursor setOnMouseEntered: YES];
4397 /*****************************************************************************/
4398 /* Keyboard handling. */
4401 - (void)keyDown: (NSEvent *)theEvent
4403 Mouse_HLInfo *hlinfo = MOUSE_HL_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 (ns_fake_keydown == YES)
4414 ns_fake_keydown = NO;
4415 else if ([theEvent type] != NSKeyDown)
4421 if (![[self window] isKeyWindow]
4422 && [[theEvent window] isKindOfClass: [EmacsWindow class]]
4423 /* we must avoid an infinite loop here. */
4424 && (EmacsView *)[[theEvent window] delegate] != self)
4426 /* XXX: There is an occasional condition in which, when Emacs display
4427 updates a different frame from the current one, and temporarily
4428 selects it, then processes some interrupt-driven input
4429 (dispnew.c:3878), OS will send the event to the correct NSWindow, but
4430 for some reason that window has its first responder set to the NSView
4431 most recently updated (I guess), which is not the correct one. */
4432 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
4436 if (nsEvArray == nil)
4437 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
4439 [NSCursor setHiddenUntilMouseMoves: YES];
4441 if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
4443 clear_mouse_face (hlinfo);
4444 hlinfo->mouse_face_hidden = 1;
4447 if (!processingCompose)
4449 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
4450 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
4451 /* (Carbon way: [theEvent keyCode]) */
4453 /* is it a "function key"? */
4454 fnKeysym = ns_convert_key (code);
4457 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
4458 because Emacs treats Delete and KP-Delete same (in simple.el). */
4459 if (fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
4460 code = 0xFF08; /* backspace */
4465 /* are there modifiers? */
4466 emacs_event->modifiers = 0;
4467 flags = [theEvent modifierFlags];
4469 if (flags & NSHelpKeyMask)
4470 emacs_event->modifiers |= hyper_modifier;
4472 if (flags & NSShiftKeyMask)
4473 emacs_event->modifiers |= shift_modifier;
4475 if ((flags & NSRightCommandKeyMask) == NSRightCommandKeyMask)
4476 emacs_event->modifiers |= parse_solitary_modifier
4477 (EQ (ns_right_command_modifier, Qleft)
4478 ? ns_command_modifier
4479 : ns_right_command_modifier);
4481 if ((flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask)
4483 emacs_event->modifiers |= parse_solitary_modifier
4484 (ns_command_modifier);
4486 /* if super (default), take input manager's word so things like
4487 dvorak / qwerty layout work */
4488 if (EQ (ns_command_modifier, Qsuper)
4490 && [[theEvent characters] length] != 0)
4492 /* XXX: the code we get will be unshifted, so if we have
4493 a shift modifier, must convert ourselves */
4494 if (!(flags & NSShiftKeyMask))
4495 code = [[theEvent characters] characterAtIndex: 0];
4497 /* this is ugly and also requires linking w/Carbon framework
4498 (for LMGetKbdType) so for now leave this rare (?) case
4499 undealt with.. in future look into CGEvent methods */
4502 long smv = GetScriptManagerVariable (smKeyScript);
4503 Handle uchrHandle = GetResource
4504 ('uchr', GetScriptVariable (smv, smScriptKeys));
4506 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
4507 [[theEvent characters] characterAtIndex: 0],
4508 kUCKeyActionDisplay,
4509 (flags & ~NSCommandKeyMask) >> 8,
4510 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
4511 &dummy, 1, &dummy, &code);
4518 if ((flags & NSRightControlKeyMask) == NSRightControlKeyMask)
4519 emacs_event->modifiers |= parse_solitary_modifier
4520 (EQ (ns_right_control_modifier, Qleft)
4521 ? ns_control_modifier
4522 : ns_right_control_modifier);
4524 if ((flags & NSLeftControlKeyMask) == NSLeftControlKeyMask)
4525 emacs_event->modifiers |= parse_solitary_modifier
4526 (ns_control_modifier);
4528 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
4529 emacs_event->modifiers |=
4530 parse_solitary_modifier (ns_function_modifier);
4532 if ((flags & NSRightAlternateKeyMask) == NSRightAlternateKeyMask)
4534 if ((NILP (ns_right_alternate_modifier)
4535 || EQ (ns_right_alternate_modifier, Qnone))
4537 { /* accept pre-interp alt comb */
4538 if ([[theEvent characters] length] > 0)
4539 code = [[theEvent characters] characterAtIndex: 0];
4540 /*HACK: clear lone shift modifier to stop next if from firing */
4541 if (emacs_event->modifiers == shift_modifier)
4542 emacs_event->modifiers = 0;
4545 emacs_event->modifiers |= parse_solitary_modifier
4546 (EQ (ns_right_alternate_modifier, Qleft)
4547 ? ns_alternate_modifier
4548 : ns_right_alternate_modifier);
4551 if ((flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask) /* default = meta */
4553 if ((NILP (ns_alternate_modifier)
4554 || EQ (ns_alternate_modifier, Qnone))
4556 { /* accept pre-interp alt comb */
4557 if ([[theEvent characters] length] > 0)
4558 code = [[theEvent characters] characterAtIndex: 0];
4559 /*HACK: clear lone shift modifier to stop next if from firing */
4560 if (emacs_event->modifiers == shift_modifier)
4561 emacs_event->modifiers = 0;
4564 emacs_event->modifiers |=
4565 parse_solitary_modifier (ns_alternate_modifier);
4569 fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
4570 code, fnKeysym, flags, emacs_event->modifiers);
4572 /* if it was a function key or had modifiers, pass it directly to emacs */
4573 if (fnKeysym || (emacs_event->modifiers
4574 && [[theEvent charactersIgnoringModifiers] length] > 0))
4575 /*[[theEvent characters] length] */
4577 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4579 code |= (1<<28)|(3<<16);
4580 else if (code == 0x7f)
4581 code |= (1<<28)|(3<<16);
4583 emacs_event->kind = code > 0xFF
4584 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4586 emacs_event->code = code;
4587 EV_TRAILER (theEvent);
4592 /* if we get here we should send the key for input manager processing */
4593 if (firstTime && [[NSInputManager currentInputManager]
4594 wantsToDelayTextChangeNotifications] == NO)
4596 "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
4599 if (NS_KEYLOG && !processingCompose)
4600 fprintf (stderr, "keyDown: Begin compose sequence.\n");
4602 processingCompose = YES;
4603 [nsEvArray addObject: theEvent];
4604 [self interpretKeyEvents: nsEvArray];
4605 [nsEvArray removeObject: theEvent];
4609 #ifdef NS_IMPL_COCOA
4610 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
4611 decided not to send key-down for.
4612 See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
4613 This only applies on Tiger and earlier.
4614 If it matches one of these, send it on to keyDown. */
4615 -(void)keyUp: (NSEvent *)theEvent
4617 int flags = [theEvent modifierFlags];
4618 int code = [theEvent keyCode];
4619 if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
4620 code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
4623 fprintf (stderr, "keyUp: passed test");
4624 ns_fake_keydown = YES;
4625 [self keyDown: theEvent];
4631 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
4634 /* <NSTextInput>: called when done composing;
4635 NOTE: also called when we delete over working text, followed immed.
4636 by doCommandBySelector: deleteBackward: */
4637 - (void)insertText: (id)aString
4640 int len = [(NSString *)aString length];
4644 NSLog (@"insertText '%@'\tlen = %d", aString, len);
4645 processingCompose = NO;
4650 /* first, clear any working text */
4651 if (workingText != nil)
4652 [self deleteWorkingText];
4654 /* now insert the string as keystrokes */
4655 for (i =0; i<len; i++)
4657 code = [aString characterAtIndex: i];
4658 /* TODO: still need this? */
4660 code = '~'; /* 0x7E */
4661 emacs_event->modifiers = 0;
4663 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4664 emacs_event->code = code;
4665 EV_TRAILER ((id)nil);
4670 /* <NSTextInput>: inserts display of composing characters */
4671 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
4673 NSString *str = [aString respondsToSelector: @selector (string)] ?
4674 [aString string] : aString;
4676 NSLog (@"setMarkedText '%@' len =%d range %d from %d", str, [str length],
4677 selRange.length, selRange.location);
4679 if (workingText != nil)
4680 [self deleteWorkingText];
4681 if ([str length] == 0)
4687 processingCompose = YES;
4688 workingText = [str copy];
4689 ns_working_text = build_string ([workingText UTF8String]);
4691 emacs_event->kind = NS_TEXT_EVENT;
4692 emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
4693 EV_TRAILER ((id)nil);
4697 /* delete display of composing characters [not in <NSTextInput>] */
4698 - (void)deleteWorkingText
4700 if (workingText == nil)
4703 NSLog(@"deleteWorkingText len =%d\n", [workingText length]);
4704 [workingText release];
4706 processingCompose = NO;
4711 emacs_event->kind = NS_TEXT_EVENT;
4712 emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
4713 EV_TRAILER ((id)nil);
4717 - (BOOL)hasMarkedText
4719 return workingText != nil;
4723 - (NSRange)markedRange
4725 NSRange rng = workingText != nil
4726 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
4728 NSLog (@"markedRange request");
4736 NSLog (@"unmark (accept) text");
4737 [self deleteWorkingText];
4738 processingCompose = NO;
4742 /* used to position char selection windows, etc. */
4743 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
4747 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
4749 NSLog (@"firstRectForCharRange request");
4751 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
4752 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
4753 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
4754 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
4755 +FRAME_LINE_HEIGHT (emacsframe));
4757 pt = [self convertPoint: pt toView: nil];
4758 pt = [[self window] convertBaseToScreen: pt];
4764 - (long)conversationIdentifier
4770 - (void)doCommandBySelector: (SEL)aSelector
4773 NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
4775 if (aSelector == @selector (deleteBackward:))
4777 /* happens when user backspaces over an ongoing composition:
4778 throw a 'delete' into the event queue */
4781 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4782 emacs_event->code = 0xFF08;
4783 EV_TRAILER ((id)nil);
4787 - (NSArray *)validAttributesForMarkedText
4789 static NSArray *arr = nil;
4790 if (arr == nil) arr = [NSArray new];
4791 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
4795 - (NSRange)selectedRange
4798 NSLog (@"selectedRange request");
4799 return NSMakeRange (NSNotFound, 0);
4802 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
4805 NSLog (@"characterIndexForPoint request");
4809 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
4811 static NSAttributedString *str = nil;
4812 if (str == nil) str = [NSAttributedString new];
4814 NSLog (@"attributedSubstringFromRange request");
4818 /* End <NSTextInput> impl. */
4819 /*****************************************************************************/
4822 /* This is what happens when the user presses a mouse button. */
4823 - (void)mouseDown: (NSEvent *)theEvent
4825 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
4828 NSTRACE (mouseDown);
4830 [self deleteWorkingText];
4835 last_mouse_frame = emacsframe;
4836 /* appears to be needed to prevent spurious movement events generated on
4838 last_mouse_frame->mouse_moved = 0;
4840 if ([theEvent type] == NSScrollWheel)
4842 float delta = [theEvent deltaY];
4843 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
4846 emacs_event->kind = WHEEL_EVENT;
4847 emacs_event->code = 0;
4848 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
4849 ((delta > 0) ? up_modifier : down_modifier);
4853 emacs_event->kind = MOUSE_CLICK_EVENT;
4854 emacs_event->code = EV_BUTTON (theEvent);
4855 emacs_event->modifiers = EV_MODIFIERS (theEvent)
4856 | EV_UDMODIFIERS (theEvent);
4858 XSETINT (emacs_event->x, lrint (p.x));
4859 XSETINT (emacs_event->y, lrint (p.y));
4860 EV_TRAILER (theEvent);
4864 - (void)rightMouseDown: (NSEvent *)theEvent
4866 NSTRACE (rightMouseDown);
4867 [self mouseDown: theEvent];
4871 - (void)otherMouseDown: (NSEvent *)theEvent
4873 NSTRACE (otherMouseDown);
4874 [self mouseDown: theEvent];
4878 - (void)mouseUp: (NSEvent *)theEvent
4881 [self mouseDown: theEvent];
4885 - (void)rightMouseUp: (NSEvent *)theEvent
4887 NSTRACE (rightMouseUp);
4888 [self mouseDown: theEvent];
4892 - (void)otherMouseUp: (NSEvent *)theEvent
4894 NSTRACE (otherMouseUp);
4895 [self mouseDown: theEvent];
4899 - (void) scrollWheel: (NSEvent *)theEvent
4901 NSTRACE (scrollWheel);
4902 [self mouseDown: theEvent];
4906 /* Tell emacs the mouse has moved. */
4907 - (void)mouseMoved: (NSEvent *)e
4909 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
4912 // NSTRACE (mouseMoved);
4914 last_mouse_movement_time = EV_TIMESTAMP (e);
4915 last_mouse_motion_position
4916 = [self convertPoint: [e locationInWindow] fromView: nil];
4918 /* update any mouse face */
4919 if (hlinfo->mouse_face_hidden)
4921 hlinfo->mouse_face_hidden = 0;
4922 clear_mouse_face (hlinfo);
4925 /* tooltip handling */
4926 previous_help_echo_string = help_echo_string;
4927 help_echo_string = Qnil;
4929 if (!note_mouse_movement (emacsframe, last_mouse_motion_position.x,
4930 last_mouse_motion_position.y))
4931 help_echo_string = previous_help_echo_string;
4933 XSETFRAME (frame, emacsframe);
4934 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
4936 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
4937 (note_mouse_highlight), which is called through the
4938 note_mouse_movement () call above */
4939 gen_help_event (help_echo_string, frame, help_echo_window,
4940 help_echo_object, help_echo_pos);
4944 help_echo_string = Qnil;
4945 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
4948 if (emacsframe->mouse_moved && send_appdefined)
4949 ns_send_appdefined (-1);
4953 - (void)mouseDragged: (NSEvent *)e
4955 NSTRACE (mouseDragged);
4956 [self mouseMoved: e];
4960 - (void)rightMouseDragged: (NSEvent *)e
4962 NSTRACE (rightMouseDragged);
4963 [self mouseMoved: e];
4967 - (void)otherMouseDragged: (NSEvent *)e
4969 NSTRACE (otherMouseDragged);
4970 [self mouseMoved: e];
4974 - (BOOL)windowShouldClose: (id)sender
4976 NSEvent *e =[[self window] currentEvent];
4978 NSTRACE (windowShouldClose);
4979 windowClosing = YES;
4982 emacs_event->kind = DELETE_WINDOW_EVENT;
4983 emacs_event->modifiers = 0;
4984 emacs_event->code = 0;
4986 /* Don't close this window, let this be done from lisp code. */
4991 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
4992 /* normalize frame to gridded text size */
4994 NSTRACE (windowWillResize);
4995 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
4997 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe,
4998 #ifdef NS_IMPL_GNUSTEP
4999 frameSize.width + 3);
5003 if (cols < MINWIDTH)
5005 frameSize.width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (emacsframe, cols);
5007 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, frameSize.height
5008 #ifdef NS_IMPL_GNUSTEP
5009 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe) + 3
5010 - FRAME_TOOLBAR_HEIGHT (emacsframe));
5012 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5013 - FRAME_TOOLBAR_HEIGHT (emacsframe));
5015 if (rows < MINHEIGHT)
5017 frameSize.height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows)
5018 + FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5019 + FRAME_TOOLBAR_HEIGHT (emacsframe);
5020 #ifdef NS_IMPL_COCOA
5022 /* this sets window title to have size in it; the wm does this under GS */
5023 NSRect r = [[self window] frame];
5024 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
5035 NSWindow *window = [self window];
5038 const char *t = [[[self window] title] UTF8String];
5039 char *pos = strstr (t, " — ");
5042 old_title = (char *) xmalloc (strlen (t) + 1);
5043 strcpy (old_title, t);
5045 size_title = xmalloc (strlen (old_title) + 40);
5046 sprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
5047 [window setTitle: [NSString stringWithUTF8String: size_title]];
5052 #endif /* NS_IMPL_COCOA */
5053 /*fprintf (stderr," ...size became %.0f x %.0f (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
5059 - (void)windowDidResize: (NSNotification *)notification
5061 NSWindow *theWindow = [notification object];
5063 #ifdef NS_IMPL_GNUSTEP
5064 /* in GNUstep, at least currently, it's possible to get a didResize
5065 without getting a willResize.. therefore we need to act as if we got
5066 the willResize now */
5067 NSSize sz = [theWindow frame].size;
5068 sz = [self windowWillResize: theWindow toSize: sz];
5069 #endif /* NS_IMPL_GNUSTEP */
5071 NSTRACE (windowDidResize);
5072 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
5074 #ifdef NS_IMPL_COCOA
5080 #endif /* NS_IMPL_COCOA */
5082 /* Avoid loop under GNUstep due to call at beginning of this function.
5083 (x_set_window_size causes a resize which causes
5084 a "windowDidResize" which calls x_set_window_size). */
5085 #ifndef NS_IMPL_GNUSTEP
5086 if (cols > 0 && rows > 0)
5087 x_set_window_size (emacsframe, 0, cols, rows);
5090 ns_send_appdefined (-1);
5094 - (void)windowDidBecomeKey: (NSNotification *)notification
5095 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5097 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5098 struct frame *old_focus = dpyinfo->x_focus_frame;
5100 NSTRACE (windowDidBecomeKey);
5102 if (emacsframe != old_focus)
5103 dpyinfo->x_focus_frame = emacsframe;
5105 ns_frame_rehighlight (emacsframe);
5109 emacs_event->kind = FOCUS_IN_EVENT;
5110 EV_TRAILER ((id)nil);
5115 - (void)windowDidResignKey: (NSNotification *)notification
5116 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5118 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5119 NSTRACE (windowDidResignKey);
5121 if (dpyinfo->x_focus_frame == emacsframe)
5122 dpyinfo->x_focus_frame = 0;
5124 ns_frame_rehighlight (emacsframe);
5126 /* FIXME: for some reason needed on second and subsequent clicks away
5127 from sole-frame Emacs to get hollow box to show */
5128 if (!windowClosing && [[self window] isVisible] == YES)
5130 x_update_cursor (emacsframe, 1);
5131 x_set_frame_alpha (emacsframe);
5136 [self deleteWorkingText];
5137 emacs_event->kind = FOCUS_IN_EVENT;
5138 EV_TRAILER ((id)nil);
5143 - (void)windowWillMiniaturize: sender
5145 NSTRACE (windowWillMiniaturize);
5161 - initFrameFromEmacs: (struct frame *)f
5166 NSButton *toggleButton;
5167 int vbextra = NS_SCROLL_BAR_WIDTH (f);
5172 NSTRACE (initFrameFromEmacs);
5175 processingCompose = NO;
5176 scrollbarsNeedingUpdate = 0;
5178 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
5180 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
5181 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
5182 [self initWithFrame: r];
5183 [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
5185 FRAME_NS_VIEW (f) = self;
5189 win = [[EmacsWindow alloc]
5190 initWithContentRect: r
5191 styleMask: (NSResizableWindowMask |
5192 NSMiniaturizableWindowMask |
5193 NSClosableWindowMask)
5194 backing: NSBackingStoreBuffered
5198 f->border_width = wr.size.width - r.size.width;
5199 FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
5201 [win setAcceptsMouseMovedEvents: YES];
5202 [win setDelegate: self];
5203 [win useOptimizedDrawing: YES];
5205 sz.width = FRAME_COLUMN_WIDTH (f);
5206 sz.height = FRAME_LINE_HEIGHT (f);
5207 [win setResizeIncrements: sz];
5209 [[win contentView] addSubview: self];
5212 [self registerForDraggedTypes: ns_drag_types];
5215 name = [NSString stringWithUTF8String:
5216 NILP (tem) ? (unsigned char *)"Emacs" : SDATA (tem)];
5217 [win setTitle: name];
5219 /* toolbar support */
5220 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
5221 [NSString stringWithFormat: @"Emacs Frame %d",
5223 [win setToolbar: toolbar];
5224 [toolbar setVisible: NO];
5225 #ifdef NS_IMPL_COCOA
5226 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
5227 [toggleButton setTarget: self];
5228 [toggleButton setAction: @selector (toggleToolbar: )];
5230 FRAME_TOOLBAR_HEIGHT (f) = 0;
5234 [win setMiniwindowTitle:
5235 [NSString stringWithUTF8String: SDATA (tem)]];
5238 NSScreen *screen = [win screen];
5241 [win setFrameTopLeftPoint: NSMakePoint
5242 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
5243 IN_BOUND (-SCREENMAX,
5244 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
5247 [win makeFirstResponder: self];
5249 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5250 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
5251 [win setBackgroundColor: col];
5252 if ([col alphaComponent] != 1.0)
5253 [win setOpaque: NO];
5255 [self allocateGState];
5262 - (void)windowDidMove: sender
5264 NSWindow *win = [self window];
5265 NSRect r = [win frame];
5266 NSScreen *screen = [win screen];
5268 NSTRACE (windowDidMove);
5270 if (!emacsframe->output_data.ns)
5274 emacsframe->left_pos = r.origin.x;
5275 emacsframe->top_pos =
5276 [screen frame].size.height - (r.origin.y + r.size.height);
5281 /* Called AFTER method below, but before our windowWillResize call there leads
5282 to windowDidResize -> x_set_window_size. Update emacs' notion of frame
5283 location so set_window_size moves the frame. */
5284 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
5286 NSTRACE (windowShouldZoom);
5287 emacsframe->left_pos = (int)newFrame.origin.x;
5288 emacsframe->top_pos = [[sender screen] frame].size.height
5289 - (newFrame.origin.y+newFrame.size.height);
5294 /* Override to do something slightly nonstandard, but nice. First click on
5295 zoom button will zoom vertically. Second will zoom completely. Third
5296 returns to original. */
5297 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
5298 defaultFrame:(NSRect)defaultFrame
5300 NSRect result = [sender frame];
5301 static NSRect ns_userRect = { 0, 0, 0, 0 };
5303 NSTRACE (windowWillUseStandardFrame);
5305 if (abs (defaultFrame.size.height - result.size.height)
5306 > FRAME_LINE_HEIGHT (emacsframe))
5309 ns_userRect = result;
5310 result.size.height = defaultFrame.size.height;
5311 result.origin.y = defaultFrame.origin.y;
5315 if (abs (defaultFrame.size.width - result.size.width)
5316 > FRAME_COLUMN_WIDTH (emacsframe))
5317 result = defaultFrame; /* second click */
5319 result = ns_userRect.size.height ? ns_userRect : result; /* restore */
5322 [self windowWillResize: sender toSize: result.size];
5327 - (void)windowDidDeminiaturize: sender
5329 NSTRACE (windowDidDeminiaturize);
5330 if (!emacsframe->output_data.ns)
5332 emacsframe->async_iconified = 0;
5333 emacsframe->async_visible = 1;
5334 windows_or_buffers_changed++;
5338 emacs_event->kind = ICONIFY_EVENT;
5339 EV_TRAILER ((id)nil);
5344 - (void)windowDidExpose: sender
5346 NSTRACE (windowDidExpose);
5347 if (!emacsframe->output_data.ns)
5349 emacsframe->async_visible = 1;
5350 SET_FRAME_GARBAGED (emacsframe);
5352 if (send_appdefined)
5353 ns_send_appdefined (-1);
5357 - (void)windowDidMiniaturize: sender
5359 NSTRACE (windowDidMiniaturize);
5360 if (!emacsframe->output_data.ns)
5363 emacsframe->async_iconified = 1;
5364 emacsframe->async_visible = 0;
5368 emacs_event->kind = ICONIFY_EVENT;
5369 EV_TRAILER ((id)nil);
5374 - (void)mouseEntered: (NSEvent *)theEvent
5376 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5377 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5378 NSTRACE (mouseEntered);
5380 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5384 - (void)mouseExited: (NSEvent *)theEvent
5386 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5388 Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
5390 NSTRACE (mouseExited);
5395 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5397 if (emacsframe == hlinfo->mouse_face_mouse_frame)
5399 clear_mouse_face (hlinfo);
5400 hlinfo->mouse_face_mouse_frame = 0;
5408 if (context_menu_value == -1)
5409 context_menu_value = [sender tag];
5411 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
5412 emacsframe->menu_bar_vector,
5413 (void *)[sender tag]);
5414 ns_send_appdefined (-1);
5419 - (EmacsToolbar *)toolbar
5425 /* this gets called on toolbar button click */
5426 - toolbarClicked: (id)item
5429 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
5431 NSTRACE (toolbarClicked);
5436 /* send first event (for some reason two needed) */
5437 theEvent = [[self window] currentEvent];
5438 emacs_event->kind = TOOL_BAR_EVENT;
5439 XSETFRAME (emacs_event->arg, emacsframe);
5440 EV_TRAILER (theEvent);
5442 emacs_event->kind = TOOL_BAR_EVENT;
5443 /* XSETINT (emacs_event->code, 0); */
5444 emacs_event->arg = AREF (emacsframe->tool_bar_items,
5445 idx + TOOL_BAR_ITEM_KEY);
5446 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5447 EV_TRAILER (theEvent);
5452 - toggleToolbar: (id)sender
5457 emacs_event->kind = NS_NONKEY_EVENT;
5458 emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
5459 EV_TRAILER ((id)nil);
5464 - (void)drawRect: (NSRect)rect
5466 int x = NSMinX (rect), y = NSMinY (rect);
5467 int width = NSWidth (rect), height = NSHeight (rect);
5471 if (!emacsframe || !emacsframe->output_data.ns || ns_in_resize)
5474 ns_clear_frame_area (emacsframe, x, y, width, height);
5475 expose_frame (emacsframe, x, y, width, height);
5478 drawRect: may be called (at least in OS X 10.5) for invisible
5479 views as well for some reason. Thus, do not infer visibility
5482 emacsframe->async_visible = 1;
5483 emacsframe->async_iconified = 0;
5488 /* NSDraggingDestination protocol methods. Actually this is not really a
5489 protocol, but a category of Object. O well... */
5491 -(NSUInteger) draggingEntered: (id <NSDraggingInfo>) sender
5493 NSTRACE (draggingEntered);
5494 return NSDragOperationGeneric;
5498 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
5504 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
5509 NSEvent *theEvent = [[self window] currentEvent];
5512 NSTRACE (performDragOperation);
5517 position = [self convertPoint: [sender draggingLocation] fromView: nil];
5518 x = lrint (position.x); y = lrint (position.y);
5520 pb = [sender draggingPasteboard];
5521 type = [pb availableTypeFromArray: ns_drag_types];
5526 else if ([type isEqualToString: NSFilenamesPboardType])
5529 NSEnumerator *fenum;
5532 if (!(files = [pb propertyListForType: type]))
5535 fenum = [files objectEnumerator];
5536 while ( (file = [fenum nextObject]) )
5538 emacs_event->kind = NS_NONKEY_EVENT;
5539 emacs_event->code = KEY_NS_DRAG_FILE;
5540 XSETINT (emacs_event->x, x);
5541 XSETINT (emacs_event->y, y);
5542 ns_input_file = append2 (ns_input_file,
5543 build_string ([file UTF8String]));
5544 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5545 EV_TRAILER (theEvent);
5549 else if ([type isEqualToString: NSURLPboardType])
5554 if (!(fileURL = [NSURL URLFromPasteboard: pb]) ||
5555 [fileURL isFileURL] == NO)
5558 file = [fileURL path];
5559 emacs_event->kind = NS_NONKEY_EVENT;
5560 emacs_event->code = KEY_NS_DRAG_FILE;
5561 XSETINT (emacs_event->x, x);
5562 XSETINT (emacs_event->y, y);
5563 ns_input_file = append2 (ns_input_file, build_string ([file UTF8String]));
5564 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5565 EV_TRAILER (theEvent);
5568 else if ([type isEqualToString: NSStringPboardType]
5569 || [type isEqualToString: NSTabularTextPboardType])
5573 if (! (data = [pb stringForType: type]))
5576 emacs_event->kind = NS_NONKEY_EVENT;
5577 emacs_event->code = KEY_NS_DRAG_TEXT;
5578 XSETINT (emacs_event->x, x);
5579 XSETINT (emacs_event->y, y);
5580 ns_input_text = build_string ([data UTF8String]);
5581 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5582 EV_TRAILER (theEvent);
5585 else if ([type isEqualToString: NSColorPboardType])
5587 NSColor *c = [NSColor colorFromPasteboard: pb];
5588 emacs_event->kind = NS_NONKEY_EVENT;
5589 emacs_event->code = KEY_NS_DRAG_COLOR;
5590 XSETINT (emacs_event->x, x);
5591 XSETINT (emacs_event->y, y);
5592 ns_input_color = ns_color_to_lisp (c);
5593 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5594 EV_TRAILER (theEvent);
5597 else if ([type isEqualToString: NSFontPboardType])
5599 /* impl based on GNUstep NSTextView.m */
5600 NSData *data = [pb dataForType: NSFontPboardType];
5601 NSDictionary *dict = [NSUnarchiver unarchiveObjectWithData: data];
5602 NSFont *font = [dict objectForKey: NSFontAttributeName];
5608 emacs_event->kind = NS_NONKEY_EVENT;
5609 emacs_event->code = KEY_NS_CHANGE_FONT;
5610 XSETINT (emacs_event->x, x);
5611 XSETINT (emacs_event->y, y);
5612 ns_input_font = build_string ([[font fontName] UTF8String]);
5613 snprintf (fontSize, 10, "%f", [font pointSize]);
5614 ns_input_fontsize = build_string (fontSize);
5615 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5616 EV_TRAILER (theEvent);
5621 error ("Invalid data type in dragging pasteboard.");
5627 - validRequestorForSendType: (NSString *)typeSent
5628 returnType: (NSString *)typeReturned
5630 NSTRACE (validRequestorForSendType);
5631 if ([ns_send_types indexOfObjectIdenticalTo: typeSent] != NSNotFound &&
5632 [ns_return_types indexOfObjectIdenticalTo: typeSent] != NSNotFound)
5635 return [super validRequestorForSendType: typeSent
5636 returnType: typeReturned];
5640 /* The next two methods are part of NSServicesRequests informal protocol,
5641 supposedly called when a services menu item is chosen from this app.
5642 But this should not happen because we override the services menu with our
5643 own entries which call ns-perform-service.
5644 Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
5645 So let's at least stub them out until further investigation can be done. */
5647 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
5649 /* we could call ns_string_from_pasteboard(pboard) here but then it should
5650 be written into the buffer in place of the existing selection..
5651 ordinary service calls go through functions defined in ns-win.el */
5655 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
5657 /* supposed to write for as many of types as we are able */
5662 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
5663 (gives a miniaturized version of the window); currently we use the latter for
5664 frames whose active buffer doesn't correspond to any file
5665 (e.g., '*scratch*') */
5666 - setMiniwindowImage: (BOOL) setMini
5668 id image = [[self window] miniwindowImage];
5669 NSTRACE (setMiniwindowImage);
5671 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
5672 about "AppleDockIconEnabled" notwithstanding, however the set message
5673 below has its effect nonetheless. */
5674 if (image != emacsframe->output_data.ns->miniimage)
5676 if (image && [image isKindOfClass: [EmacsImage class]])
5678 [[self window] setMiniwindowImage:
5679 setMini ? emacsframe->output_data.ns->miniimage : nil];
5686 - (void) setRows: (int) r andColumns: (int) c
5692 @end /* EmacsView */
5696 /* ==========================================================================
5698 EmacsWindow implementation
5700 ========================================================================== */
5702 @implementation EmacsWindow
5704 /* called only on resize clicks by special case in EmacsApp-sendEvent */
5705 - (void)mouseDown: (NSEvent *)theEvent
5709 NSSize size = [[theEvent window] frame].size;
5710 grabOffset = [theEvent locationInWindow];
5711 grabOffset.x = size.width - grabOffset.x;
5714 [super mouseDown: theEvent];
5719 - (void)mouseUp: (NSEvent *)theEvent
5723 struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
5725 ns_set_name_as_filename (f);
5727 ns_send_appdefined (-1);
5730 [super mouseUp: theEvent];
5734 /* send resize events */
5735 - (void)mouseDragged: (NSEvent *)theEvent
5739 NSPoint p = [theEvent locationInWindow];
5740 NSSize size, vettedSize, origSize = [self frame].size;
5742 size.width = p.x + grabOffset.x;
5743 size.height = origSize.height - p.y + grabOffset.y;
5745 if (size.width == origSize.width && size.height == origSize.height)
5748 vettedSize = [[self delegate] windowWillResize: self toSize: size];
5749 if (vettedSize.width != size.width || vettedSize.height != size.height)
5751 [[NSNotificationCenter defaultCenter]
5752 postNotificationName: NSWindowDidResizeNotification
5757 [super mouseDragged: theEvent];
5760 @end /* EmacsWindow */
5763 /* ==========================================================================
5765 EmacsScroller implementation
5767 ========================================================================== */
5770 @implementation EmacsScroller
5772 /* for repeat button push */
5773 #define SCROLL_BAR_FIRST_DELAY 0.5
5774 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
5776 + (CGFloat) scrollerWidth
5778 /* TODO: if we want to allow variable widths, this is the place to do it,
5779 however neither GNUstep nor Cocoa support it very well */
5780 return [NSScroller scrollerWidth];
5784 - initFrame: (NSRect )r window: (Lisp_Object)nwin
5786 NSTRACE (EmacsScroller_initFrame);
5788 r.size.width = [EmacsScroller scrollerWidth];
5789 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
5790 [self setContinuous: YES];
5791 [self setEnabled: YES];
5793 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
5794 locked against the top and bottom edges, and right edge on OS X, where
5795 scrollers are on right. */
5796 #ifdef NS_IMPL_GNUSTEP
5797 [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
5799 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
5804 pixel_height = NSHeight (r);
5805 min_portion = 20 / pixel_height;
5807 frame = XFRAME (XWINDOW (win)->frame);
5808 if (FRAME_LIVE_P (frame))
5811 EmacsView *view = FRAME_NS_VIEW (frame);
5812 NSView *sview = [[view window] contentView];
5813 NSArray *subs = [sview subviews];
5815 /* disable optimization stopping redraw of other scrollbars */
5816 view->scrollbarsNeedingUpdate = 0;
5817 for (i =[subs count]-1; i >= 0; i--)
5818 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
5819 view->scrollbarsNeedingUpdate++;
5820 [sview addSubview: self];
5823 /* [self setFrame: r]; */
5829 - (void)setFrame: (NSRect)newRect
5831 NSTRACE (EmacsScroller_setFrame);
5833 pixel_height = NSHeight (newRect);
5834 min_portion = 20 / pixel_height;
5835 [super setFrame: newRect];
5837 /* UNBLOCK_INPUT; */
5843 NSTRACE (EmacsScroller_dealloc);
5845 XWINDOW (win)->vertical_scroll_bar = Qnil;
5873 /* ensure other scrollbar updates after deletion */
5874 view = (EmacsView *)FRAME_NS_VIEW (frame);
5876 view->scrollbarsNeedingUpdate++;
5877 [self removeFromSuperview];
5885 - (void)resetCursorRects
5887 NSRect visible = [self visibleRect];
5888 NSTRACE (resetCursorRects);
5890 if (!NSIsEmptyRect (visible))
5891 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
5892 [[NSCursor arrowCursor] setOnMouseEntered: YES];
5896 - (int) checkSamePosition: (int) position portion: (int) portion
5899 return em_position ==position && em_portion ==portion && em_whole ==whole
5900 && portion != whole; /* needed for resize empty buf */
5904 - setPosition: (int)position portion: (int)portion whole: (int)whole
5906 NSTRACE (setPosition);
5908 em_position = position;
5909 em_portion = portion;
5912 if (portion >= whole)
5913 [self setFloatValue: 0.0 knobProportion: 1.0];
5917 portion = max ((float)whole*min_portion/pixel_height, portion);
5918 pos = (float)position / (whole - portion);
5919 por = (float)portion/whole;
5920 [self setFloatValue: pos knobProportion: por];
5925 /* FIXME: unused at moment (see ns_mouse_position) at the moment because
5926 drag events will go directly to the EmacsScroller. Leaving in for now. */
5927 -(void)getMouseMotionPart: (int *)part window: (Lisp_Object *)window
5928 x: (Lisp_Object *)x y: ( Lisp_Object *)y
5930 *part = last_hit_part;
5932 XSETINT (*y, pixel_height);
5933 if ([self floatValue] > 0.999)
5934 XSETINT (*x, pixel_height);
5936 XSETINT (*x, pixel_height * [self floatValue]);
5940 /* set up emacs_event */
5941 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
5946 emacs_event->part = last_hit_part;
5947 emacs_event->code = 0;
5948 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
5949 emacs_event->frame_or_window = win;
5950 emacs_event->timestamp = EV_TIMESTAMP (e);
5951 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
5952 emacs_event->arg = Qnil;
5953 XSETINT (emacs_event->x, loc * pixel_height);
5954 XSETINT (emacs_event->y, pixel_height-20);
5956 n_emacs_events_pending++;
5957 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
5958 EVENT_INIT (*emacs_event);
5959 ns_send_appdefined (-1);
5963 /* called manually thru timer to implement repeated button action w/hold-down */
5964 - repeatScroll: (NSTimer *)scrollEntry
5966 NSEvent *e = [[self window] currentEvent];
5967 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
5968 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
5970 /* clear timer if need be */
5971 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
5973 [scroll_repeat_entry invalidate];
5974 [scroll_repeat_entry release];
5975 scroll_repeat_entry = nil;
5981 = [[NSTimer scheduledTimerWithTimeInterval:
5982 SCROLL_BAR_CONTINUOUS_DELAY
5984 selector: @selector (repeatScroll:)
5990 [self sendScrollEventAtLoc: 0 fromEvent: e];
5995 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
5996 mouseDragged events without going into a modal loop. */
5997 - (void)mouseDown: (NSEvent *)e
6000 /* hitPart is only updated AFTER event is passed on */
6001 NSScrollerPart part = [self testPart: [e locationInWindow]];
6002 double inc = 0.0, loc, kloc, pos;
6005 NSTRACE (EmacsScroller_mouseDown);
6009 case NSScrollerDecrementPage:
6010 last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
6011 case NSScrollerIncrementPage:
6012 last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
6013 case NSScrollerDecrementLine:
6014 last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
6015 case NSScrollerIncrementLine:
6016 last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
6017 case NSScrollerKnob:
6018 last_hit_part = scroll_bar_handle; break;
6019 case NSScrollerKnobSlot: /* GNUstep-only */
6020 last_hit_part = scroll_bar_move_ratio; break;
6021 default: /* NSScrollerNoPart? */
6022 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
6029 pos = 0; /* ignored */
6031 /* set a timer to repeat, as we can't let superclass do this modally */
6033 = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
6035 selector: @selector (repeatScroll:)
6042 /* handle, or on GNUstep possibly slot */
6043 NSEvent *fake_event;
6045 /* compute float loc in slot and mouse offset on knob */
6046 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6048 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6054 else if (loc >= NSHeight (sr))
6056 loc = NSHeight (sr);
6064 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
6066 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
6068 last_mouse_offset = kloc;
6070 /* if knob, tell emacs a location offset by knob pos
6071 (to indicate top of handle) */
6072 if (part == NSScrollerKnob)
6073 pos = (loc - last_mouse_offset) / NSHeight (sr);
6075 /* else this is a slot click on GNUstep: go straight there */
6076 pos = loc / NSHeight (sr);
6078 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
6079 fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
6080 location: [e locationInWindow]
6081 modifierFlags: [e modifierFlags]
6082 timestamp: [e timestamp]
6083 windowNumber: [e windowNumber]
6084 context: [e context]
6085 eventNumber: [e eventNumber]
6086 clickCount: [e clickCount]
6087 pressure: [e pressure]];
6088 [super mouseUp: fake_event];
6091 if (part != NSScrollerKnob)
6092 [self sendScrollEventAtLoc: pos fromEvent: e];
6096 /* Called as we manually track scroller drags, rather than superclass. */
6097 - (void)mouseDragged: (NSEvent *)e
6103 NSTRACE (EmacsScroller_mouseDragged);
6105 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6107 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6114 else if (loc >= NSHeight (sr) + last_mouse_offset)
6116 loc = NSHeight (sr) + last_mouse_offset;
6120 pos = /*(edge ? loc :*/ (loc - last_mouse_offset) / NSHeight (sr);
6121 [self sendScrollEventAtLoc: pos fromEvent: e];
6125 - (void)mouseUp: (NSEvent *)e
6127 if (scroll_repeat_entry)
6129 [scroll_repeat_entry invalidate];
6130 [scroll_repeat_entry release];
6131 scroll_repeat_entry = nil;
6137 /* treat scrollwheel events in the bar as though they were in the main window */
6138 - (void) scrollWheel: (NSEvent *)theEvent
6140 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
6141 [view mouseDown: theEvent];
6144 @end /* EmacsScroller */
6149 /* ==========================================================================
6151 Font-related functions; these used to be in nsfaces.m
6153 ========================================================================== */
6157 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
6159 struct font *font = XFONT_OBJECT (font_object);
6162 fontset = fontset_from_font (font_object);
6163 FRAME_FONTSET (f) = fontset;
6165 if (FRAME_FONT (f) == font)
6166 /* This font is already set in frame F. There's nothing more to
6170 FRAME_FONT (f) = font;
6172 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
6173 FRAME_COLUMN_WIDTH (f) = font->average_width;
6174 FRAME_SPACE_WIDTH (f) = font->space_width;
6175 FRAME_LINE_HEIGHT (f) = font->height;
6177 compute_fringe_widths (f, 1);
6179 /* Compute the scroll bar width in character columns. */
6180 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
6182 int wid = FRAME_COLUMN_WIDTH (f);
6183 FRAME_CONFIG_SCROLL_BAR_COLS (f)
6184 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
6188 int wid = FRAME_COLUMN_WIDTH (f);
6189 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
6192 /* Now make the frame display the given font. */
6193 if (FRAME_NS_WINDOW (f) != 0)
6194 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
6200 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
6201 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
6205 ns_xlfd_to_fontname (const char *xlfd)
6206 /* --------------------------------------------------------------------------
6207 Convert an X font name (XLFD) to an NS font name.
6208 Only family is used.
6209 The string returned is temporarily allocated.
6210 -------------------------------------------------------------------------- */
6212 char *name = xmalloc (180);
6216 if (!strncmp (xlfd, "--", 2))
6217 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
6219 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
6221 /* stopgap for malformed XLFD input */
6222 if (strlen (name) == 0)
6223 strcpy (name, "Monaco");
6225 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
6226 also uppercase after '-' or ' ' */
6227 name[0] = toupper (name[0]);
6228 for (len =strlen (name), i =0; i<len; i++)
6234 name[i+1] = toupper (name[i+1]);
6236 else if (name[i] == '_')
6240 name[i+1] = toupper (name[i+1]);
6243 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
6244 ret = [[NSString stringWithUTF8String: name] UTF8String];
6251 syms_of_nsterm (void)
6253 NSTRACE (syms_of_nsterm);
6255 ns_antialias_threshold = 10.0;
6257 /* from 23+ we need to tell emacs what modifiers there are.. */
6258 DEFSYM (Qmodifier_value, "modifier-value");
6259 DEFSYM (Qalt, "alt");
6260 DEFSYM (Qhyper, "hyper");
6261 DEFSYM (Qmeta, "meta");
6262 DEFSYM (Qsuper, "super");
6263 DEFSYM (Qcontrol, "control");
6264 DEFSYM (Qnone, "none");
6265 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
6266 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
6267 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
6268 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
6269 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
6271 DEFVAR_LISP ("ns-input-file", &ns_input_file,
6272 "The file specified in the last NS event.");
6273 ns_input_file =Qnil;
6275 DEFVAR_LISP ("ns-input-text", &ns_input_text,
6276 "The data received in the last NS text drag event.");
6277 ns_input_text =Qnil;
6279 DEFVAR_LISP ("ns-working-text", &ns_working_text,
6280 "String for visualizing working composition sequence.");
6281 ns_working_text =Qnil;
6283 DEFVAR_LISP ("ns-input-font", &ns_input_font,
6284 "The font specified in the last NS event.");
6285 ns_input_font =Qnil;
6287 DEFVAR_LISP ("ns-input-fontsize", &ns_input_fontsize,
6288 "The fontsize specified in the last NS event.");
6289 ns_input_fontsize =Qnil;
6291 DEFVAR_LISP ("ns-input-line", &ns_input_line,
6292 "The line specified in the last NS event.");
6293 ns_input_line =Qnil;
6295 DEFVAR_LISP ("ns-input-color", &ns_input_color,
6296 "The color specified in the last NS event.");
6297 ns_input_color =Qnil;
6299 DEFVAR_LISP ("ns-input-spi-name", &ns_input_spi_name,
6300 "The service name specified in the last NS event.");
6301 ns_input_spi_name =Qnil;
6303 DEFVAR_LISP ("ns-input-spi-arg", &ns_input_spi_arg,
6304 "The service argument specified in the last NS event.");
6305 ns_input_spi_arg =Qnil;
6307 DEFVAR_LISP ("ns-alternate-modifier", &ns_alternate_modifier,
6308 "This variable describes the behavior of the alternate or option key.\n\
6309 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6310 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6311 at all, allowing it to be used at a lower level for accented character entry.");
6312 ns_alternate_modifier = Qmeta;
6314 DEFVAR_LISP ("ns-right-alternate-modifier", &ns_right_alternate_modifier,
6315 "This variable describes the behavior of the right alternate or option key.\n\
6316 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6317 Set to left means be the same key as `ns-alternate-modifier'.\n\
6318 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6319 at all, allowing it to be used at a lower level for accented character entry.");
6320 ns_right_alternate_modifier = Qleft;
6322 DEFVAR_LISP ("ns-command-modifier", &ns_command_modifier,
6323 "This variable describes the behavior of the command key.\n\
6324 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6325 ns_command_modifier = Qsuper;
6327 DEFVAR_LISP ("ns-right-command-modifier", &ns_right_command_modifier,
6328 "This variable describes the behavior of the right command key.\n\
6329 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6330 Set to left means be the same key as `ns-command-modifier'.\n\
6331 Set to none means that the command / option key is not interpreted by Emacs\n\
6332 at all, allowing it to be used at a lower level for accented character entry.");
6333 ns_right_command_modifier = Qleft;
6335 DEFVAR_LISP ("ns-control-modifier", &ns_control_modifier,
6336 "This variable describes the behavior of the control key.\n\
6337 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6338 ns_control_modifier = Qcontrol;
6340 DEFVAR_LISP ("ns-right-control-modifier", &ns_right_control_modifier,
6341 "This variable describes the behavior of the right control key.\n\
6342 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6343 Set to left means be the same key as `ns-control-modifier'.\n\
6344 Set to none means that the control / option key is not interpreted by Emacs\n\
6345 at all, allowing it to be used at a lower level for accented character entry.");
6346 ns_right_control_modifier = Qleft;
6348 DEFVAR_LISP ("ns-function-modifier", &ns_function_modifier,
6349 "This variable describes the behavior of the function key (on laptops).\n\
6350 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6351 Set to none means that the function key is not interpreted by Emacs at all,\n\
6352 allowing it to be used at a lower level for accented character entry.");
6353 ns_function_modifier = Qnone;
6355 DEFVAR_LISP ("ns-antialias-text", &ns_antialias_text,
6356 "Non-nil (the default) means to render text antialiased. Only has an effect on OS X Panther and above.");
6357 ns_antialias_text = Qt;
6359 DEFVAR_LISP ("ns-confirm-quit", &ns_confirm_quit,
6360 "Whether to confirm application quit using dialog.");
6361 ns_confirm_quit = Qnil;
6363 staticpro (&ns_display_name_list);
6364 ns_display_name_list = Qnil;
6366 staticpro (&last_mouse_motion_frame);
6367 last_mouse_motion_frame = Qnil;
6369 /* TODO: move to common code */
6370 DEFVAR_LISP ("x-toolkit-scroll-bars", &Vx_toolkit_scroll_bars,
6371 doc: /* If not nil, Emacs uses toolkit scroll bars. */);
6372 #ifdef USE_TOOLKIT_SCROLL_BARS
6373 Vx_toolkit_scroll_bars = Qt;
6375 Vx_toolkit_scroll_bars = Qnil;
6378 /* these are unsupported but we need the declarations to avoid whining
6379 messages from cus-start.el */
6380 DEFVAR_BOOL ("x-use-underline-position-properties",
6381 &x_use_underline_position_properties,
6382 doc: /* NOT SUPPORTED UNDER NS.
6383 *Non-nil means make use of UNDERLINE_POSITION font properties.
6384 A value of nil means ignore them. If you encounter fonts with bogus
6385 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
6386 to 4.1, set this to nil.
6388 NOTE: Not supported on Mac yet. */);
6389 x_use_underline_position_properties = 0;
6391 DEFVAR_BOOL ("x-underline-at-descent-line",
6392 &x_underline_at_descent_line,
6393 doc: /* NOT SUPPORTED UNDER NS.
6394 *Non-nil means to draw the underline at the same place as the descent line.
6395 A value of nil means to draw the underline according to the value of the
6396 variable `x-use-underline-position-properties', which is usually at the
6397 baseline level. The default value is nil. */);
6398 x_underline_at_descent_line = 0;
6400 /* Tell emacs about this window system. */
6401 Fprovide (intern ("ns"), Qnil);
6405 // arch-tag: 6eaa8f7d-a69b-4e1c-b43d-ab31defbe0d2