1 /* NeXT/Open/GNUstep / MacOSX communication module.
2 Copyright (C) 1989, 1993, 1994, 2005, 2006, 2008, 2009
3 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 Originally by Carl Edman
22 Updated by Christian Limpach (chris@nice.ch)
23 OpenStep/Rhapsody port by Scott Bender (sbender@harmony-ds.com)
24 MacOSX/Aqua port by Christophe de Dinechin (descubes@earthlink.net)
25 GNUstep port and post-20 update by Adrian Robert (arobert@cogsci.ucsd.edu)
28 /* This should be the first include, as it may set up #defines affecting
29 interpretation of even the system includes. */
33 #include <sys/types.h>
39 #include "blockinput.h"
40 #include "sysselect.h"
43 #include "character.h"
45 #include "composite.h"
48 #include "termhooks.h"
59 int term_trace_num = 0;
60 #define NSTRACE(x) fprintf (stderr, "%s:%d: [%d] " #x "\n", \
61 __FILE__, __LINE__, ++term_trace_num)
67 /* ==========================================================================
71 ========================================================================== */
73 /* Convert a symbol indexed with an NSxxx value to a value as defined
74 in keyboard.c (lispy_function_key). I hope this is a correct way
76 static unsigned convert_ns_to_X_keysym[] =
78 NSHomeFunctionKey, 0x50,
79 NSLeftArrowFunctionKey, 0x51,
80 NSUpArrowFunctionKey, 0x52,
81 NSRightArrowFunctionKey, 0x53,
82 NSDownArrowFunctionKey, 0x54,
83 NSPageUpFunctionKey, 0x55,
84 NSPageDownFunctionKey, 0x56,
85 NSEndFunctionKey, 0x57,
86 NSBeginFunctionKey, 0x58,
87 NSSelectFunctionKey, 0x60,
88 NSPrintFunctionKey, 0x61,
89 NSExecuteFunctionKey, 0x62,
90 NSInsertFunctionKey, 0x63,
91 NSUndoFunctionKey, 0x65,
92 NSRedoFunctionKey, 0x66,
93 NSMenuFunctionKey, 0x67,
94 NSFindFunctionKey, 0x68,
95 NSHelpFunctionKey, 0x6A,
96 NSBreakFunctionKey, 0x6B,
98 NSF1FunctionKey, 0xBE,
99 NSF2FunctionKey, 0xBF,
100 NSF3FunctionKey, 0xC0,
101 NSF4FunctionKey, 0xC1,
102 NSF5FunctionKey, 0xC2,
103 NSF6FunctionKey, 0xC3,
104 NSF7FunctionKey, 0xC4,
105 NSF8FunctionKey, 0xC5,
106 NSF9FunctionKey, 0xC6,
107 NSF10FunctionKey, 0xC7,
108 NSF11FunctionKey, 0xC8,
109 NSF12FunctionKey, 0xC9,
110 NSF13FunctionKey, 0xCA,
111 NSF14FunctionKey, 0xCB,
112 NSF15FunctionKey, 0xCC,
113 NSF16FunctionKey, 0xCD,
114 NSF17FunctionKey, 0xCE,
115 NSF18FunctionKey, 0xCF,
116 NSF19FunctionKey, 0xD0,
117 NSF20FunctionKey, 0xD1,
118 NSF21FunctionKey, 0xD2,
119 NSF22FunctionKey, 0xD3,
120 NSF23FunctionKey, 0xD4,
121 NSF24FunctionKey, 0xD5,
123 NSBackspaceCharacter, 0x08, /* 8: Not on some KBs. */
124 NSDeleteCharacter, 0xFF, /* 127: Big 'delete' key upper right. */
125 NSDeleteFunctionKey, 0x9F, /* 63272: Del forw key off main array. */
127 NSTabCharacter, 0x09,
128 0x19, 0x09, /* left tab->regular since pass shift */
129 NSCarriageReturnCharacter, 0x0D,
130 NSNewlineCharacter, 0x0D,
131 NSEnterCharacter, 0x8D,
133 0x1B, 0x1B /* escape */
137 /* Lisp communications */
138 Lisp_Object ns_input_file, ns_input_font, ns_input_fontsize, ns_input_line;
139 Lisp_Object ns_input_color, ns_input_text, ns_working_text;
140 Lisp_Object ns_input_spi_name, ns_input_spi_arg;
141 Lisp_Object Vx_toolkit_scroll_bars;
142 static Lisp_Object Qmodifier_value;
143 /* TODO: unsure why these defined in term files, anyway we need in keymap.c */
144 Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper;
145 extern Lisp_Object Qcursor_color, Qcursor_type, Qns;
148 /* Some preferences equivalent to those set by X resources under X are
149 managed through the OpenStep defaults system. We depart from X
150 behavior and refuse to read defaults when started under these
153 /* Set in emacs.c. */
156 /* Specifies which emacs modifier should be generated when NS receives
157 the Alternate modifer. May be Qnone or any of the modifier lisp symbols. */
158 Lisp_Object ns_alternate_modifier;
160 /* Specifies which emacs modifier should be generated when NS receives
161 the Command modifer. May be any of the modifier lisp symbols. */
162 Lisp_Object ns_command_modifier;
164 /* Specifies which emacs modifier should be generated when NS receives
165 the Control modifer. May be any of the modifier lisp symbols. */
166 Lisp_Object ns_control_modifier;
168 /* Specifies which emacs modifier should be generated when NS receives
169 the Function modifer (laptops). May be any of the modifier lisp symbols. */
170 Lisp_Object ns_function_modifier;
172 /* Control via default 'GSFontAntiAlias' on OS X and GNUstep. */
173 Lisp_Object ns_antialias_text;
175 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
176 the maximum font size to NOT antialias. On GNUstep there is currently
177 no way to control this behavior. */
178 float ns_antialias_threshold;
180 /* Controls use of an undocumented CG function to do Quickdraw-style font
181 smoothing (less heavy) instead of regular Quartz smoothing. */
182 Lisp_Object ns_use_qd_smoothing;
184 /* Used to pick up AppleHighlightColor on OS X */
185 Lisp_Object ns_use_system_highlight_color;
186 NSString *ns_selection_color;
188 /* Confirm on exit. */
189 Lisp_Object ns_confirm_quit;
191 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
193 /* Display variables */
194 struct ns_display_info *x_display_list; /* Chain of existing displays */
195 Lisp_Object ns_display_name_list;
196 long context_menu_value = 0;
199 NSPoint last_mouse_motion_position;
200 static NSRect last_mouse_glyph;
201 static unsigned long last_mouse_movement_time = 0;
202 static Lisp_Object last_mouse_motion_frame;
203 static EmacsScroller *last_mouse_scroll_bar = nil;
204 static struct frame *ns_updating_frame;
205 static NSView *focus_view = NULL;
206 static int ns_window_num =0;
208 static BOOL gsaved = NO;
209 BOOL ns_in_resize = NO;
210 static BOOL ns_fake_keydown = NO;
211 int ns_tmp_flags; /* FIXME */
212 struct nsfont_info *ns_tmp_font; /* FIXME */
213 /*static int debug_lock = 0; */
216 /* This undocumented Quartz function controls how fonts are anti-aliased.
217 (Found from code in Mac wxWindows impl, discovered by running `nm' on
219 Mode 0 is normal anti-aliasing, mode 1 is no anti-aliasing, and mode 2 is
220 4-bit pixel-aligned anti-aliasing (the old QuickDraw standard). */
221 extern void CGContextSetFontRenderingMode (CGContextRef cg, int v);
226 static BOOL send_appdefined = YES;
227 static NSEvent *last_appdefined_event = 0;
228 static NSTimer *timed_entry = 0;
229 static NSTimer *fd_entry = nil;
230 static NSTimer *scroll_repeat_entry = nil;
231 static fd_set select_readfds, t_readfds;
232 static struct timeval select_timeout;
233 static int select_nfds;
234 static NSAutoreleasePool *outerpool;
235 static struct input_event *emacs_event = NULL;
236 static struct input_event *q_event_ptr = NULL;
237 static int n_emacs_events_pending = 0;
238 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
239 *ns_pending_service_args;
240 static BOOL inNsSelect = 0;
242 /* Convert modifiers in a NeXTSTEP event to emacs style modifiers. */
243 #define NS_FUNCTION_KEY_MASK 0x800000
244 #define EV_MODIFIERS(e) \
245 ((([e modifierFlags] & NSHelpKeyMask) ? \
246 hyper_modifier : 0) \
247 | (([e modifierFlags] & NSAlternateKeyMask) ? \
248 parse_solitary_modifier (ns_alternate_modifier) : 0) \
249 | (([e modifierFlags] & NSShiftKeyMask) ? \
250 shift_modifier : 0) \
251 | (([e modifierFlags] & NSControlKeyMask) ? \
252 parse_solitary_modifier (ns_control_modifier) : 0) \
253 | (([e modifierFlags] & NS_FUNCTION_KEY_MASK) ? \
254 parse_solitary_modifier (ns_function_modifier) : 0) \
255 | (([e modifierFlags] & NSCommandKeyMask) ? \
256 parse_solitary_modifier (ns_command_modifier):0))
258 #define EV_UDMODIFIERS(e) \
259 ((([e type] == NSLeftMouseDown) ? down_modifier : 0) \
260 | (([e type] == NSRightMouseDown) ? down_modifier : 0) \
261 | (([e type] == NSOtherMouseDown) ? down_modifier : 0) \
262 | (([e type] == NSLeftMouseDragged) ? down_modifier : 0) \
263 | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
264 | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
265 | (([e type] == NSLeftMouseUp) ? up_modifier : 0) \
266 | (([e type] == NSRightMouseUp) ? up_modifier : 0) \
267 | (([e type] == NSOtherMouseUp) ? up_modifier : 0))
269 #define EV_BUTTON(e) \
270 ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 : \
271 (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
272 [e buttonNumber] - 1)
274 /* Convert the time field to a timestamp in milliseconds. */
275 #ifdef NS_IMPL_GNUSTEP
276 /* Apple says timestamp is in seconds, but GNUstep seems to be returning msec */
277 #define EV_TIMESTAMP(e) ([e timestamp])
279 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
280 #endif /* not gnustep */
282 /* This is a piece of code which is common to all the event handling
283 methods. Maybe it should even be a function. */
284 #define EV_TRAILER(e) \
286 XSETFRAME (emacs_event->frame_or_window, emacsframe); \
287 if (e) emacs_event->timestamp = EV_TIMESTAMP (e); \
288 n_emacs_events_pending++; \
289 kbd_buffer_store_event_hold (emacs_event, q_event_ptr); \
290 EVENT_INIT (*emacs_event); \
291 ns_send_appdefined (-1); \
294 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
296 /* TODO: get rid of need for these forward declarations */
297 static void ns_condemn_scroll_bars (struct frame *f);
298 static void ns_judge_scroll_bars (struct frame *f);
299 void x_set_frame_alpha (struct frame *f);
301 /* unused variables needed for compatibility reasons */
302 int x_use_underline_position_properties, x_underline_at_descent_line;
303 /* FIXME: figure out what to do with underline_minimum_offset. */
306 /* ==========================================================================
310 ========================================================================== */
314 append2 (Lisp_Object list, Lisp_Object item)
315 /* --------------------------------------------------------------------------
316 Utility to append to a list
317 -------------------------------------------------------------------------- */
319 Lisp_Object array[2];
321 array[1] = Fcons (item, Qnil);
322 return Fnconc (2, &array[0]);
328 /* --------------------------------------------------------------------------
329 Used to allow emacs to find its resources under Emacs.app
330 Called from emacs.c at startup.
331 -------------------------------------------------------------------------- */
333 NSBundle *bundle = [NSBundle mainBundle];
334 NSString *binDir = [bundle bundlePath], *resourceDir = [bundle resourcePath];
335 NSString *resourcePath, *resourcePaths;
337 BOOL onWindows = NO; /* how do I determine this? */
338 NSString *pathSeparator = onWindows ? @";" : @":";
339 NSFileManager *fileManager = [NSFileManager defaultManager];
341 /*NSLog (@"ns_init_paths: '%@'\n%@\n", [[NSBundle mainBundle] bundlePath], [[NSBundle mainBundle] resourcePath]); */
343 /* get bindir from base */
344 range = [resourceDir rangeOfString: @"Contents"];
345 if (range.location != NSNotFound)
347 binDir = [binDir stringByAppendingPathComponent: @"Contents"];
349 binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
353 /* the following based on Andrew Choi's init_mac_osx_environment () */
354 if (!getenv ("EMACSLOADPATH"))
356 NSArray *paths = [resourceDir stringsByAppendingPaths:
357 [NSArray arrayWithObjects:
358 @"site-lisp", @"lisp", @"leim", nil]];
359 NSEnumerator *pathEnum = [paths objectEnumerator];
361 while (resourcePath = [pathEnum nextObject])
363 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
366 if ([resourcePaths length] > 0)
368 = [resourcePaths stringByAppendingString: pathSeparator];
370 = [resourcePaths stringByAppendingString: resourcePath];
373 if ([resourcePaths length] > 0)
374 setenv ("EMACSLOADPATH", [resourcePaths UTF8String], 1);
375 /*NSLog (@"loadPath: '%s'\n", resourcePaths); */
378 if (!getenv ("EMACSPATH"))
380 NSArray *paths = [binDir stringsByAppendingPaths:
381 [NSArray arrayWithObjects: @"bin",
383 NSEnumerator *pathEnum = [paths objectEnumerator];
385 while (resourcePath = [pathEnum nextObject])
387 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
390 if ([resourcePaths length] > 0)
392 = [resourcePaths stringByAppendingString: pathSeparator];
394 = [resourcePaths stringByAppendingString: resourcePath];
397 if ([resourcePaths length] > 0)
398 setenv ("EMACSPATH", [resourcePaths UTF8String], 1);
401 resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
402 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
406 if (!getenv ("EMACSDATA"))
407 setenv ("EMACSDATA", [resourcePath UTF8String], 1);
408 if (!getenv ("EMACSDOC"))
409 setenv ("EMACSDOC", [resourcePath UTF8String], 1);
413 if (!getenv ("INFOPATH"))
415 resourcePath = [resourceDir stringByAppendingPathComponent: @"info"];
416 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
418 setenv ("INFOPATH", [resourcePath UTF8String], 1);
424 timeval_subtract (struct timeval *result, struct timeval x, struct timeval y)
425 /* --------------------------------------------------------------------------
426 Subtract the `struct timeval' values X and Y, storing the result in RESULT.
427 Return 1 if the difference is negative, otherwise 0.
428 -------------------------------------------------------------------------- */
430 /* Perform the carry for the later subtraction by updating y.
431 This is safer because on some systems
432 the tv_sec member is unsigned. */
433 if (x.tv_usec < y.tv_usec)
435 int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
436 y.tv_usec -= 1000000 * nsec;
439 if (x.tv_usec - y.tv_usec > 1000000)
441 int nsec = (y.tv_usec - x.tv_usec) / 1000000;
442 y.tv_usec += 1000000 * nsec;
446 /* Compute the time remaining to wait. tv_usec is certainly positive. */
447 result->tv_sec = x.tv_sec - y.tv_sec;
448 result->tv_usec = x.tv_usec - y.tv_usec;
450 /* Return indication of whether the result should be considered negative. */
451 return x.tv_sec < y.tv_sec;
455 ns_timeout (int usecs)
456 /* --------------------------------------------------------------------------
457 Blocking timer utility used by ns_ring_bell
458 -------------------------------------------------------------------------- */
460 struct timeval wakeup;
462 EMACS_GET_TIME (wakeup);
464 /* Compute time to wait until, propagating carry from usecs. */
465 wakeup.tv_usec += usecs;
466 wakeup.tv_sec += (wakeup.tv_usec / 1000000);
467 wakeup.tv_usec %= 1000000;
469 /* Keep waiting until past the time wakeup. */
472 struct timeval timeout;
474 EMACS_GET_TIME (timeout);
476 /* In effect, timeout = wakeup - timeout.
477 Break if result would be negative. */
478 if (timeval_subtract (&timeout, wakeup, timeout))
481 /* Try to wait that long--but we might wake up sooner. */
482 select (0, NULL, NULL, NULL, &timeout);
488 ns_release_object (void *obj)
489 /* --------------------------------------------------------------------------
490 Release an object (callable from C)
491 -------------------------------------------------------------------------- */
498 ns_retain_object (void *obj)
499 /* --------------------------------------------------------------------------
500 Retain an object (callable from C)
501 -------------------------------------------------------------------------- */
508 ns_alloc_autorelease_pool ()
509 /* --------------------------------------------------------------------------
510 Allocate a pool for temporary objects (callable from C)
511 -------------------------------------------------------------------------- */
513 return [[NSAutoreleasePool alloc] init];
518 ns_release_autorelease_pool (void *pool)
519 /* --------------------------------------------------------------------------
520 Free a pool and temporary objects it refers to (callable from C)
521 -------------------------------------------------------------------------- */
523 ns_release_object (pool);
528 /* ==========================================================================
530 Focus (clipping) and screen update
532 ========================================================================== */
535 ns_resize_handle_rect (NSWindow *window)
537 NSRect r = [window frame];
538 r.origin.x = r.size.width - RESIZE_HANDLE_SIZE;
540 r.size.width = r.size.height = RESIZE_HANDLE_SIZE;
546 ns_update_begin (struct frame *f)
547 /* --------------------------------------------------------------------------
548 Prepare for a grouped sequence of drawing calls
549 external (RIF) call; whole frame, called before update_window_begin
550 -------------------------------------------------------------------------- */
552 NSView *view = FRAME_NS_VIEW (f);
553 NSTRACE (ns_update_begin);
555 ns_updating_frame = f;
558 #ifdef NS_IMPL_GNUSTEP
559 uRect = NSMakeRect (0, 0, 0, 0);
565 ns_update_window_begin (struct window *w)
566 /* --------------------------------------------------------------------------
567 Prepare for a grouped sequence of drawing calls
568 external (RIF) call; for one window, called after update_begin
569 -------------------------------------------------------------------------- */
571 struct frame *f = XFRAME (WINDOW_FRAME (w));
572 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
573 NSTRACE (ns_update_window_begin);
576 set_output_cursor (&w->cursor);
580 if (f == dpyinfo->mouse_face_mouse_frame)
582 /* Don't do highlighting for mouse motion during the update. */
583 dpyinfo->mouse_face_defer = 1;
585 /* If the frame needs to be redrawn,
586 simply forget about any prior mouse highlighting. */
587 if (FRAME_GARBAGED_P (f))
588 dpyinfo->mouse_face_window = Qnil;
590 /* (further code for mouse faces ifdef'd out in other terms elided) */
598 ns_update_window_end (struct window *w, int cursor_on_p,
599 int mouse_face_overwritten_p)
600 /* --------------------------------------------------------------------------
601 Finished a grouped sequence of drawing calls
602 external (RIF) call; for one window called before update_end
603 -------------------------------------------------------------------------- */
605 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (XFRAME (w->frame));
607 /* note: this fn is nearly identical in all terms */
608 if (!w->pseudo_window_p)
613 display_and_set_cursor (w, 1,
614 output_cursor.hpos, output_cursor.vpos,
615 output_cursor.x, output_cursor.y);
617 if (draw_window_fringes (w, 1))
618 x_draw_vertical_border (w);
623 /* If a row with mouse-face was overwritten, arrange for
624 frame_up_to_date to redisplay the mouse highlight. */
625 if (mouse_face_overwritten_p)
627 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
628 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
629 dpyinfo->mouse_face_window = Qnil;
632 updated_window = NULL;
633 NSTRACE (update_window_end);
638 ns_update_end (struct frame *f)
639 /* --------------------------------------------------------------------------
640 Finished a grouped sequence of drawing calls
641 external (RIF) call; for whole frame, called after update_window_end
642 -------------------------------------------------------------------------- */
644 NSView *view = FRAME_NS_VIEW (f);
646 /* if (f == FRAME_NS_DISPLAY_INFO (f)->mouse_face_mouse_frame) */
647 FRAME_NS_DISPLAY_INFO (f)->mouse_face_defer = 0;
651 #ifdef NS_IMPL_GNUSTEP
652 /* trigger flush only in the rectangle we tracked as being drawn */
653 [view unlockFocusNeedsFlush: NO];
654 /*fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", uRect.origin.x, uRect.origin.y, uRect.size.width, uRect.size.height); */
655 [view lockFocusInRect: uRect];
659 [[view window] flushWindow];
662 ns_updating_frame = NULL;
663 NSTRACE (ns_update_end);
668 ns_flush (struct frame *f)
669 /* --------------------------------------------------------------------------
671 NS impl is no-op since currently we flush in ns_update_end and elsewhere
672 -------------------------------------------------------------------------- */
679 ns_focus (struct frame *f, NSRect *r, int n)
680 /* --------------------------------------------------------------------------
681 Internal: Focus on given frame. During small local updates this is used to
682 draw, however during large updates, ns_update_begin and ns_update_end are
683 called to wrap the whole thing, in which case these calls are stubbed out.
684 Except, on GNUstep, we accumulate the rectangle being drawn into, because
685 the back end won't do this automatically, and will just end up flushing
687 -------------------------------------------------------------------------- */
689 // NSTRACE (ns_focus);
690 #ifdef NS_IMPL_GNUSTEP
693 u = NSUnionRect (r[0], r[1]);
698 fprintf (stderr, "focus: %d", c++);
699 if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
700 fprintf (stderr, "\n"); */
702 if (f != ns_updating_frame)
704 NSView *view = FRAME_NS_VIEW (f);
705 if (view != focus_view)
707 if (focus_view != NULL)
709 [focus_view unlockFocus];
710 [[focus_view window] flushWindow];
715 #ifdef NS_IMPL_GNUSTEP
716 r ? [view lockFocusInRect: u] : [view lockFocus];
721 /*if (view) debug_lock++; */
723 #ifdef NS_IMPL_GNUSTEP
726 /* more than one rect being drawn into */
729 [view unlockFocus]; /* add prev rect to redraw list */
730 [view lockFocusInRect: u]; /* focus for draw in new rect */
735 #ifdef NS_IMPL_GNUSTEP
738 /* in batch mode, but in GNUstep must still track rectangles explicitly */
739 uRect = (r ? NSUnionRect (uRect, u) : [FRAME_NS_VIEW (f) visibleRect]);
746 [[NSGraphicsContext currentContext] saveGraphicsState];
748 NSRectClipList (r, 2);
757 ns_unfocus (struct frame *f)
758 /* --------------------------------------------------------------------------
759 Internal: Remove focus on given frame
760 -------------------------------------------------------------------------- */
762 // NSTRACE (ns_unfocus);
766 [[NSGraphicsContext currentContext] restoreGraphicsState];
770 if (f != ns_updating_frame)
772 if (focus_view != NULL)
774 [focus_view unlockFocus];
775 [[focus_view window] flushWindow];
784 ns_clip_to_row (struct window *w, struct glyph_row *row, int area, BOOL gc)
785 /* --------------------------------------------------------------------------
786 Internal (but parallels other terms): Focus drawing on given row
787 -------------------------------------------------------------------------- */
789 struct frame *f = XFRAME (WINDOW_FRAME (w));
791 int window_x, window_y, window_width;
793 window_box (w, area, &window_x, &window_y, &window_width, 0);
795 clip_rect.origin.x = window_x - FRAME_INTERNAL_BORDER_WIDTH (f);
796 clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
797 clip_rect.origin.y = max (clip_rect.origin.y, window_y);
798 clip_rect.size.width = window_width + 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
799 clip_rect.size.height = row->visible_height;
801 /* allow a full-height row at the top when requested
802 (used to draw fringe all the way through internal border area) */
803 if (gc && clip_rect.origin.y < 5)
805 clip_rect.origin.y -= FRAME_INTERNAL_BORDER_WIDTH (f);
806 clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
809 /* likewise at bottom */
811 FRAME_PIXEL_HEIGHT (f) - (clip_rect.origin.y + clip_rect.size.height) < 5)
812 clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
814 ns_focus (f, &clip_rect, 1);
820 /* --------------------------------------------------------------------------
822 -------------------------------------------------------------------------- */
824 NSTRACE (ns_ring_bell);
827 NSAutoreleasePool *pool;
828 struct frame *frame = SELECTED_FRAME ();
832 pool = [[NSAutoreleasePool alloc] init];
834 view = FRAME_NS_VIEW (frame);
838 NSPoint dim = NSMakePoint (128, 128);
841 r.origin.x += (r.size.width - dim.x) / 2;
842 r.origin.y += (r.size.height - dim.y) / 2;
843 r.size.width = dim.x;
844 r.size.height = dim.y;
845 surr = NSInsetRect (r, -2, -2);
846 ns_focus (frame, &surr, 1);
847 [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
848 [ns_lookup_indexed_color (NS_FACE_FOREGROUND
849 (FRAME_DEFAULT_FACE (frame)), frame) set];
851 [[view window] flushWindow];
853 [[view window] restoreCachedImage];
854 [[view window] flushWindow];
868 ns_reset_terminal_modes (struct terminal *terminal)
869 /* Externally called as hook */
871 NSTRACE (ns_reset_terminal_modes);
875 ns_set_terminal_modes (struct terminal *terminal)
876 /* Externally called as hook */
878 NSTRACE (ns_set_terminal_modes);
883 /* ==========================================================================
885 Frame / window manager related functions
887 ========================================================================== */
891 ns_raise_frame (struct frame *f)
892 /* --------------------------------------------------------------------------
893 Bring window to foreground and make it active
894 -------------------------------------------------------------------------- */
896 NSView *view = FRAME_NS_VIEW (f);
899 [[view window] makeKeyAndOrderFront: NSApp];
905 ns_lower_frame (struct frame *f)
906 /* --------------------------------------------------------------------------
908 -------------------------------------------------------------------------- */
910 NSView *view = FRAME_NS_VIEW (f);
913 [[view window] orderBack: NSApp];
919 ns_frame_raise_lower (struct frame *f, int raise)
920 /* --------------------------------------------------------------------------
922 -------------------------------------------------------------------------- */
924 NSTRACE (ns_frame_raise_lower);
934 ns_frame_rehighlight (struct frame *frame)
935 /* --------------------------------------------------------------------------
936 External (hook): called on things like window switching within frame
937 -------------------------------------------------------------------------- */
939 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
940 struct frame *old_highlight = dpyinfo->x_highlight_frame;
942 NSTRACE (ns_frame_rehighlight);
943 if (dpyinfo->x_focus_frame)
945 dpyinfo->x_highlight_frame
946 = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
947 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
948 : dpyinfo->x_focus_frame);
949 if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
951 FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
952 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
956 dpyinfo->x_highlight_frame = 0;
958 if (dpyinfo->x_highlight_frame &&
959 dpyinfo->x_highlight_frame != old_highlight)
963 x_update_cursor (old_highlight, 1);
964 x_set_frame_alpha (old_highlight);
966 if (dpyinfo->x_highlight_frame)
968 x_update_cursor (dpyinfo->x_highlight_frame, 1);
969 x_set_frame_alpha (dpyinfo->x_highlight_frame);
976 x_make_frame_visible (struct frame *f)
977 /* --------------------------------------------------------------------------
978 External: Show the window (X11 semantics)
979 -------------------------------------------------------------------------- */
981 NSTRACE (x_make_frame_visible);
982 /* XXX: at some points in past this was not needed, as the only place that
983 called this (frame.c:Fraise_frame ()) also called raise_lower;
984 if this ends up the case again, comment this out again. */
985 if (!FRAME_VISIBLE_P (f))
991 x_make_frame_invisible (struct frame *f)
992 /* --------------------------------------------------------------------------
993 External: Hide the window (X11 semantics)
994 -------------------------------------------------------------------------- */
996 NSView * view = FRAME_NS_VIEW (f);
997 NSTRACE (x_make_frame_invisible);
999 [[view window] orderOut: NSApp];
1000 f->async_visible = 0;
1001 f->async_iconified = 0;
1006 x_iconify_frame (struct frame *f)
1007 /* --------------------------------------------------------------------------
1008 External: Iconify window
1009 -------------------------------------------------------------------------- */
1011 NSView * view = FRAME_NS_VIEW (f);
1012 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1013 NSTRACE (x_iconify_frame);
1016 if (dpyinfo->x_highlight_frame == f)
1017 dpyinfo->x_highlight_frame = 0;
1019 if ([[view window] windowNumber] <= 0)
1021 /* the window is still deferred. Make it very small, bring it
1022 on screen and order it out. */
1023 NSRect s = { { 100, 100}, {0, 0} };
1025 t = [[view window] frame];
1026 [[view window] setFrame: s display: NO];
1027 [[view window] orderBack: NSApp];
1028 [[view window] orderOut: NSApp];
1029 [[view window] setFrame: t display: NO];
1031 [[view window] miniaturize: NSApp];
1036 x_destroy_window (struct frame *f)
1037 /* --------------------------------------------------------------------------
1038 External: Delete the window
1039 -------------------------------------------------------------------------- */
1041 NSView *view = FRAME_NS_VIEW (f);
1042 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1043 NSTRACE (x_destroy_window);
1046 [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1050 free_frame_menubar (f);
1052 if (FRAME_FACE_CACHE (f))
1053 free_frame_faces (f);
1055 if (f == dpyinfo->x_focus_frame)
1056 dpyinfo->x_focus_frame = 0;
1057 if (f == dpyinfo->x_highlight_frame)
1058 dpyinfo->x_highlight_frame = 0;
1059 if (f == dpyinfo->mouse_face_mouse_frame)
1061 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
1062 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
1063 dpyinfo->mouse_face_window = Qnil;
1064 dpyinfo->mouse_face_deferred_gc = 0;
1065 dpyinfo->mouse_face_mouse_frame = 0;
1068 xfree (f->output_data.ns);
1070 [[view window] close];
1079 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1080 /* --------------------------------------------------------------------------
1081 External: Position the window
1082 -------------------------------------------------------------------------- */
1085 NSView *view = FRAME_NS_VIEW (f);
1087 NSTRACE (x_set_offset);
1093 #ifdef NS_IMPL_GNUSTEP
1095 f->left_pos = 100; /* don't overlap menu */
1097 if (view != nil && (screen = [[view window] screen]))
1098 [[view window] setFrameTopLeftPoint:
1099 NSMakePoint (SCREENMAXBOUND (f->left_pos),
1100 SCREENMAXBOUND ([screen frame].size.height
1101 - NS_TOP_POS (f)))];
1107 x_set_window_size (struct frame *f, int change_grav, int cols, int rows)
1108 /* --------------------------------------------------------------------------
1109 Adjust window pixel size based on given character grid size
1110 Impl is a bit more complex than other terms, need to do some
1111 internal clipping and also pay attention to screen constraints.
1112 -------------------------------------------------------------------------- */
1114 EmacsView *view = FRAME_NS_VIEW (f);
1115 EmacsToolbar *toolbar = [view toolbar];
1116 NSWindow *window = [view window];
1117 NSScreen *screen = [window screen];
1118 NSRect wr = [window frame];
1119 int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1120 int pixelwidth, pixelheight;
1121 static int oldRows, oldCols, oldFontWidth, oldFontHeight;
1123 static struct frame *oldF;
1125 NSTRACE (x_set_window_size);
1129 && rows == oldRows && cols == oldCols
1130 && oldFontWidth == FRAME_COLUMN_WIDTH (f)
1131 && oldFontHeight == FRAME_LINE_HEIGHT (f)
1135 /*fprintf (stderr, "\tsetWindowSize: %d x %d, font size %d x %d\n", cols, rows, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f)); */
1139 check_frame_size (f, &rows, &cols);
1143 oldFontWidth = FRAME_COLUMN_WIDTH (f);
1144 oldFontHeight = FRAME_LINE_HEIGHT (f);
1147 f->scroll_bar_actual_width = NS_SCROLL_BAR_WIDTH (f);
1148 compute_fringe_widths (f, 0);
1150 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols);
1151 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
1153 /* If we have a toolbar, take its height into account. */
1155 FRAME_NS_TOOLBAR_HEIGHT (f) =
1156 /* XXX: GNUstep has not yet implemented the first method below, added
1157 in Panther, however the second is incorrect under Cocoa. */
1158 #ifdef NS_IMPL_COCOA
1159 NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1160 /* NOTE: previously this would generate wrong result if toolbar not
1161 yet displayed and fixing toolbar_height=32 helped, but
1162 now (200903) seems no longer needed */
1164 NSHeight ([NSWindow frameRectForContentRect: NSMakeRect (0, 0, 0, 0)
1165 styleMask: [window styleMask]])
1167 - FRAME_NS_TITLEBAR_HEIGHT (f);
1169 FRAME_NS_TOOLBAR_HEIGHT (f) = 0;
1171 wr.size.width = pixelwidth + f->border_width;
1172 wr.size.height = pixelheight + FRAME_NS_TITLEBAR_HEIGHT (f)
1173 + FRAME_NS_TOOLBAR_HEIGHT (f);
1175 /* constrain to screen if we can */
1178 NSSize sz = [screen visibleFrame].size;
1179 NSSize ez = { wr.size.width - sz.width, wr.size.height - sz.height };
1182 int cr = ez.width / FRAME_COLUMN_WIDTH (f) + 1;
1185 wr.size.width -= cr * FRAME_COLUMN_WIDTH (f);
1186 pixelwidth -= cr * FRAME_COLUMN_WIDTH (f);
1190 int rr = ez.height / FRAME_LINE_HEIGHT (f) + 1;
1193 wr.size.height -= rr * FRAME_LINE_HEIGHT (f);
1194 pixelheight -= rr * FRAME_LINE_HEIGHT (f);
1196 wr.origin.x = f->left_pos;
1197 wr.origin.y = [screen frame].size.height - NS_TOP_POS (f)
1201 [view setRows: rows andColumns: cols];
1202 [window setFrame: wr display: YES];
1204 /*fprintf (stderr, "\tx_set_window_size %d, %d\t%d, %d\n", cols, rows, pixelwidth, pixelheight); */
1206 /* This is a trick to compensate for Emacs' managing the scrollbar area
1207 as a fixed number of standard character columns. Instead of leaving
1208 blank space for the extra, we chopped it off above. Now for
1209 left-hand scrollbars, we shift all rendering to the left by the
1210 difference between the real width and Emacs' imagined one. For
1211 right-hand bars, don't worry about it since the extra is never used.
1212 (Obviously doesn't work for vertically split windows tho..) */
1213 NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1214 ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1215 - NS_SCROLL_BAR_WIDTH (f), 0)
1216 : NSMakePoint (0, 0);
1217 [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1218 [view setBoundsOrigin: origin];
1220 change_frame_size (f, rows, cols, 0, 1, 0); /* pretend, delay, safe */
1221 FRAME_PIXEL_WIDTH (f) = pixelwidth;
1222 FRAME_PIXEL_HEIGHT (f) = pixelheight;
1223 /* SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */
1225 mark_window_cursors_off (XWINDOW (f->root_window));
1226 cancel_mouse_face (f);
1233 /* ==========================================================================
1237 ========================================================================== */
1241 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1243 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1244 return color_table->colors[idx];
1249 ns_index_color (NSColor *color, struct frame *f)
1251 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1255 if (!color_table->colors)
1257 color_table->size = NS_COLOR_CAPACITY;
1258 color_table->avail = 1; /* skip idx=0 as marker */
1260 = (NSColor **)xmalloc (color_table->size * sizeof (NSColor *));
1261 color_table->empty_indices = [[NSMutableSet alloc] init];
1264 /* do we already have this color ? */
1267 for (i = 1; i < color_table->avail; i++)
1269 if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1271 [color_table->colors[i] retain];
1277 if ([color_table->empty_indices count] > 0)
1279 index = [color_table->empty_indices anyObject];
1280 [color_table->empty_indices removeObject: index];
1281 idx = [index unsignedIntValue];
1285 if (color_table->avail == color_table->size)
1287 color_table->size += NS_COLOR_CAPACITY;
1289 = (NSColor **)xrealloc (color_table->colors,
1290 color_table->size * sizeof (NSColor *));
1292 idx = color_table->avail++;
1295 color_table->colors[idx] = color;
1297 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1303 ns_free_indexed_color (unsigned long idx, struct frame *f)
1305 struct ns_color_table *color_table;
1312 color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1314 if (idx <= 0 || idx >= color_table->size) {
1315 message1("ns_free_indexed_color: Color index out of range.\n");
1319 index = [NSNumber numberWithUnsignedInt: idx];
1320 if ([color_table->empty_indices containsObject: index]) {
1321 message1("ns_free_indexed_color: attempt to free already freed color.\n");
1325 color = color_table->colors[idx];
1327 color_table->colors[idx] = nil;
1328 [color_table->empty_indices addObject: [NSNumber numberWithUnsignedInt: idx]];
1329 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1334 ns_get_color (const char *name, NSColor **col)
1335 /* --------------------------------------------------------------------------
1337 /* --------------------------------------------------------------------------
1338 /* On *Step, we recognize several color formats, in addition to a catalog
1339 of colors found in the file Emacs.clr. Color formats include:
1340 - #rrggbb or RGBrrggbb where rr, gg, bb specify red, green and blue in hex
1341 - ARGBaarrggbb is similar, with aa being the alpha channel (FF = opaque)
1342 - HSVhhssvv and AHSVaahhssvv (or HSB/AHSB) are similar for hue, saturation,
1344 - CMYKccmmyykk is similar for cyan, magenta, yellow, black. */
1346 NSColor * new = nil;
1347 const char *hex = NULL;
1348 enum { rgb, argb, hsv, ahsv, cmyk, gray } color_space;
1349 NSString *nsname = [NSString stringWithUTF8String: name];
1351 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1354 if ([nsname isEqualToString: @"ns_selection_color"])
1356 nsname = ns_selection_color;
1357 name = [ns_selection_color UTF8String];
1360 if (name[0] == '0' || name[0] == '1' || name[0] == '.')
1363 NSScanner *scanner = [NSScanner scannerWithString: nsname];
1365 [scanner scanFloat: &r];
1366 [scanner scanFloat: &g];
1367 [scanner scanFloat: &b];
1368 *col = [NSColor colorWithCalibratedRed: r green: g blue: b alpha: 1.0];
1373 /* FIXME: emacs seems to downcase everything before passing it here,
1374 which we can work around, except for GRAY, since gray##, where ## is
1375 decimal between 0 and 99, is also an X11 colorname. */
1376 if (name[0] == '#') /* X11 format */
1381 else if (!memcmp (name, "RGB", 3) || !memcmp (name, "rgb", 3))
1386 else if (!memcmp (name, "ARGB", 4) || !memcmp (name, "argb", 4))
1391 else if (!memcmp (name, "HSV", 3) || !memcmp (name, "hsv", 3) ||
1392 !memcmp (name, "HSB", 3) || !memcmp (name, "hsb", 3))
1397 else if (!memcmp (name, "AHSV", 4) || !memcmp (name, "ahsv", 4) ||
1398 !memcmp (name, "AHSB", 4) || !memcmp (name, "ahsb", 4))
1403 else if (!memcmp (name, "CMYK", 4) || !memcmp (name, "cmyk", 4))
1408 else if (!memcmp (name, "GRAY", 4) /*|| !memcmp (name, "gray", 4)*/)
1414 /* Direct colors (hex values) */
1417 unsigned long long color = 0;
1418 if (sscanf (hex, "%x", &color))
1420 float f1, f2, f3, f4;
1421 /* Assume it's either 1 byte or 2 per channel... */
1422 if (strlen(hex) > 8) {
1423 f1 = ((color >> 48) & 0xffff) / 65535.0;
1424 f2 = ((color >> 32) & 0xffff) / 65535.0;
1425 f3 = ((color >> 16) & 0xffff) / 65535.0;
1426 f4 = ((color ) & 0xffff) / 65535.0;
1428 f1 = ((color >> 24) & 0xff) / 255.0;
1429 f2 = ((color >> 16) & 0xff) / 255.0;
1430 f3 = ((color >> 8) & 0xff) / 255.0;
1431 f4 = ((color ) & 0xff) / 255.0;
1434 switch (color_space)
1437 *col = [NSColor colorWithCalibratedRed: f2
1443 *col = [NSColor colorWithCalibratedRed: f2
1449 *col = [NSColor colorWithCalibratedHue: f2
1455 *col = [NSColor colorWithCalibratedHue: f2
1461 *col = [NSColor colorWithCalibratedWhite: f3 alpha: f4];
1464 *col = [NSColor colorWithDeviceCyan: f1
1471 *col = [*col colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1477 /* Otherwise, color is expected to be from a list */
1479 NSEnumerator *lenum, *cenum;
1483 #ifdef NS_IMPL_GNUSTEP
1484 /* XXX: who is wrong, the requestor or the implementation? */
1485 if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1487 nsname = @"highlightColor";
1490 lenum = [[NSColorList availableColorLists] objectEnumerator];
1491 while ( (clist = [lenum nextObject]) && new == nil)
1493 cenum = [[clist allKeys] objectEnumerator];
1494 while ( (name = [cenum nextObject]) && new == nil )
1496 if ([name compare: nsname
1497 options: NSCaseInsensitiveSearch] == NSOrderedSame )
1498 new = [clist colorWithKey: name];
1504 *col = [new colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1506 NSLog (@"Failed to find color '%@'", nsname); */
1513 ns_get_color_default (const char *name, NSColor *dflt)
1514 /* --------------------------------------------------------------------------
1515 Parse a color or use a default value
1516 -------------------------------------------------------------------------- */
1520 if (ns_get_color (name, &col))
1528 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1529 /* --------------------------------------------------------------------------
1530 Convert a Lisp string object to a NS color
1531 -------------------------------------------------------------------------- */
1533 NSTRACE (ns_lisp_to_color);
1534 if (STRINGP (color))
1535 return ns_get_color (SDATA (color), col);
1536 else if (SYMBOLP (color))
1537 return ns_get_color (SDATA (SYMBOL_NAME (color)), col);
1543 ns_color_to_lisp (NSColor *col)
1544 /* --------------------------------------------------------------------------
1545 Convert a color to a lisp string with the RGB equivalent
1546 -------------------------------------------------------------------------- */
1548 float red, green, blue, alpha, gray;
1551 NSTRACE (ns_color_to_lisp);
1554 if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1556 if ((str =[[col colorNameComponent] UTF8String]))
1559 return build_string ((char *)str);
1562 [[col colorUsingColorSpaceName: NSCalibratedRGBColorSpace]
1563 getRed: &red green: &green blue: &blue alpha: &alpha];
1564 if (red ==green && red ==blue)
1566 [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1567 getWhite: &gray alpha: &alpha];
1568 snprintf (buf, sizeof (buf), "GRAY%02.2lx%02.2lx",
1569 lrint (gray * 0xff), lrint (alpha * 0xff));
1571 return build_string (buf);
1574 snprintf (buf, sizeof (buf), "ARGB%02.2lx%02.2lx%02.2lx%02.2lx",
1576 lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1579 return build_string (buf);
1584 ns_query_color(void *col, XColor *color_def, int setPixel)
1585 /* --------------------------------------------------------------------------
1586 Get ARGB values out of NSColor col and put them into color_def.
1587 If setPixel, set the pixel to a concatenated version.
1588 and set color_def pixel to the resulting index.
1589 -------------------------------------------------------------------------- */
1593 [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1594 color_def->red = r * 65535;
1595 color_def->green = g * 65535;
1596 color_def->blue = b * 65535;
1598 if (setPixel == YES)
1600 = ARGB_TO_ULONG((int)(a*255),
1601 (int)(r*255), (int)(g*255), (int)(b*255));
1606 ns_defined_color (struct frame *f, char *name, XColor *color_def, int alloc,
1608 /* --------------------------------------------------------------------------
1609 Return 1 if named color found, and set color_def rgb accordingly.
1610 If makeIndex and alloc are nonzero put the color in the color_table,
1611 and set color_def pixel to the resulting index.
1612 If makeIndex is zero, set color_def pixel to ARGB.
1613 Return 0 if not found
1614 -------------------------------------------------------------------------- */
1617 int notFound = ns_get_color (name, &temp);
1619 NSTRACE (ns_defined_color);
1624 if (makeIndex && alloc)
1625 color_def->pixel = ns_index_color(temp, f); /* [temp retain]; */
1627 ns_query_color (temp, color_def, !makeIndex);
1634 ns_get_rgb_color (struct frame *f, float r, float g, float b, float a)
1635 /* --------------------------------------------------------------------------
1636 return an autoreleased RGB color
1637 -------------------------------------------------------------------------- */
1639 /*static int c = 1; fprintf (stderr, "color request %d\n", c++); */
1640 if (r < 0.0) r = 0.0;
1641 else if (r > 1.0) r = 1.0;
1642 if (g < 0.0) g = 0.0;
1643 else if (g > 1.0) g = 1.0;
1644 if (b < 0.0) b = 0.0;
1645 else if (b > 1.0) b = 1.0;
1646 if (a < 0.0) a = 0.0;
1647 else if (a > 1.0) a = 1.0;
1648 return (unsigned long) ns_index_color(
1649 [NSColor colorWithCalibratedRed: r green: g blue: b alpha: a], f);
1654 x_set_frame_alpha (struct frame *f)
1655 /* --------------------------------------------------------------------------
1656 change the entire-frame transparency
1657 -------------------------------------------------------------------------- */
1659 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1660 EmacsView *view = FRAME_NS_VIEW (f);
1662 double alpha_min = 1.0;
1664 if (dpyinfo->x_highlight_frame == f)
1665 alpha = f->alpha[0];
1667 alpha = f->alpha[1];
1669 if (FLOATP (Vframe_alpha_lower_limit))
1670 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1671 else if (INTEGERP (Vframe_alpha_lower_limit))
1672 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1676 else if (1.0 < alpha)
1678 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1681 #ifdef NS_IMPL_COCOA
1682 [[view window] setAlphaValue: alpha];
1687 /* ==========================================================================
1691 ========================================================================== */
1695 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1696 /* --------------------------------------------------------------------------
1697 Programmatically reposition mouse pointer in pixel coordinates
1698 -------------------------------------------------------------------------- */
1700 NSTRACE (x_set_mouse_pixel_position);
1703 /* FIXME: this does not work, and what about GNUstep? */
1704 #ifdef NS_IMPL_COCOA
1705 [FRAME_NS_VIEW (f) lockFocus];
1706 PSsetmouse ((float)pix_x, (float)pix_y);
1707 [FRAME_NS_VIEW (f) unlockFocus];
1714 x_set_mouse_position (struct frame *f, int h, int v)
1715 /* --------------------------------------------------------------------------
1716 Programmatically reposition mouse pointer in character coordinates
1717 -------------------------------------------------------------------------- */
1721 pix_x = FRAME_COL_TO_PIXEL_X (f, h) + FRAME_COLUMN_WIDTH (f) / 2;
1722 pix_y = FRAME_LINE_TO_PIXEL_Y (f, v) + FRAME_LINE_HEIGHT (f) / 2;
1724 if (pix_x < 0) pix_x = 0;
1725 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
1727 if (pix_y < 0) pix_y = 0;
1728 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
1730 x_set_mouse_pixel_position (f, pix_x, pix_y);
1735 note_mouse_movement (struct frame *frame, float x, float y)
1736 /* ------------------------------------------------------------------------
1737 Called by EmacsView on mouseMovement events. Passes on
1738 to emacs mainstream code if we moved off of a rect of interest
1739 known as last_mouse_glyph.
1740 ------------------------------------------------------------------------ */
1742 // NSTRACE (note_mouse_movement);
1744 XSETFRAME (last_mouse_motion_frame, frame);
1746 /* Note, this doesn't get called for enter/leave, since we don't have a
1747 position. Those are taken care of in the corresponding NSView methods. */
1749 /* has movement gone beyond last rect we were tracking? */
1750 if (x < last_mouse_glyph.origin.x ||
1751 x >= (last_mouse_glyph.origin.x + last_mouse_glyph.size.width) ||
1752 y < last_mouse_glyph.origin.y ||
1753 y >= (last_mouse_glyph.origin.y + last_mouse_glyph.size.height))
1755 ns_update_begin(frame);
1756 frame->mouse_moved = 1;
1757 note_mouse_highlight (frame, x, y);
1758 remember_mouse_glyph (frame, x, y, &last_mouse_glyph);
1759 ns_update_end(frame);
1768 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1769 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1770 unsigned long *time)
1771 /* --------------------------------------------------------------------------
1772 External (hook): inform emacs about mouse position and hit parts.
1773 If a scrollbar is being dragged, set bar_window, part, x, y, time.
1774 x & y should be position in the scrollbar (the whole bar, not the handle)
1775 and length of scrollbar respectively
1776 -------------------------------------------------------------------------- */
1781 Lisp_Object frame, tail;
1783 struct ns_display_info *dpyinfo;
1785 NSTRACE (ns_mouse_position);
1789 fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1793 dpyinfo = FRAME_NS_DISPLAY_INFO (*fp);
1797 if (last_mouse_scroll_bar != nil && insist == 0)
1799 /* TODO: we do not use this path at the moment because drag events will
1800 go directly to the EmacsScroller. Leaving code in for now. */
1801 [last_mouse_scroll_bar getMouseMotionPart: (int *)part window: bar_window
1803 if (time) *time = last_mouse_movement_time;
1804 last_mouse_scroll_bar = nil;
1808 /* Clear the mouse-moved flag for every frame on this display. */
1809 FOR_EACH_FRAME (tail, frame)
1810 if (FRAME_NS_P (XFRAME (frame))
1811 && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1812 XFRAME (frame)->mouse_moved = 0;
1814 last_mouse_scroll_bar = nil;
1815 if (last_mouse_frame && FRAME_LIVE_P (last_mouse_frame))
1816 f = last_mouse_frame;
1818 f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame
1819 : SELECTED_FRAME ();
1821 if (f && f->output_data.ns) /* TODO: 2nd check no longer needed? */
1823 view = FRAME_NS_VIEW (*fp);
1825 position = [[view window] mouseLocationOutsideOfEventStream];
1826 position = [view convertPoint: position fromView: nil];
1827 remember_mouse_glyph (f, position.x, position.y, &last_mouse_glyph);
1828 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1830 if (bar_window) *bar_window = Qnil;
1831 if (part) *part = 0; /*scroll_bar_handle; */
1833 if (x) XSETINT (*x, lrint (position.x));
1834 if (y) XSETINT (*y, lrint (position.y));
1835 if (time) *time = last_mouse_movement_time;
1845 ns_frame_up_to_date (struct frame *f)
1846 /* --------------------------------------------------------------------------
1847 External (hook): Fix up mouse highlighting right after a full update.
1848 Some highlighting was deferred if GC was happening during
1849 note_mouse_highlight (), while other highlighting was deferred for update.
1850 -------------------------------------------------------------------------- */
1852 NSTRACE (ns_frame_up_to_date);
1856 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1857 if ((dpyinfo->mouse_face_deferred_gc||f ==dpyinfo->mouse_face_mouse_frame)
1858 /*&& dpyinfo->mouse_face_mouse_frame*/)
1862 if (dpyinfo->mouse_face_mouse_frame)
1863 note_mouse_highlight (dpyinfo->mouse_face_mouse_frame,
1864 dpyinfo->mouse_face_mouse_x,
1865 dpyinfo->mouse_face_mouse_y);
1866 dpyinfo->mouse_face_deferred_gc = 0;
1875 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1876 /* --------------------------------------------------------------------------
1877 External (RIF): set frame mouse pointer type.
1878 -------------------------------------------------------------------------- */
1880 NSTRACE (ns_define_frame_cursor);
1881 if (FRAME_POINTER_TYPE (f) != cursor)
1883 EmacsView *view = FRAME_NS_VIEW (f);
1884 FRAME_POINTER_TYPE (f) = cursor;
1885 [[view window] invalidateCursorRectsForView: view];
1891 /* ==========================================================================
1895 ========================================================================== */
1899 ns_convert_key (unsigned code)
1900 /* --------------------------------------------------------------------------
1901 Internal call used by NSView-keyDown.
1902 -------------------------------------------------------------------------- */
1904 const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym)
1905 / sizeof (convert_ns_to_X_keysym[0]));
1907 /* An array would be faster, but less easy to read. */
1908 for (keysym = 0; keysym < last_keysym; keysym += 2)
1909 if (code == convert_ns_to_X_keysym[keysym])
1910 return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
1912 /* if decide to use keyCode and Carbon table, use this line:
1913 return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
1918 x_get_keysym_name (int keysym)
1919 /* --------------------------------------------------------------------------
1920 Called by keyboard.c. Not sure if the return val is important, except
1922 -------------------------------------------------------------------------- */
1924 static char value[16];
1925 NSTRACE (x_get_keysym_name);
1926 sprintf (value, "%d", keysym);
1932 /* ==========================================================================
1934 Block drawing operations
1936 ========================================================================== */
1940 ns_redraw_scroll_bars (struct frame *f)
1944 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
1945 NSTRACE (ns_judge_scroll_bars);
1946 for (i =[subviews count]-1; i >= 0; i--)
1948 view = [subviews objectAtIndex: i];
1949 if (![view isKindOfClass: [EmacsScroller class]]) continue;
1956 ns_clear_frame (struct frame *f)
1957 /* --------------------------------------------------------------------------
1958 External (hook): Erase the entire frame
1959 -------------------------------------------------------------------------- */
1961 NSView *view = FRAME_NS_VIEW (f);
1964 NSTRACE (ns_clear_frame);
1968 /* comes on initial frame because we have
1969 after-make-frame-functions = select-frame */
1970 if (!FRAME_DEFAULT_FACE (f))
1973 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
1975 output_cursor.hpos = output_cursor.vpos = 0;
1976 output_cursor.x = -1;
1981 ns_focus (f, &r, 1);
1982 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
1986 #ifdef NS_IMPL_COCOA
1987 [[view window] display]; /* redraw resize handle */
1990 /* as of 2006/11 or so this is now needed */
1991 ns_redraw_scroll_bars (f);
1997 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
1998 /* --------------------------------------------------------------------------
1999 External (RIF): Clear section of frame
2000 -------------------------------------------------------------------------- */
2002 NSRect r = NSMakeRect (x, y, width, height);
2003 NSView *view = FRAME_NS_VIEW (f);
2004 struct face *face = FRAME_DEFAULT_FACE (f);
2009 NSTRACE (ns_clear_frame_area);
2011 r = NSIntersectionRect (r, [view frame]);
2012 ns_focus (f, &r, 1);
2013 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2015 #ifdef NS_IMPL_COCOA
2017 /* clip out the resize handle */
2018 NSWindow *window = [FRAME_NS_VIEW (f) window];
2020 = [view convertRect: ns_resize_handle_rect (window) fromView: nil];
2022 ir = NSIntersectionRect (r, ir);
2023 if (NSIsEmptyRect (ir))
2029 #ifdef NS_IMPL_COCOA
2033 NSRect r1 = r, r2 = r; /* upper and lower non-intersecting */
2034 r1.size.height -= ir.size.height;
2035 r2.origin.y += r1.size.height;
2036 r2.size.width -= ir.size.width;
2037 r2.size.height = ir.size.height;
2050 ns_scroll_run (struct window *w, struct run *run)
2051 /* --------------------------------------------------------------------------
2052 External (RIF): Insert or delete n lines at line vpos
2053 -------------------------------------------------------------------------- */
2055 struct frame *f = XFRAME (w->frame);
2056 int x, y, width, height, from_y, to_y, bottom_y;
2058 NSTRACE (ns_scroll_run);
2060 /* begin copy from other terms */
2061 /* Get frame-relative bounding box of the text display area of W,
2062 without mode lines. Include in this box the left and right
2064 window_box (w, -1, &x, &y, &width, &height);
2066 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2067 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2068 bottom_y = y + height;
2072 /* Scrolling up. Make sure we don't copy part of the mode
2073 line at the bottom. */
2074 if (from_y + run->height > bottom_y)
2075 height = bottom_y - from_y;
2077 height = run->height;
2081 /* Scolling down. Make sure we don't copy over the mode line.
2083 if (to_y + run->height > bottom_y)
2084 height = bottom_y - to_y;
2086 height = run->height;
2088 /* end copy from other terms */
2099 NSRect srcRect = NSMakeRect (x, from_y, width, height);
2100 NSRect dstRect = NSMakeRect (x, to_y, width, height);
2101 NSPoint dstOrigin = NSMakePoint (x, to_y);
2103 ns_focus (f, &dstRect, 1);
2104 NSCopyBits (0, srcRect , dstOrigin);
2113 ns_after_update_window_line (struct glyph_row *desired_row)
2114 /* --------------------------------------------------------------------------
2115 External (RIF): preparatory to fringe update after text was updated
2116 -------------------------------------------------------------------------- */
2118 struct window *w = updated_window;
2122 NSTRACE (ns_after_update_window_line);
2124 /* begin copy from other terms */
2127 if (!desired_row->mode_line_p && !w->pseudo_window_p)
2128 desired_row->redraw_fringe_bitmaps_p = 1;
2130 /* When a window has disappeared, make sure that no rest of
2131 full-width rows stays visible in the internal border.
2132 Under NS this is drawn inside the fringes. */
2133 if (windows_or_buffers_changed
2134 && (f = XFRAME (w->frame),
2135 width = FRAME_INTERNAL_BORDER_WIDTH (f),
2137 && (height = desired_row->visible_height,
2140 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2142 /* Internal border is drawn below the tool bar. */
2143 if (WINDOWP (f->tool_bar_window)
2144 && w == XWINDOW (f->tool_bar_window))
2146 /* end copy from other terms */
2149 if (!desired_row->full_width_p)
2151 int x1 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2152 + WINDOW_LEFT_FRINGE_WIDTH (w);
2153 int x2 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2154 + FRAME_PIXEL_WIDTH (f) - NS_SCROLL_BAR_WIDTH (f)
2155 - WINDOW_RIGHT_FRINGE_WIDTH (w)
2156 - FRAME_INTERNAL_BORDER_WIDTH (f);
2157 ns_clear_frame_area (f, x1, y, width, height);
2158 ns_clear_frame_area (f, x2, y, width, height);
2166 ns_shift_glyphs_for_insert (struct frame *f,
2167 int x, int y, int width, int height,
2169 /* --------------------------------------------------------------------------
2170 External (RIF): copy an area horizontally, don't worry about clearing src
2171 -------------------------------------------------------------------------- */
2173 NSRect srcRect = NSMakeRect (x, y, width, height);
2174 NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2175 NSPoint dstOrigin = dstRect.origin;
2177 NSTRACE (ns_shift_glyphs_for_insert);
2179 ns_focus (f, &dstRect, 1);
2180 NSCopyBits (0, srcRect, dstOrigin);
2186 /* ==========================================================================
2188 Character encoding and metrics
2190 ========================================================================== */
2194 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2195 /* --------------------------------------------------------------------------
2196 External (RIF); compute left/right overhang of whole string and set in s
2197 -------------------------------------------------------------------------- */
2199 struct face *face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2200 struct font *font = s->font; /*face->font; */
2204 struct font_metrics metrics;
2205 unsigned int codes[2];
2206 codes[0] = *(s->char2b);
2207 codes[1] = *(s->char2b + s->nchars - 1);
2209 font->driver->text_extents (font, codes, 2, &metrics);
2210 s->left_overhang = -metrics.lbearing;
2212 = metrics.rbearing > metrics.width
2213 ? metrics.rbearing - metrics.width : 0;
2217 s->left_overhang = 0;
2218 s->right_overhang = ((struct nsfont_info *)font)->ital ?
2219 FONT_HEIGHT (font) * 0.2 : 0;
2225 /* ==========================================================================
2227 Fringe and cursor drawing
2229 ========================================================================== */
2232 extern int max_used_fringe_bitmap;
2234 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2235 struct draw_fringe_bitmap_params *p)
2236 /* --------------------------------------------------------------------------
2237 External (RIF); fringe-related
2238 -------------------------------------------------------------------------- */
2240 struct frame *f = XFRAME (WINDOW_FRAME (w));
2241 struct face *face = p->face;
2243 static EmacsImage **bimgs = NULL;
2244 static int nBimgs = 0;
2245 /* NS-specific: move internal border inside fringe */
2246 int x = p->bx < 0 ? p->x : p->bx;
2247 int wd = p->bx < 0 ? p->wd : p->nx;
2248 BOOL fringeOnVeryLeft
2249 = x - WINDOW_LEFT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w)
2250 - FRAME_INTERNAL_BORDER_WIDTH (f) < 10;
2251 BOOL fringeOnVeryRight
2252 = FRAME_PIXEL_WIDTH (f) - x - wd - FRAME_INTERNAL_BORDER_WIDTH (f)
2253 - WINDOW_RIGHT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w) < 10;
2254 int xAdjust = FRAME_INTERNAL_BORDER_WIDTH (f) *
2255 (fringeOnVeryLeft ? -1 : (fringeOnVeryRight ? 1 : 0));
2257 /* grow bimgs if needed */
2258 if (nBimgs < max_used_fringe_bitmap)
2260 EmacsImage **newBimgs
2261 = xmalloc (max_used_fringe_bitmap * sizeof (EmacsImage *));
2262 bzero (newBimgs, max_used_fringe_bitmap * sizeof (EmacsImage *));
2266 bcopy (bimgs, newBimgs, nBimgs * sizeof (EmacsImage *));
2271 nBimgs = max_used_fringe_bitmap;
2274 /* Must clip because of partially visible lines. */
2275 rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
2278 /* Adjust position of "bottom aligned" bitmap on partially
2279 visible last row. */
2281 int oldVH = row->visible_height;
2282 row->visible_height = p->h;
2283 row->y -= rowY - p->y;
2284 ns_clip_to_row (w, row, -1, NO);
2286 row->visible_height = oldVH;
2289 ns_clip_to_row (w, row, -1, YES);
2291 if (p->bx >= 0 && !p->overlay_p)
2293 int yAdjust = rowY - FRAME_INTERNAL_BORDER_WIDTH (f) < 5 ?
2294 -FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2295 int yIncr = FRAME_PIXEL_HEIGHT (f) - (p->by+yAdjust + p->ny) < 5 ?
2296 FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2298 yIncr += FRAME_INTERNAL_BORDER_WIDTH (f);
2299 NSRect r = NSMakeRect (p->bx+xAdjust, p->by+yAdjust, p->nx, p->ny+yIncr);
2301 [ns_lookup_indexed_color(face->background, f) set];
2307 NSRect r = NSMakeRect (p->x+xAdjust, p->y, p->wd, p->h);
2308 NSPoint pt = r.origin;
2309 EmacsImage *img = bimgs[p->which - 1];
2313 unsigned short *bits = p->bits + p->dh;
2314 int len = 8 * p->h/8;
2316 unsigned char *cbits = xmalloc (len);
2318 for (i =0; i<len; i++)
2319 cbits[i] = ~(bits[i] & 0xff);
2320 img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2322 bimgs[p->which - 1] = img;
2327 /* Since we composite the bitmap instead of just blitting it, we need
2328 to erase the whole background. */
2329 [ns_lookup_indexed_color(face->background, f) set];
2332 [img setXBMColor: ns_lookup_indexed_color(face->foreground, f)];
2333 [img compositeToPoint: pt operation: NSCompositeSourceOver];
2340 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2341 int x, int y, int cursor_type, int cursor_width,
2342 int on_p, int active_p)
2343 /* --------------------------------------------------------------------------
2344 External call (RIF): draw cursor
2345 (modeled after x_draw_window_cursor
2346 FIXME: cursor_width is effectively bogus -- it sometimes gets set
2347 in xdisp.c set_frame_cursor_types, sometimes left uninitialized;
2348 DON'T USE IT (no other terms do)
2349 -------------------------------------------------------------------------- */
2353 struct frame *f = WINDOW_XFRAME (w);
2354 struct glyph *phys_cursor_glyph;
2355 int overspill, cursorToDraw;
2357 NSTRACE (dumpcursor);
2358 //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);
2363 w->phys_cursor_type = cursor_type;
2364 w->phys_cursor_on_p = on_p;
2366 if (cursor_type == NO_CURSOR)
2368 w->phys_cursor_width = 0;
2372 if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2374 if (glyph_row->exact_window_width_line_p
2375 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2377 glyph_row->cursor_in_fringe_p = 1;
2378 draw_fringe_bitmap (w, glyph_row, 0);
2383 get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2385 r.origin.x = fx, r.origin.y = fy;
2387 r.size.width = w->phys_cursor_width;
2389 /* FIXME: if we overwrite the internal border area, it does not get erased;
2390 fix by truncating cursor, but better would be to erase properly */
2391 overspill = r.origin.x + r.size.width -
2392 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, WINDOW_BOX_RIGHT_EDGE_X (w)
2393 - WINDOW_TOTAL_FRINGE_WIDTH (w) - FRAME_INTERNAL_BORDER_WIDTH (f));
2395 r.size.width -= overspill;
2397 /* TODO: only needed in rare cases with last-resort font in HELLO..
2398 should we do this more efficiently? */
2399 ns_clip_to_row (w, glyph_row, -1, NO); /* do ns_focus(f, &r, 1); if remove */
2400 [FRAME_CURSOR_COLOR (f) set];
2402 #ifdef NS_IMPL_COCOA
2403 /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2404 atomic. Cleaner ways of doing this should be investigated.
2405 One way would be to set a global variable DRAWING_CURSOR
2406 when making the call to draw_phys..(), don't focus in that
2407 case, then move the ns_unfocus() here after that call. */
2408 NSDisableScreenUpdates ();
2411 cursorToDraw = active_p ? cursor_type : HOLLOW_BOX_CURSOR;
2412 switch (cursorToDraw)
2416 case FILLED_BOX_CURSOR:
2419 case HOLLOW_BOX_CURSOR:
2421 [FRAME_BACKGROUND_COLOR (f) set];
2422 NSRectFill (NSInsetRect (r, 1, 1));
2423 [FRAME_CURSOR_COLOR (f) set];
2427 s.origin.y += lrint (0.75 * s.size.height);
2428 s.size.height = lrint (s.size.height * 0.25);
2433 s.size.width = min (cursor_width, 2); //FIXME(see above)
2439 /* draw the character under the cursor */
2440 if (cursorToDraw != NO_CURSOR)
2441 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2443 #ifdef NS_IMPL_COCOA
2444 NSEnableScreenUpdates ();
2451 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2452 /* --------------------------------------------------------------------------
2453 External (RIF): Draw a vertical line.
2454 -------------------------------------------------------------------------- */
2456 struct frame *f = XFRAME (WINDOW_FRAME (w));
2458 NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2460 NSTRACE (ns_draw_vertical_window_border);
2462 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2464 [ns_lookup_indexed_color(face->foreground, f) set];
2466 ns_focus (f, &r, 1);
2473 show_hourglass (struct atimer *timer)
2475 if (hourglass_shown_p)
2480 /* TODO: add NSProgressIndicator to selected frame (see macfns.c) */
2482 hourglass_shown_p = 1;
2490 if (!hourglass_shown_p)
2495 /* TODO: remove NSProgressIndicator from all frames */
2497 hourglass_shown_p = 0;
2503 /* ==========================================================================
2505 Glyph drawing operations
2507 ========================================================================== */
2510 static inline NSRect
2511 ns_fix_rect_ibw (NSRect r, int fibw, int frame_pixel_width)
2512 /* --------------------------------------------------------------------------
2513 Under NS we draw internal borders inside fringes, and want full-width
2514 rendering to go all the way to edge. This function makes that correction.
2515 -------------------------------------------------------------------------- */
2517 if (r.origin.y <= fibw+1)
2519 r.size.height += r.origin.y;
2522 if (r.origin.x <= fibw+1)
2524 r.size.width += r.origin.x;
2527 if (frame_pixel_width - (r.origin.x+r.size.width) <= fibw+1)
2528 r.size.width += fibw;
2535 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2536 /* --------------------------------------------------------------------------
2537 Wrapper utility to account for internal border width on full-width lines,
2538 and allow top full-width rows to hit the frame top. nr should be pointer
2539 to two successive NSRects. Number of rects actually used is returned.
2540 -------------------------------------------------------------------------- */
2542 int n = get_glyph_string_clip_rects (s, nr, 2);
2543 if (s->row->full_width_p)
2545 *nr = ns_fix_rect_ibw (*nr, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2546 FRAME_PIXEL_WIDTH (s->f));
2548 *nr = ns_fix_rect_ibw (*(nr+1), FRAME_INTERNAL_BORDER_WIDTH (s->f),
2549 FRAME_PIXEL_WIDTH (s->f));
2556 ns_draw_box (NSRect r, float thickness, NSColor *col, char left_p, char right_p)
2557 /* --------------------------------------------------------------------------
2558 Draw an unfilled rect inside r, optionally leaving left and/or right open.
2559 Note we can't just use an NSDrawRect command, because of the possibility
2560 of some sides not being drawn, and because the rect will be filled.
2561 -------------------------------------------------------------------------- */
2567 s.size.height = thickness;
2569 s.origin.y += r.size.height - thickness;
2572 s.size.height = r.size.height;
2573 s.origin.y = r.origin.y;
2575 /* left, right (optional) */
2576 s.size.width = thickness;
2581 s.origin.x += r.size.width - thickness;
2588 ns_draw_relief (NSRect r, int thickness, char raised_p,
2589 char top_p, char bottom_p, char left_p, char right_p,
2590 struct glyph_string *s)
2591 /* --------------------------------------------------------------------------
2592 Draw a relief rect inside r, optionally leaving some sides open.
2593 Note we can't just use an NSDrawBezel command, because of the possibility
2594 of some sides not being drawn, and because the rect will be filled.
2595 -------------------------------------------------------------------------- */
2597 static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2598 NSColor *newBaseCol = nil;
2601 NSTRACE (ns_draw_relief);
2605 if (s->face->use_box_color_for_shadows_p)
2607 newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2609 /* else if (s->first_glyph->type == IMAGE_GLYPH
2611 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2613 newBaseCol = IMAGE_BACKGROUND (s->img, s->f, 0);
2617 newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2620 if (newBaseCol == nil)
2621 newBaseCol = [NSColor grayColor];
2623 if (newBaseCol != baseCol) /* TODO: better check */
2626 baseCol = [newBaseCol retain];
2628 lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2630 darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2633 [(raised_p ? lightCol : darkCol) set];
2635 /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2638 sr.size.height = thickness;
2639 if (top_p) NSRectFill (sr);
2642 sr.size.height = r.size.height;
2643 sr.size.width = thickness;
2644 if (left_p) NSRectFill (sr);
2646 [(raised_p ? darkCol : lightCol) set];
2649 sr.size.width = r.size.width;
2650 sr.size.height = thickness;
2651 sr.origin.y += r.size.height - thickness;
2652 if (bottom_p) NSRectFill (sr);
2655 sr.size.height = r.size.height;
2656 sr.origin.y = r.origin.y;
2657 sr.size.width = thickness;
2658 sr.origin.x += r.size.width - thickness;
2659 if (right_p) NSRectFill (sr);
2664 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2665 /* --------------------------------------------------------------------------
2666 Function modeled after x_draw_glyph_string_box ().
2667 Sets up parameters for drawing.
2668 -------------------------------------------------------------------------- */
2670 int right_x, last_x;
2671 char left_p, right_p;
2672 struct glyph *last_glyph;
2677 if (s->hl == DRAW_MOUSE_FACE)
2680 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2682 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2687 thickness = face->box_line_width;
2689 NSTRACE (ns_dumpglyphs_box_or_relief);
2691 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2692 ? WINDOW_RIGHT_EDGE_X (s->w)
2693 : window_box_right (s->w, s->area));
2694 last_glyph = (s->cmp || s->img
2695 ? s->first_glyph : s->first_glyph + s->nchars-1);
2697 right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2698 ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2700 left_p = (s->first_glyph->left_box_line_p
2701 || (s->hl == DRAW_MOUSE_FACE
2702 && (s->prev == NULL || s->prev->hl != s->hl)));
2703 right_p = (last_glyph->right_box_line_p
2704 || (s->hl == DRAW_MOUSE_FACE
2705 && (s->next == NULL || s->next->hl != s->hl)));
2707 r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2709 /* expand full-width row over internal borders */
2710 if (s->row->full_width_p)
2711 r = ns_fix_rect_ibw (r, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2712 FRAME_PIXEL_WIDTH (s->f));
2714 if (s->face->box == FACE_SIMPLE_BOX)
2716 xassert (s->face->box_color != nil);
2717 ns_draw_box (r, abs (thickness),
2718 ns_lookup_indexed_color (face->box_color, s->f),
2723 ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2724 1, 1, left_p, right_p, s);
2730 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2731 /* --------------------------------------------------------------------------
2732 Modeled after x_draw_glyph_string_background, which draws BG in
2733 certain cases. Others are left to the text rendering routine.
2734 -------------------------------------------------------------------------- */
2736 NSTRACE (ns_maybe_dumpglyphs_background);
2738 if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2740 int box_line_width = max (s->face->box_line_width, 0);
2741 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2742 || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2745 if (s->hl == DRAW_MOUSE_FACE)
2748 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2750 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2753 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2755 [(NS_FACE_BACKGROUND (face) != 0
2756 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2757 : FRAME_BACKGROUND_COLOR (s->f)) set];
2760 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (s->f);
2761 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2764 if (s->hl != DRAW_CURSOR)
2766 NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2767 s->background_width,
2768 s->height-2*box_line_width);
2770 /* expand full-width row over internal borders */
2771 if (s->row->full_width_p)
2773 int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2774 if (r.origin.y <= fibw+1 + box_line_width)
2776 r.size.height += r.origin.y;
2779 if (r.origin.x <= fibw+1)
2781 r.size.width += 2*r.origin.x;
2784 if (FRAME_PIXEL_WIDTH (s->f) - (r.origin.x + r.size.width)
2786 r.size.width += fibw;
2792 s->background_filled_p = 1;
2799 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2800 /* --------------------------------------------------------------------------
2801 Renders an image and associated borders.
2802 -------------------------------------------------------------------------- */
2804 EmacsImage *img = s->img->pixmap;
2805 int box_line_vwidth = max (s->face->box_line_width, 0);
2806 int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2807 int bg_x, bg_y, bg_height;
2813 NSTRACE (ns_dumpglyphs_image);
2815 if (s->face->box != FACE_NO_BOX
2816 && s->first_glyph->left_box_line_p && s->slice.x == 0)
2817 x += abs (s->face->box_line_width);
2820 bg_y = s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2821 bg_height = s->height;
2822 /* other terms have this, but was causing problems w/tabbar mode */
2823 /* - 2 * box_line_vwidth; */
2825 if (s->slice.x == 0) x += s->img->hmargin;
2826 if (s->slice.y == 0) y += s->img->vmargin;
2828 /* Draw BG: if we need larger area than image itself cleared, do that,
2829 otherwise, since we composite the image under NS (instead of mucking
2830 with its background color), we must clear just the image area. */
2831 if (s->hl == DRAW_MOUSE_FACE)
2834 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2836 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2839 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2841 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
2843 if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
2844 || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
2846 br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
2847 s->background_filled_p = 1;
2851 br = NSMakeRect (x, y, s->slice.width, s->slice.height);
2854 /* expand full-width row over internal borders */
2855 if (s->row->full_width_p)
2857 int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2858 if (br.origin.y <= fibw+1 + box_line_vwidth)
2860 br.size.height += br.origin.y;
2863 if (br.origin.x <= fibw+1 + box_line_vwidth)
2865 br.size.width += br.origin.x;
2868 if (FRAME_PIXEL_WIDTH (s->f) - (br.origin.x + br.size.width) <= fibw+1)
2869 br.size.width += fibw;
2874 /* Draw the image.. do we need to draw placeholder if img ==nil? */
2876 [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
2877 operation: NSCompositeSourceOver];
2879 /* Draw relief, if requested */
2880 if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
2882 if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
2884 th = tool_bar_button_relief >= 0 ?
2885 tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2886 raised_p = (s->hl == DRAW_IMAGE_RAISED);
2890 th = abs (s->img->relief);
2891 raised_p = (s->img->relief > 0);
2894 r.origin.x = x - th;
2895 r.origin.y = y - th;
2896 r.size.width = s->slice.width + 2*th-1;
2897 r.size.height = s->slice.height + 2*th-1;
2898 ns_draw_relief (r, th, raised_p,
2900 s->slice.y + s->slice.height == s->img->height,
2902 s->slice.x + s->slice.width == s->img->width, s);
2908 ns_dumpglyphs_stretch (struct glyph_string *s)
2914 if (!s->background_filled_p)
2916 n = ns_get_glyph_string_clip_rect (s, r);
2917 *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
2921 if (!s->row->full_width_p)
2923 /* truncate to avoid overwriting fringe and/or scrollbar */
2924 int overrun = max (0, (s->x + s->background_width)
2925 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
2926 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
2927 r[i].size.width -= overrun;
2929 /* XXX: Try to work between problem where a stretch glyph on
2930 a partially-visible bottom row will clear part of the
2931 modeline, and another where list-buffers headers and similar
2932 rows erroneously have visible_height set to 0. Not sure
2933 where this is coming from as other terms seem not to show. */
2934 r[i].size.height = min (s->height, s->row->visible_height);
2937 /* expand full-width rows over internal borders */
2940 r[i] = ns_fix_rect_ibw (r[i], FRAME_INTERNAL_BORDER_WIDTH (s->f),
2941 FRAME_PIXEL_WIDTH (s->f));
2944 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
2945 overwriting cursor (usually when cursor on a tab) */
2946 if (s->hl == DRAW_CURSOR)
2948 r[i].origin.x += s->width;
2949 r[i].size.width -= s->width;
2953 ns_focus (s->f, r, n);
2955 if (s->hl == DRAW_MOUSE_FACE)
2958 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2960 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2963 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2965 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
2970 s->background_filled_p = 1;
2976 ns_draw_glyph_string (struct glyph_string *s)
2977 /* --------------------------------------------------------------------------
2978 External (RIF): Main draw-text call.
2979 -------------------------------------------------------------------------- */
2981 /* TODO (optimize): focus for box and contents draw */
2984 char box_drawn_p = 0;
2986 NSTRACE (ns_draw_glyph_string);
2988 if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
2991 struct glyph_string *next;
2993 for (width = 0, next = s->next;
2994 next && width < s->right_overhang;
2995 width += next->width, next = next->next)
2996 if (next->first_glyph->type != IMAGE_GLYPH)
2998 if (next->first_glyph->type != STRETCH_GLYPH)
3000 n = ns_get_glyph_string_clip_rect (s->next, r);
3001 ns_focus (s->f, r, n);
3002 ns_maybe_dumpglyphs_background (s->next, 1);
3007 ns_dumpglyphs_stretch (s->next);
3009 next->num_clips = 0;
3013 if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3014 && (s->first_glyph->type == CHAR_GLYPH
3015 || s->first_glyph->type == COMPOSITE_GLYPH))
3017 n = ns_get_glyph_string_clip_rect (s, r);
3018 ns_focus (s->f, r, n);
3019 ns_maybe_dumpglyphs_background (s, 1);
3020 ns_dumpglyphs_box_or_relief (s);
3025 switch (s->first_glyph->type)
3029 n = ns_get_glyph_string_clip_rect (s, r);
3030 ns_focus (s->f, r, n);
3031 ns_dumpglyphs_image (s, r[0]);
3036 ns_dumpglyphs_stretch (s);
3040 case COMPOSITE_GLYPH:
3041 n = ns_get_glyph_string_clip_rect (s, r);
3042 ns_focus (s->f, r, n);
3044 if (s->for_overlaps || (s->cmp_from > 0
3045 && ! s->first_glyph->u.cmp.automatic))
3046 s->background_filled_p = 1;
3048 ns_maybe_dumpglyphs_background
3049 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3051 ns_tmp_flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3052 (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3053 (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3054 NS_DUMPGLYPH_NORMAL));
3055 ns_tmp_font = (struct nsfont_info *)s->face->font;
3056 if (ns_tmp_font == NULL)
3057 ns_tmp_font = (struct nsfont_info *)FRAME_FONT (s->f);
3059 ns_tmp_font->font.driver->draw
3060 (s, 0, s->nchars, s->x, s->y,
3061 (ns_tmp_flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3062 || ns_tmp_flags == NS_DUMPGLYPH_MOUSEFACE);
3071 /* Draw box if not done already. */
3072 if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3074 n = ns_get_glyph_string_clip_rect (s, r);
3075 ns_focus (s->f, r, n);
3076 ns_dumpglyphs_box_or_relief (s);
3085 /* ==========================================================================
3089 ========================================================================== */
3093 ns_send_appdefined (int value)
3094 /* --------------------------------------------------------------------------
3095 Internal: post an appdefined event which EmacsApp-sendEvent will
3096 recognize and take as a command to halt the event loop.
3097 -------------------------------------------------------------------------- */
3099 /*NSTRACE (ns_send_appdefined); */
3101 /* Only post this event if we haven't already posted one. This will end
3102 the [NXApp run] main loop after having processed all events queued at
3104 if (send_appdefined)
3108 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
3109 send_appdefined = NO;
3111 /* Don't need wakeup timer any more */
3114 [timed_entry invalidate];
3115 [timed_entry release];
3119 /* Ditto for file descriptor poller */
3122 [fd_entry invalidate];
3127 nxev = [NSEvent otherEventWithType: NSApplicationDefined
3128 location: NSMakePoint (0, 0)
3131 windowNumber: [[NSApp mainWindow] windowNumber]
3132 context: [NSApp context]
3137 /* Post an application defined event on the event queue. When this is
3138 received the [NXApp run] will return, thus having processed all
3139 events which are currently queued. */
3140 [NSApp postEvent: nxev atStart: NO];
3146 ns_read_socket (struct terminal *terminal, int expected,
3147 struct input_event *hold_quit)
3148 /* --------------------------------------------------------------------------
3149 External (hook): Post an event to ourself and keep reading events until
3150 we read it back again. In effect process all events which were waiting.
3151 From 21+ we have to manage the event buffer ourselves.
3152 -------------------------------------------------------------------------- */
3154 struct input_event ev;
3157 /* NSTRACE (ns_read_socket); */
3159 if (interrupt_input_blocked)
3161 interrupt_input_pending = 1;
3163 pending_signals = 1;
3168 interrupt_input_pending = 0;
3170 pending_signals = pending_atimers;
3174 n_emacs_events_pending = 0;
3177 q_event_ptr = hold_quit;
3179 /* we manage autorelease pools by allocate/reallocate each time around
3180 the loop; strict nesting is occasionally violated but seems not to
3181 matter.. earlier methods using full nesting caused major memory leaks */
3182 [outerpool release];
3183 outerpool = [[NSAutoreleasePool alloc] init];
3185 /* If have pending open-file requests, attend to the next one of those. */
3186 if (ns_pending_files && [ns_pending_files count] != 0
3187 && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3189 [ns_pending_files removeObjectAtIndex: 0];
3191 /* Deal with pending service requests. */
3192 else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3194 NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3195 withArg: [ns_pending_service_args objectAtIndex: 0]])
3197 [ns_pending_service_names removeObjectAtIndex: 0];
3198 [ns_pending_service_args removeObjectAtIndex: 0];
3202 /* Run and wait for events. We must always send one NX_APPDEFINED event
3203 to ourself, otherwise [NXApp run] will never exit. */
3204 send_appdefined = YES;
3206 /* If called via ns_select, this is called once with expected=1,
3207 because we expect either the timeout or file descriptor activity.
3208 In this case the first event through will either be real input or
3209 one of these. read_avail_input() then calls once more with expected=0
3210 and in that case we need to return quickly if there is nothing.
3211 If we're being called outside of that, it's also OK to return quickly
3212 after one iteration through the event loop, since other terms do
3213 this and emacs expects it. */
3214 if (!(inNsSelect && expected)) // (!inNsSelect || !expected)
3216 /* Post an application defined event on the event queue. When this is
3217 received the [NXApp run] will return, thus having processed all
3218 events which are currently queued, if any. */
3219 ns_send_appdefined (-1);
3225 nevents = n_emacs_events_pending;
3226 n_emacs_events_pending = 0;
3227 emacs_event = q_event_ptr = NULL;
3235 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3236 fd_set *exceptfds, struct timeval *timeout)
3237 /* --------------------------------------------------------------------------
3238 Replacement for select, checking for events
3239 -------------------------------------------------------------------------- */
3244 /* NSTRACE (ns_select); */
3246 if (NSApp == nil || inNsSelect == 1 /* || ([NSApp isActive] == NO &&
3247 [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
3248 inMode:NSDefaultRunLoopMode dequeue:NO] == nil) */)
3249 return select (nfds, readfds, writefds, exceptfds, timeout);
3251 /* Save file descriptor set, which gets overwritten in calls to select ()
3252 Note, this is called from process.c, and only readfds is ever set */
3255 memcpy (&select_readfds, readfds, sizeof (fd_set));
3261 /* Try an initial select for pending data on input files */
3262 select_timeout.tv_sec = select_timeout.tv_usec = 0;
3263 result = select (nfds, readfds, writefds, exceptfds, &select_timeout);
3267 /* if (!timeout || timed_entry || fd_entry)
3268 fprintf (stderr, "assertion failed: timeout null or timed_entry/fd_entry non-null in ns_select\n"); */
3270 /* set a timeout and run the main AppKit event loop while continuing
3271 to monitor the files */
3272 time = ((double) timeout->tv_sec) + ((double) timeout->tv_usec)/1000000.0;
3273 timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3275 selector: @selector (timeout_handler:)
3277 repeats: YES] /* for safe removal */
3280 /* set a periodic task to try the select () again */
3281 fd_entry = [[NSTimer scheduledTimerWithTimeInterval: 0.1
3283 selector: @selector (fd_handler:)
3288 /* Let Application dispatch events until it receives an event of the type
3289 NX_APPDEFINED, which should only be sent by timeout_handler.
3290 We tell read_avail_input() that input is "expected" because we do expect
3291 either the timeout or fd handler to fire, and if they don't, the original
3292 call from process.c that got us here expects us to wait until some input
3296 ev = last_appdefined_event;
3302 if ([ev type] != NSApplicationDefined)
3306 last_appdefined_event = 0;
3310 /* The NX_APPDEFINED event we received was a timeout. */
3315 /* The NX_APPDEFINED event we received was the result of
3316 at least one real input event arriving. */
3322 /* Received back from select () in fd_handler; copy the results */
3324 memcpy (readfds, &select_readfds, sizeof (fd_set));
3328 /* never reached, shut compiler up */
3334 /* ==========================================================================
3338 ========================================================================== */
3342 ns_set_vertical_scroll_bar (struct window *window,
3343 int portion, int whole, int position)
3344 /* --------------------------------------------------------------------------
3345 External (hook): Update or add scrollbar
3346 -------------------------------------------------------------------------- */
3350 struct frame *f = XFRAME (WINDOW_FRAME (window));
3351 EmacsView *view = FRAME_NS_VIEW (f);
3352 int window_y, window_height;
3353 BOOL barOnVeryLeft, barOnVeryRight;
3354 int top, left, height, width, sb_width, sb_left;
3356 static int count = 0;
3358 /* optimization; display engine sends WAY too many of these.. */
3359 if (!NILP (window->vertical_scroll_bar))
3361 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3362 if ([bar checkSamePosition: position portion: portion whole: whole])
3364 if (view->scrollbarsNeedingUpdate == 0)
3366 if (!windows_or_buffers_changed)
3370 view->scrollbarsNeedingUpdate--;
3374 NSTRACE (ns_set_vertical_scroll_bar);
3376 /* Get dimensions. */
3377 window_box (window, -1, 0, &window_y, 0, &window_height);
3379 height = window_height;
3380 width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3381 left = WINDOW_SCROLL_BAR_AREA_X (window);
3383 if (top < 5) /* top scrollbar adjustment */
3385 top -= FRAME_INTERNAL_BORDER_WIDTH (f);
3386 height += FRAME_INTERNAL_BORDER_WIDTH (f);
3389 /* allow for displaying a skinnier scrollbar than char area allotted */
3390 sb_width = (WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) > 0) ?
3391 WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) : width;
3393 barOnVeryLeft = left < 5;
3394 barOnVeryRight = FRAME_PIXEL_WIDTH (f) - left - width < 5;
3395 sb_left = left + FRAME_INTERNAL_BORDER_WIDTH (f)
3396 * (barOnVeryLeft ? -1 : (barOnVeryRight ? 1 : 0));
3398 r = NSMakeRect (sb_left, top, sb_width, height);
3399 /* the parent view is flipped, so we need to flip y value */
3401 r.origin.y = (v.size.height - r.size.height - r.origin.y);
3403 XSETWINDOW (win, window);
3406 /* we want at least 5 lines to display a scrollbar */
3407 if (WINDOW_TOTAL_LINES (window) < 5)
3409 if (!NILP (window->vertical_scroll_bar))
3411 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3412 [bar removeFromSuperview];
3413 window->vertical_scroll_bar = Qnil;
3415 ns_clear_frame_area (f, sb_left, top, width, height);
3420 if (NILP (window->vertical_scroll_bar))
3422 ns_clear_frame_area (f, sb_left, top, width, height);
3423 bar = [[EmacsScroller alloc] initFrame: r window: win];
3424 window->vertical_scroll_bar = make_save_value (bar, 0);
3429 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3430 oldRect = [bar frame];
3431 r.size.width = oldRect.size.width;
3432 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3434 if (oldRect.origin.x != r.origin.x)
3435 ns_clear_frame_area (f, sb_left, top, width, height);
3440 [bar setPosition: position portion: portion whole: whole];
3446 ns_condemn_scroll_bars (struct frame *f)
3447 /* --------------------------------------------------------------------------
3448 External (hook): arrange for all frame's scrollbars to be removed
3449 at next call to judge_scroll_bars, except for those redeemed.
3450 -------------------------------------------------------------------------- */
3454 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3456 NSTRACE (ns_condemn_scroll_bars);
3458 for (i =[subviews count]-1; i >= 0; i--)
3460 view = [subviews objectAtIndex: i];
3461 if ([view isKindOfClass: [EmacsScroller class]])
3468 ns_redeem_scroll_bar (struct window *window)
3469 /* --------------------------------------------------------------------------
3470 External (hook): arrange to spare this window's scrollbar
3471 at next call to judge_scroll_bars.
3472 -------------------------------------------------------------------------- */
3475 NSTRACE (ns_redeem_scroll_bar);
3476 if (!NILP (window->vertical_scroll_bar))
3478 bar =XNS_SCROLL_BAR (window->vertical_scroll_bar);
3485 ns_judge_scroll_bars (struct frame *f)
3486 /* --------------------------------------------------------------------------
3487 External (hook): destroy all scrollbars on frame that weren't
3488 redeemed after call to condemn_scroll_bars.
3489 -------------------------------------------------------------------------- */
3493 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3494 NSTRACE (ns_judge_scroll_bars);
3495 for (i =[subviews count]-1; i >= 0; i--)
3497 view = [subviews objectAtIndex: i];
3498 if (![view isKindOfClass: [EmacsScroller class]]) continue;
3505 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
3507 /* XXX irrelevant under NS */
3512 /* ==========================================================================
3516 ========================================================================== */
3519 x_display_pixel_height (dpyinfo)
3520 struct ns_display_info *dpyinfo;
3522 NSScreen *screen = [NSScreen mainScreen];
3523 return [screen frame].size.height;
3527 x_display_pixel_width (dpyinfo)
3528 struct ns_display_info *dpyinfo;
3530 NSScreen *screen = [NSScreen mainScreen];
3531 return [screen frame].size.width;
3535 static Lisp_Object ns_string_to_lispmod (const char *s)
3536 /* --------------------------------------------------------------------------
3537 Convert modifier name to lisp symbol
3538 -------------------------------------------------------------------------- */
3540 if (!strncmp (SDATA (SYMBOL_NAME (Qmeta)), s, 10))
3542 else if (!strncmp (SDATA (SYMBOL_NAME (Qsuper)), s, 10))
3544 else if (!strncmp (SDATA (SYMBOL_NAME (Qcontrol)), s, 10))
3546 else if (!strncmp (SDATA (SYMBOL_NAME (Qalt)), s, 10))
3548 else if (!strncmp (SDATA (SYMBOL_NAME (Qhyper)), s, 10))
3550 else if (!strncmp (SDATA (SYMBOL_NAME (Qnone)), s, 10))
3557 static Lisp_Object ns_mod_to_lisp (int m)
3558 /* --------------------------------------------------------------------------
3559 Convert modifier code (see lisp.h) to lisp symbol
3560 -------------------------------------------------------------------------- */
3564 else if (m == CHAR_SUPER)
3566 else if (m == CHAR_CTL)
3568 else if (m == CHAR_ALT)
3570 else if (m == CHAR_HYPER)
3572 else /* if (m == 0) */
3578 ns_set_default_prefs ()
3579 /* --------------------------------------------------------------------------
3580 Initialize preference variables to defaults
3581 -------------------------------------------------------------------------- */
3583 ns_alternate_modifier = Qmeta;
3584 ns_command_modifier = Qsuper;
3585 ns_control_modifier = Qcontrol;
3586 ns_function_modifier = Qnone;
3587 ns_antialias_text = Qt;
3588 ns_antialias_threshold = 10.0; /* not exposed to lisp side */
3589 ns_use_qd_smoothing = Qnil;
3590 ns_use_system_highlight_color = Qt;
3591 ns_confirm_quit = Qnil;
3596 ns_default (const char *parameter, Lisp_Object *result,
3597 Lisp_Object yesval, Lisp_Object noval,
3598 BOOL is_float, BOOL is_modstring)
3599 /* --------------------------------------------------------------------------
3600 Check a parameter value in user's preferences
3601 -------------------------------------------------------------------------- */
3605 if ( (value =[[[NSUserDefaults standardUserDefaults]
3606 stringForKey: [NSString stringWithUTF8String: parameter]]
3611 if (strcasecmp (value, "YES") == 0)
3613 else if (strcasecmp (value, "NO") == 0)
3615 else if (is_float && (f = strtod (value, &pos), pos != value))
3616 *result = make_float (f);
3617 else if (is_modstring && value)
3618 *result = ns_string_to_lispmod (value);
3619 else fprintf (stderr,
3620 "Bad value for default \"%s\": \"%s\"\n", parameter, value);
3626 ns_initialize_display_info (struct ns_display_info *dpyinfo)
3627 /* --------------------------------------------------------------------------
3628 Initialize global info and storage for display.
3629 -------------------------------------------------------------------------- */
3631 NSScreen *screen = [NSScreen mainScreen];
3632 NSWindowDepth depth = [screen depth];
3634 dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
3635 dpyinfo->resy = 72.27;
3636 dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
3637 NSColorSpaceFromDepth (depth)]
3638 && ![NSCalibratedWhiteColorSpace isEqualToString:
3639 NSColorSpaceFromDepth (depth)];
3640 dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
3641 dpyinfo->image_cache = make_image_cache ();
3642 dpyinfo->color_table
3643 = (struct ns_color_table *)xmalloc (sizeof (struct ns_color_table));
3644 dpyinfo->color_table->colors = NULL;
3645 dpyinfo->root_window = 42; /* a placeholder.. */
3647 dpyinfo->mouse_face_mouse_frame = NULL;
3648 dpyinfo->mouse_face_deferred_gc = 0;
3649 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
3650 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
3651 dpyinfo->mouse_face_face_id = DEFAULT_FACE_ID;
3652 dpyinfo->mouse_face_window = dpyinfo->mouse_face_overlay = Qnil;
3653 dpyinfo->mouse_face_hidden = 0;
3655 dpyinfo->mouse_face_mouse_x = dpyinfo->mouse_face_mouse_y = 0;
3656 dpyinfo->mouse_face_defer = 0;
3658 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
3660 dpyinfo->n_fonts = 0;
3661 dpyinfo->smallest_font_height = 1;
3662 dpyinfo->smallest_char_width = 1;
3666 /* This and next define (many of the) public functions in this file. */
3667 /* x_... are generic versions in xdisp.c that we, and other terms, get away
3668 with using despite presence in the "system dependent" redisplay
3669 interface. In addition, many of the ns_ methods have code that is
3670 shared with all terms, indicating need for further refactoring. */
3671 extern frame_parm_handler ns_frame_parm_handlers[];
3672 static struct redisplay_interface ns_redisplay_interface =
3674 ns_frame_parm_handlers,
3678 x_clear_end_of_line,
3680 ns_after_update_window_line,
3681 ns_update_window_begin,
3682 ns_update_window_end,
3685 0, /* flush_display_optional */
3686 x_clear_window_mouse_face,
3687 x_get_glyph_overhangs,
3688 x_fix_overlapping_area,
3689 ns_draw_fringe_bitmap,
3690 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
3691 0, /* destroy_fringe_bitmap */
3692 ns_compute_glyph_string_overhangs,
3693 ns_draw_glyph_string, /* interface to nsfont.m */
3694 ns_define_frame_cursor,
3695 ns_clear_frame_area,
3696 ns_draw_window_cursor,
3697 ns_draw_vertical_window_border,
3698 ns_shift_glyphs_for_insert
3703 ns_delete_display (struct ns_display_info *dpyinfo)
3709 /* This function is called when the last frame on a display is deleted. */
3711 ns_delete_terminal (struct terminal *terminal)
3713 struct ns_display_info *dpyinfo = terminal->display_info.ns;
3716 /* Protect against recursive calls. delete_frame in
3717 delete_terminal calls us back when it deletes our last frame. */
3718 if (!terminal->name)
3723 x_destroy_all_bitmaps (dpyinfo);
3724 ns_delete_display (dpyinfo);
3729 static struct terminal *
3730 ns_create_terminal (struct ns_display_info *dpyinfo)
3731 /* --------------------------------------------------------------------------
3732 Set up use of NS before we make the first connection.
3733 -------------------------------------------------------------------------- */
3735 struct terminal *terminal;
3737 NSTRACE (ns_create_terminal);
3739 terminal = create_terminal ();
3741 terminal->type = output_ns;
3742 terminal->display_info.ns = dpyinfo;
3743 dpyinfo->terminal = terminal;
3745 terminal->rif = &ns_redisplay_interface;
3747 terminal->clear_frame_hook = ns_clear_frame;
3748 terminal->ins_del_lines_hook = 0; /* XXX vestigial? */
3749 terminal->delete_glyphs_hook = 0; /* XXX vestigial? */
3750 terminal->ring_bell_hook = ns_ring_bell;
3751 terminal->reset_terminal_modes_hook = ns_reset_terminal_modes;
3752 terminal->set_terminal_modes_hook = ns_set_terminal_modes;
3753 terminal->update_begin_hook = ns_update_begin;
3754 terminal->update_end_hook = ns_update_end;
3755 terminal->set_terminal_window_hook = NULL; /* XXX vestigial? */
3756 terminal->read_socket_hook = ns_read_socket;
3757 terminal->frame_up_to_date_hook = ns_frame_up_to_date;
3758 terminal->mouse_position_hook = ns_mouse_position;
3759 terminal->frame_rehighlight_hook = ns_frame_rehighlight;
3760 terminal->frame_raise_lower_hook = ns_frame_raise_lower;
3762 terminal->fullscreen_hook = 0; /* see XTfullscreen_hook */
3764 terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
3765 terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
3766 terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
3767 terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
3769 terminal->delete_frame_hook = x_destroy_window;
3770 terminal->delete_terminal_hook = ns_delete_terminal;
3772 terminal->scroll_region_ok = 1;
3773 terminal->char_ins_del_ok = 1;
3774 terminal->line_ins_del_ok = 1;
3775 terminal->fast_clear_end_of_line = 1;
3776 terminal->memory_below_frame = 0;
3782 struct ns_display_info *
3783 ns_term_init (Lisp_Object display_name)
3784 /* --------------------------------------------------------------------------
3785 Start the Application and get things rolling.
3786 -------------------------------------------------------------------------- */
3788 struct terminal *terminal;
3789 struct ns_display_info *dpyinfo;
3790 static int ns_initialized = 0;
3793 NSTRACE (ns_term_init);
3795 /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
3796 /*GSDebugAllocationActive (YES); */
3798 handling_signal = 0;
3800 if (!ns_initialized)
3803 Fset_input_interrupt_mode (Qnil);
3807 ns_pending_files = [[NSMutableArray alloc] init];
3808 ns_pending_service_names = [[NSMutableArray alloc] init];
3809 ns_pending_service_args = [[NSMutableArray alloc] init];
3811 /* Start app and create the main menu, window, view.
3812 Needs to be here because ns_initialize_display_info () uses AppKit classes.
3813 The view will then ask the NSApp to stop and return to Emacs. */
3814 [EmacsApp sharedApplication];
3817 [NSApp setDelegate: NSApp];
3819 /* debugging: log all notifications */
3820 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
3821 selector: @selector (logNotification:)
3822 name: nil object: nil]; */
3824 dpyinfo = (struct ns_display_info *)xmalloc (sizeof (struct ns_display_info));
3825 bzero (dpyinfo, sizeof (struct ns_display_info));
3827 ns_initialize_display_info (dpyinfo);
3828 terminal = ns_create_terminal (dpyinfo);
3830 terminal->kboard = (KBOARD *) xmalloc (sizeof (KBOARD));
3831 init_kboard (terminal->kboard);
3832 terminal->kboard->Vwindow_system = Qns;
3833 terminal->kboard->next_kboard = all_kboards;
3834 all_kboards = terminal->kboard;
3835 /* Don't let the initial kboard remain current longer than necessary.
3836 That would cause problems if a file loaded on startup tries to
3837 prompt in the mini-buffer. */
3838 if (current_kboard == initial_kboard)
3839 current_kboard = terminal->kboard;
3840 terminal->kboard->reference_count++;
3842 dpyinfo->next = x_display_list;
3843 x_display_list = dpyinfo;
3845 /* Put it on ns_display_name_list */
3846 ns_display_name_list = Fcons (Fcons (display_name, Qnil),
3847 ns_display_name_list);
3848 dpyinfo->name_list_element = XCAR (ns_display_name_list);
3850 /* Set the name of the terminal. */
3851 terminal->name = (char *) xmalloc (SBYTES (display_name) + 1);
3852 strncpy (terminal->name, SDATA (display_name), SBYTES (display_name));
3853 terminal->name[SBYTES (display_name)] = 0;
3857 /* Read various user defaults. */
3858 ns_set_default_prefs ();
3859 if (!ns_no_defaults)
3861 ns_default ("GSFontAntiAlias", &ns_antialias_text,
3864 /* this is a standard variable */
3865 ns_default ("AppleAntiAliasingThreshold", &tmp,
3866 make_float (10.0), make_float (6.0), YES, NO);
3867 ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
3870 ns_selection_color = [[NSUserDefaults standardUserDefaults]
3871 stringForKey: @"AppleHighlightColor"];
3872 if (ns_selection_color == nil)
3873 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
3876 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
3880 Lisp_Object color_file, color_map, color;
3885 color_file = Fexpand_file_name (build_string ("rgb.txt"),
3886 Fsymbol_value (intern ("data-directory")));
3887 if (NILP (Ffile_readable_p (color_file)))
3888 fatal ("Could not find %s.\n", SDATA (color_file));
3890 color_map = Fx_load_color_file (color_file);
3891 if (NILP (color_map))
3892 fatal ("Could not read %s.\n", SDATA (color_file));
3894 cl = [[NSColorList alloc] initWithName: @"Emacs"];
3895 for ( ; CONSP (color_map); color_map = XCDR (color_map))
3897 color = XCAR (color_map);
3898 name = SDATA (XCAR (color));
3899 c = XINT (XCDR (color));
3901 [NSColor colorWithCalibratedRed: RED_FROM_ULONG (c) / 255.0
3902 green: GREEN_FROM_ULONG (c) / 255.0
3903 blue: BLUE_FROM_ULONG (c) / 255.0
3905 forKey: [NSString stringWithUTF8String: name]];
3907 [cl writeToFile: nil];
3913 #ifdef NS_IMPL_GNUSTEP
3914 strncpy (c, gnustep_base_version, sizeof (c));
3916 /*PSnextrelease (128, c); */
3917 snprintf (c, sizeof (c), "%g", NSAppKitVersionNumber);
3919 Vwindow_system_version = build_string (c);
3922 delete_keyboard_wait_descriptor (0);
3924 /* Set up OS X app menu */
3925 #ifdef NS_IMPL_COCOA
3929 /* set up the application menu */
3930 svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
3931 [svcsMenu setAutoenablesItems: NO];
3932 appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
3933 [appMenu setAutoenablesItems: NO];
3934 mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
3935 dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
3937 [appMenu insertItemWithTitle: @"About Emacs"
3938 action: @selector (orderFrontStandardAboutPanel:)
3941 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
3942 [appMenu insertItemWithTitle: @"Preferences..."
3943 action: @selector (showPreferencesWindow:)
3946 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
3947 item = [appMenu insertItemWithTitle: @"Services"
3948 action: @selector (menuDown:)
3951 [appMenu setSubmenu: svcsMenu forItem: item];
3952 /* [svcsMenu setSupercell: item]; */
3953 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
3954 [appMenu insertItemWithTitle: @"Hide Emacs"
3955 action: @selector (hide:)
3958 item = [appMenu insertItemWithTitle: @"Hide Others"
3959 action: @selector (hideOtherApplications:)
3962 [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
3963 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
3964 [appMenu insertItemWithTitle: @"Quit Emacs"
3965 action: @selector (terminate:)
3969 item = [mainMenu insertItemWithTitle: @"Emacs"
3970 action: @selector (menuDown:)
3973 [mainMenu setSubmenu: appMenu forItem: item];
3974 [dockMenu insertItemWithTitle: @"New Frame"
3975 action: @selector (newFrame:)
3979 [NSApp setMainMenu: mainMenu];
3980 [NSApp setAppleMenu: appMenu];
3981 [NSApp setServicesMenu: svcsMenu];
3982 /* Needed at least on Cocoa, to get dock menu to show windows */
3983 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
3985 #endif /* MAC OS X menu setup */
3993 extern Lisp_Object Vauto_save_list_file_name;
3995 ns_term_shutdown (int sig)
3997 /* code not reached in emacs.c after this is called by shut_down_emacs: */
3998 if (STRINGP (Vauto_save_list_file_name))
3999 unlink (SDATA (Vauto_save_list_file_name));
4001 if (sig == 0 || sig == SIGTERM)
4003 [NSApp terminate: NSApp];
4005 else // force a stack trace to happen
4012 /* ==========================================================================
4014 EmacsApp implementation
4016 ========================================================================== */
4019 @implementation EmacsApp
4021 - (void)logNotification: (NSNotification *)notification
4023 const char *name = [[notification name] UTF8String];
4024 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4025 && !strstr (name, "WindowNumber"))
4026 NSLog (@"notification: '%@'", [notification name]);
4030 - (void)sendEvent: (NSEvent *)theEvent
4031 /* --------------------------------------------------------------------------
4032 Called when NSApp is running for each event received. Used to stop
4033 the loop when we choose, since there's no way to just run one iteration.
4034 -------------------------------------------------------------------------- */
4036 int type = [theEvent type];
4037 NSWindow *window = [theEvent window];
4038 /* NSTRACE (sendEvent); */
4039 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4041 if (type == NSCursorUpdate && window == nil)
4043 fprintf (stderr, "Dropping external cursor update event.\n");
4047 #ifdef NS_IMPL_COCOA
4048 /* pass mouse down in resize handle and subsequent drags directly to
4049 EmacsWindow so we can generate continuous redisplays */
4052 if (type == NSLeftMouseDragged)
4054 [window mouseDragged: theEvent];
4057 else if (type == NSLeftMouseUp)
4059 [window mouseUp: theEvent];
4063 else if (type == NSLeftMouseDown)
4065 NSRect r = ns_resize_handle_rect (window);
4066 if (NSPointInRect ([theEvent locationInWindow], r))
4069 [window mouseDown: theEvent];
4075 if (type == NSApplicationDefined)
4077 /* Events posted by ns_send_appdefined interrupt the run loop here.
4078 But, if a modal window is up, an appdefined can still come through,
4079 (e.g., from a makeKeyWindow event) but stopping self also stops the
4080 modal loop. Just defer it until later. */
4081 if ([NSApp modalWindow] == nil)
4083 last_appdefined_event = theEvent;
4088 send_appdefined = YES;
4092 [super sendEvent: theEvent];
4096 - (void)showPreferencesWindow: (id)sender
4098 struct frame *emacsframe = SELECTED_FRAME ();
4099 NSEvent *theEvent = [NSApp currentEvent];
4103 emacs_event->kind = NS_NONKEY_EVENT;
4104 emacs_event->code = KEY_NS_SHOW_PREFS;
4105 emacs_event->modifiers = 0;
4106 EV_TRAILER (theEvent);
4110 - (void)newFrame: (id)sender
4112 struct frame *emacsframe = SELECTED_FRAME ();
4113 NSEvent *theEvent = [NSApp currentEvent];
4117 emacs_event->kind = NS_NONKEY_EVENT;
4118 emacs_event->code = KEY_NS_NEW_FRAME;
4119 emacs_event->modifiers = 0;
4120 EV_TRAILER (theEvent);
4124 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4125 - (BOOL) openFile: (NSString *)fileName
4127 struct frame *emacsframe = SELECTED_FRAME ();
4128 NSEvent *theEvent = [NSApp currentEvent];
4133 emacs_event->kind = NS_NONKEY_EVENT;
4134 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4135 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4136 ns_input_line = Qnil; /* can be start or cons start,end */
4137 emacs_event->modifiers =0;
4138 EV_TRAILER (theEvent);
4144 /* **************************************************************************
4146 EmacsApp delegate implementation
4148 ************************************************************************** */
4150 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4151 /* --------------------------------------------------------------------------
4152 When application is loaded, terminate event loop in ns_term_init
4153 -------------------------------------------------------------------------- */
4155 NSTRACE (applicationDidFinishLaunching);
4156 [NSApp setServicesProvider: NSApp];
4157 ns_send_appdefined (-2);
4161 /* Termination sequences:
4164 MenuBar | File | Exit:
4165 Select Quit from App menubar:
4167 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4170 Select Quit from Dock menu:
4173 Cancel -> Nothing else
4177 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4182 - (void) terminate: (id)sender
4184 struct frame *emacsframe = SELECTED_FRAME ();
4189 emacs_event->kind = NS_NONKEY_EVENT;
4190 emacs_event->code = KEY_NS_POWER_OFF;
4191 emacs_event->arg = Qt; /* mark as non-key event */
4192 EV_TRAILER ((id)nil);
4196 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4200 if (NILP (ns_confirm_quit)) // || ns_shutdown_properly --> TO DO
4201 return NSTerminateNow;
4203 ret = NSRunAlertPanel([[NSProcessInfo processInfo] processName],
4204 [NSString stringWithUTF8String:"Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?"],
4205 @"Save Buffers and Exit", @"Cancel", nil);
4207 if (ret == NSAlertDefaultReturn)
4208 return NSTerminateNow;
4209 else if (ret == NSAlertAlternateReturn)
4210 return NSTerminateCancel;
4211 return NSTerminateNow; /* just in case */
4215 /* Notification from the Workspace to open a file */
4216 - (BOOL)application: sender openFile: (NSString *)file
4218 [ns_pending_files addObject: file];
4223 /* Open a file as a temporary file */
4224 - (BOOL)application: sender openTempFile: (NSString *)file
4226 [ns_pending_files addObject: file];
4231 /* Notification from the Workspace to open a file noninteractively (?) */
4232 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4234 [ns_pending_files addObject: file];
4239 /* Notification from the Workspace to open multiple files */
4240 - (void)application: sender openFiles: (NSArray *)fileList
4242 NSEnumerator *files = [fileList objectEnumerator];
4244 while ((file = [files nextObject]) != nil)
4245 [ns_pending_files addObject: file];
4247 /* TODO: when GNUstep implements this (and we require that version of
4248 GNUstep), remove. */
4249 #ifndef NS_IMPL_GNUSTEP
4250 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4251 #endif /* !NS_IMPL_GNUSTEP */
4256 /* Handle dock menu requests. */
4257 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4263 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4264 - (void)applicationWillBecomeActive: (NSNotification *)notification
4266 //ns_app_active=YES;
4268 - (void)applicationDidBecomeActive: (NSNotification *)notification
4270 //ns_app_active=YES;
4272 - (void)applicationDidResignActive: (NSNotification *)notification
4275 ns_send_appdefined (-1);
4280 /* ==========================================================================
4282 EmacsApp aux handlers for managing event loop
4284 ========================================================================== */
4287 - (void)timeout_handler: (NSTimer *)timedEntry
4288 /* --------------------------------------------------------------------------
4289 The timeout specified to ns_select has passed.
4290 -------------------------------------------------------------------------- */
4292 /*NSTRACE (timeout_handler); */
4293 ns_send_appdefined (-2);
4296 extern void update_window_cursor (struct window *w, int on);
4298 - (void)fd_handler: (NSTimer *) fdEntry
4299 /* --------------------------------------------------------------------------
4300 Check data waiting on file descriptors and terminate if so
4301 -------------------------------------------------------------------------- */
4304 /* NSTRACE (fd_handler); */
4306 if (select_nfds == 0)
4309 memcpy (&t_readfds, &select_readfds, sizeof (fd_set));
4311 select_timeout.tv_sec = select_timeout.tv_usec = 0;
4312 result = select (select_nfds, &t_readfds, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
4316 memcpy (&select_readfds, &t_readfds, sizeof (fd_set));
4317 ns_send_appdefined (result);
4323 /* ==========================================================================
4327 ========================================================================== */
4329 /* called from system: queue for next pass through event loop */
4330 - (void)requestService: (NSPasteboard *)pboard
4331 userData: (NSString *)userData
4332 error: (NSString **)error
4334 [ns_pending_service_names addObject: userData];
4335 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
4336 SDATA (ns_string_from_pasteboard (pboard))]];
4340 /* called from ns_read_socket to clear queue */
4341 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
4343 struct frame *emacsframe = SELECTED_FRAME ();
4344 NSEvent *theEvent = [NSApp currentEvent];
4349 emacs_event->kind = NS_NONKEY_EVENT;
4350 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
4351 ns_input_spi_name = build_string ([name UTF8String]);
4352 ns_input_spi_arg = build_string ([arg UTF8String]);
4353 emacs_event->modifiers = EV_MODIFIERS (theEvent);
4354 EV_TRAILER (theEvent);
4364 /* ==========================================================================
4366 EmacsView implementation
4368 ========================================================================== */
4371 @implementation EmacsView
4373 /* needed to inform when window closed from LISP */
4374 - (void) setWindowClosing: (BOOL)closing
4376 windowClosing = closing;
4382 NSTRACE (EmacsView_dealloc);
4388 /* called on font panel selection */
4389 - (void)changeFont: (id)sender
4391 NSEvent *e =[[self window] currentEvent];
4392 struct face *face =FRAME_DEFAULT_FACE (emacsframe);
4396 NSTRACE (changeFont);
4400 if (newFont = [sender convertFont:
4401 ((struct nsfont_info *)face->font)->nsfont])
4403 SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
4405 emacs_event->kind = NS_NONKEY_EVENT;
4406 emacs_event->modifiers = 0;
4407 emacs_event->code = KEY_NS_CHANGE_FONT;
4409 size = [newFont pointSize];
4410 ns_input_fontsize = make_number (lrint (size));
4411 ns_input_font = build_string ([[newFont familyName] UTF8String]);
4417 - (BOOL)acceptsFirstResponder
4419 NSTRACE (acceptsFirstResponder);
4424 - (void)resetCursorRects
4426 NSRect visible = [self visibleRect];
4427 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
4428 NSTRACE (resetCursorRects);
4430 if (currentCursor == nil)
4431 currentCursor = [NSCursor arrowCursor];
4433 if (!NSIsEmptyRect (visible))
4434 [self addCursorRect: visible cursor: currentCursor];
4435 [currentCursor setOnMouseEntered: YES];
4440 /*****************************************************************************/
4441 /* Keyboard handling. */
4444 - (void)keyDown: (NSEvent *)theEvent
4446 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4448 unsigned fnKeysym = 0;
4450 static NSMutableArray *nsEvArray;
4451 static BOOL firstTime = YES;
4455 /* Rhapsody and OS X give up and down events for the arrow keys */
4456 if (ns_fake_keydown == YES)
4457 ns_fake_keydown = NO;
4458 else if ([theEvent type] != NSKeyDown)
4464 if (![[self window] isKeyWindow])
4466 /* XXX: There is an occasional condition in which, when Emacs display
4467 updates a different frame from the current one, and temporarily
4468 selects it, then processes some interrupt-driven input
4469 (dispnew.c:3878), OS will send the event to the correct NSWindow, but
4470 for some reason that window has its first responder set to the NSView
4471 most recently updated (I guess), which is not the correct one. */
4472 if ([[theEvent window] isKindOfClass: [EmacsWindow class]])
4473 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
4477 if (nsEvArray == nil)
4478 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
4480 [NSCursor setHiddenUntilMouseMoves: YES];
4482 if (dpyinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
4484 clear_mouse_face (dpyinfo);
4485 dpyinfo->mouse_face_hidden = 1;
4488 if (!processingCompose)
4490 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
4491 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
4492 /* (Carbon way: [theEvent keyCode]) */
4494 /* is it a "function key"? */
4495 fnKeysym = ns_convert_key (code);
4498 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
4499 because Emacs treats Delete and KP-Delete same (in simple.el). */
4500 if (fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
4501 code = 0xFF08; /* backspace */
4506 /* are there modifiers? */
4507 emacs_event->modifiers = 0;
4508 flags = [theEvent modifierFlags];
4510 if (flags & NSHelpKeyMask)
4511 emacs_event->modifiers |= hyper_modifier;
4513 if (flags & NSShiftKeyMask)
4514 emacs_event->modifiers |= shift_modifier;
4516 if (flags & NSCommandKeyMask)
4518 emacs_event->modifiers |= parse_solitary_modifier (ns_command_modifier);
4519 /* if super (default), take input manager's word so things like
4520 dvorak / qwerty layout work */
4521 if (EQ (ns_command_modifier, Qsuper)
4523 && [[theEvent characters] length] != 0)
4525 /* XXX: the code we get will be unshifted, so if we have
4526 a shift modifier, must convert ourselves */
4527 if (!(flags & NSShiftKeyMask))
4528 code = [[theEvent characters] characterAtIndex: 0];
4530 /* this is ugly and also requires linking w/Carbon framework
4531 (for LMGetKbdType) so for now leave this rare (?) case
4532 undealt with.. in future look into CGEvent methods */
4535 long smv = GetScriptManagerVariable (smKeyScript);
4536 Handle uchrHandle = GetResource
4537 ('uchr', GetScriptVariable (smv, smScriptKeys));
4539 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
4540 [[theEvent characters] characterAtIndex: 0],
4541 kUCKeyActionDisplay,
4542 (flags & ~NSCommandKeyMask) >> 8,
4543 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
4544 &dummy, 1, &dummy, &code);
4551 if (flags & NSControlKeyMask)
4552 emacs_event->modifiers |=
4553 parse_solitary_modifier (ns_control_modifier);
4555 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
4556 emacs_event->modifiers |=
4557 parse_solitary_modifier (ns_function_modifier);
4559 if (flags & NSAlternateKeyMask) /* default = meta */
4561 if ((NILP (ns_alternate_modifier) || EQ (ns_alternate_modifier, Qnone))
4563 { /* accept pre-interp alt comb */
4564 if ([[theEvent characters] length] > 0)
4565 code = [[theEvent characters] characterAtIndex: 0];
4566 /*HACK: clear lone shift modifier to stop next if from firing */
4567 if (emacs_event->modifiers == shift_modifier)
4568 emacs_event->modifiers = 0;
4571 emacs_event->modifiers |=
4572 parse_solitary_modifier (ns_alternate_modifier);
4576 fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
4577 code, fnKeysym, flags, emacs_event->modifiers);
4579 /* if it was a function key or had modifiers, pass it directly to emacs */
4580 if (fnKeysym || (emacs_event->modifiers
4581 && [[theEvent charactersIgnoringModifiers] length] > 0))
4582 /*[[theEvent characters] length] */
4584 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4586 code |= (1<<28)|(3<<16);
4587 else if (code == 0x7f)
4588 code |= (1<<28)|(3<<16);
4590 emacs_event->kind = code > 0xFF
4591 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4593 emacs_event->code = code;
4594 EV_TRAILER (theEvent);
4599 /* if we get here we should send the key for input manager processing */
4600 if (firstTime && [[NSInputManager currentInputManager]
4601 wantsToDelayTextChangeNotifications] == NO)
4603 "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
4606 if (NS_KEYLOG && !processingCompose)
4607 fprintf (stderr, "keyDown: Begin compose sequence.\n");
4609 processingCompose = YES;
4610 [nsEvArray addObject: theEvent];
4611 [self interpretKeyEvents: nsEvArray];
4612 [nsEvArray removeObject: theEvent];
4616 #ifdef NS_IMPL_COCOA
4617 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
4618 decided not to send key-down for.
4619 See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
4620 If it matches one of these, send it on to keyDown. */
4621 -(void)keyUp: (NSEvent *)theEvent
4623 int flags = [theEvent modifierFlags];
4624 int code = [theEvent keyCode];
4625 if (code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
4628 fprintf (stderr, "keyUp: passed test");
4629 ns_fake_keydown = YES;
4630 [self keyDown: theEvent];
4636 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
4639 /* <NSTextInput>: called when done composing;
4640 NOTE: also called when we delete over working text, followed immed.
4641 by doCommandBySelector: deleteBackward: */
4642 - (void)insertText: (id)aString
4645 int len = [(NSString *)aString length];
4649 NSLog (@"insertText '%@'\tlen = %d", aString, len);
4650 processingCompose = NO;
4655 /* first, clear any working text */
4656 if (workingText != nil)
4657 [self deleteWorkingText];
4659 /* now insert the string as keystrokes */
4660 for (i =0; i<len; i++)
4662 code = [aString characterAtIndex: i];
4663 /* TODO: still need this? */
4665 code = '~'; /* 0x7E */
4666 emacs_event->modifiers = 0;
4668 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4669 emacs_event->code = code;
4670 EV_TRAILER ((id)nil);
4675 /* <NSTextInput>: inserts display of composing characters */
4676 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
4678 NSString *str = [aString respondsToSelector: @selector (string)] ?
4679 [aString string] : aString;
4681 NSLog (@"setMarkedText '%@' len =%d range %d from %d", str, [str length],
4682 selRange.length, selRange.location);
4684 if (workingText != nil)
4685 [self deleteWorkingText];
4686 if ([str length] == 0)
4692 processingCompose = YES;
4693 workingText = [str copy];
4694 ns_working_text = build_string ([workingText UTF8String]);
4696 emacs_event->kind = NS_TEXT_EVENT;
4697 emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
4698 EV_TRAILER ((id)nil);
4702 /* delete display of composing characters [not in <NSTextInput>] */
4703 - (void)deleteWorkingText
4705 if (workingText == nil)
4708 NSLog(@"deleteWorkingText len =%d\n", [workingText length]);
4709 [workingText release];
4711 processingCompose = NO;
4716 emacs_event->kind = NS_TEXT_EVENT;
4717 emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
4718 EV_TRAILER ((id)nil);
4722 - (BOOL)hasMarkedText
4724 return workingText != nil;
4728 - (NSRange)markedRange
4730 NSRange rng = workingText != nil
4731 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
4733 NSLog (@"markedRange request");
4741 NSLog (@"unmark (accept) text");
4742 [self deleteWorkingText];
4743 processingCompose = NO;
4747 /* used to position char selection windows, etc. */
4748 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
4752 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
4754 NSLog (@"firstRectForCharRange request");
4756 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
4757 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
4758 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
4759 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
4760 +FRAME_LINE_HEIGHT (emacsframe));
4762 pt = [self convertPoint: pt toView: nil];
4763 pt = [[self window] convertBaseToScreen: pt];
4769 - (NSInteger)conversationIdentifier
4771 return (NSInteger)self;
4775 - (void)doCommandBySelector: (SEL)aSelector
4778 NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
4780 if (aSelector == @selector (deleteBackward:))
4782 /* happens when user backspaces over an ongoing composition:
4783 throw a 'delete' into the event queue */
4786 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4787 emacs_event->code = 0xFF08;
4788 EV_TRAILER ((id)nil);
4792 - (NSArray *)validAttributesForMarkedText
4794 static NSArray *arr = nil;
4795 if (arr == nil) arr = [NSArray new];
4796 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
4800 - (NSRange)selectedRange
4803 NSLog (@"selectedRange request");
4804 return NSMakeRange (NSNotFound, 0);
4807 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
4810 NSLog (@"characterIndexForPoint request");
4814 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
4816 static NSAttributedString *str = nil;
4817 if (str == nil) str = [NSAttributedString new];
4819 NSLog (@"attributedSubstringFromRange request");
4823 /* End <NSTextInput> impl. */
4824 /*****************************************************************************/
4827 /* This is what happens when the user presses a mouse button. */
4828 - (void)mouseDown: (NSEvent *)theEvent
4830 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
4833 NSTRACE (mouseDown);
4835 [self deleteWorkingText];
4840 last_mouse_frame = emacsframe;
4841 /* appears to be needed to prevent spurious movement events generated on
4843 last_mouse_frame->mouse_moved = 0;
4845 if ([theEvent type] == NSScrollWheel)
4847 float delta = [theEvent deltaY];
4848 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
4851 emacs_event->kind = WHEEL_EVENT;
4852 emacs_event->code = 0;
4853 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
4854 ((delta > 0) ? up_modifier : down_modifier);
4858 emacs_event->kind = MOUSE_CLICK_EVENT;
4859 emacs_event->code = EV_BUTTON (theEvent);
4860 emacs_event->modifiers = EV_MODIFIERS (theEvent)
4861 | EV_UDMODIFIERS (theEvent);
4863 XSETINT (emacs_event->x, lrint (p.x));
4864 XSETINT (emacs_event->y, lrint (p.y));
4865 EV_TRAILER (theEvent);
4869 - (void)rightMouseDown: (NSEvent *)theEvent
4871 NSTRACE (rightMouseDown);
4872 [self mouseDown: theEvent];
4876 - (void)otherMouseDown: (NSEvent *)theEvent
4878 NSTRACE (otherMouseDown);
4879 [self mouseDown: theEvent];
4883 - (void)mouseUp: (NSEvent *)theEvent
4886 [self mouseDown: theEvent];
4890 - (void)rightMouseUp: (NSEvent *)theEvent
4892 NSTRACE (rightMouseUp);
4893 [self mouseDown: theEvent];
4897 - (void)otherMouseUp: (NSEvent *)theEvent
4899 NSTRACE (otherMouseUp);
4900 [self mouseDown: theEvent];
4904 - (void) scrollWheel: (NSEvent *)theEvent
4906 NSTRACE (scrollWheel);
4907 [self mouseDown: theEvent];
4911 /* Tell emacs the mouse has moved. */
4912 - (void)mouseMoved: (NSEvent *)e
4914 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4917 // NSTRACE (mouseMoved);
4919 last_mouse_movement_time = EV_TIMESTAMP (e);
4920 last_mouse_motion_position
4921 = [self convertPoint: [e locationInWindow] fromView: nil];
4923 /* update any mouse face */
4924 if (dpyinfo->mouse_face_hidden)
4926 dpyinfo->mouse_face_hidden = 0;
4927 clear_mouse_face (dpyinfo);
4930 /* tooltip handling */
4931 previous_help_echo_string = help_echo_string;
4932 help_echo_string = Qnil;
4934 if (!note_mouse_movement (emacsframe, last_mouse_motion_position.x,
4935 last_mouse_motion_position.y))
4936 help_echo_string = previous_help_echo_string;
4938 XSETFRAME (frame, emacsframe);
4939 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
4941 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
4942 (note_mouse_highlight), which is called through the
4943 note_mouse_movement () call above */
4944 gen_help_event (help_echo_string, frame, help_echo_window,
4945 help_echo_object, help_echo_pos);
4949 help_echo_string = Qnil;
4950 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
4953 if (emacsframe->mouse_moved && send_appdefined)
4954 ns_send_appdefined (-1);
4958 - (void)mouseDragged: (NSEvent *)e
4960 NSTRACE (mouseDragged);
4961 [self mouseMoved: e];
4965 - (void)rightMouseDragged: (NSEvent *)e
4967 NSTRACE (rightMouseDragged);
4968 [self mouseMoved: e];
4972 - (void)otherMouseDragged: (NSEvent *)e
4974 NSTRACE (otherMouseDragged);
4975 [self mouseMoved: e];
4979 - (BOOL)windowShouldClose: (id)sender
4981 NSEvent *e =[[self window] currentEvent];
4983 NSTRACE (windowShouldClose);
4984 windowClosing = YES;
4987 emacs_event->kind = DELETE_WINDOW_EVENT;
4988 emacs_event->modifiers = 0;
4989 emacs_event->code = 0;
4991 /* Don't close this window, let this be done from lisp code. */
4996 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
4997 /* normalize frame to gridded text size */
4999 NSTRACE (windowWillResize);
5000 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
5002 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe,
5003 #ifdef NS_IMPL_GNUSTEP
5004 frameSize.width + 3);
5008 if (cols < MINWIDTH)
5010 frameSize.width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (emacsframe, cols);
5012 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, frameSize.height
5013 #ifdef NS_IMPL_GNUSTEP
5014 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe) + 3
5015 - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
5017 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5018 - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
5020 if (rows < MINHEIGHT)
5022 frameSize.height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows)
5023 + FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5024 + FRAME_NS_TOOLBAR_HEIGHT (emacsframe);
5025 #ifdef NS_IMPL_COCOA
5027 /* this sets window title to have size in it; the wm does this under GS */
5028 NSRect r = [[self window] frame];
5029 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
5040 NSWindow *window = [self window];
5043 const char *t = [[[self window] title] UTF8String];
5044 char *pos = strstr (t, " — ");
5047 old_title = (char *) xmalloc (strlen (t) + 1);
5048 strcpy (old_title, t);
5050 size_title = xmalloc (strlen (old_title) + 40);
5051 sprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
5052 [window setTitle: [NSString stringWithUTF8String: size_title]];
5057 #endif /* NS_IMPL_COCOA */
5058 /*fprintf (stderr," ...size became %.0f x %.0f (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
5064 - (void)windowDidResize: (NSNotification *)notification
5066 NSWindow *theWindow = [notification object];
5068 #ifdef NS_IMPL_GNUSTEP
5069 /* in GNUstep, at least currently, it's possible to get a didResize
5070 without getting a willResize.. therefore we need to act as if we got
5071 the willResize now */
5072 NSSize sz = [theWindow frame].size;
5073 sz = [self windowWillResize: theWindow toSize: sz];
5074 #endif /* NS_IMPL_GNUSTEP */
5076 NSTRACE (windowDidResize);
5077 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
5079 #ifdef NS_IMPL_COCOA
5085 #endif /* NS_IMPL_COCOA */
5087 // Calling x_set_window_size tends to get us into inf-loops
5088 // (x_set_window_size causes a resize which causes
5089 // a "windowDidResize" which calls x_set_window_size).
5090 // At least with GNUStep, don't know about MacOSX. --Stef
5091 #ifndef NS_IMPL_GNUSTEP
5092 if (cols > 0 && rows > 0)
5093 x_set_window_size (emacsframe, 0, cols, rows);
5096 ns_send_appdefined (-1);
5100 - (void)windowDidBecomeKey: (NSNotification *)notification
5101 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5103 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5104 struct frame *old_focus = dpyinfo->x_focus_frame;
5106 NSTRACE (windowDidBecomeKey);
5108 if (emacsframe != old_focus)
5109 dpyinfo->x_focus_frame = emacsframe;
5111 ns_frame_rehighlight (emacsframe);
5115 emacs_event->kind = FOCUS_IN_EVENT;
5116 EV_TRAILER ((id)nil);
5121 - (void)windowDidResignKey: (NSNotification *)notification
5122 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5124 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5125 NSTRACE (windowDidResignKey);
5127 if (dpyinfo->x_focus_frame == emacsframe)
5128 dpyinfo->x_focus_frame = 0;
5130 ns_frame_rehighlight (emacsframe);
5132 /* FIXME: for some reason needed on second and subsequent clicks away
5133 from sole-frame Emacs to get hollow box to show */
5134 if (!windowClosing && [[self window] isVisible] == YES)
5136 x_update_cursor (emacsframe, 1);
5137 x_set_frame_alpha (emacsframe);
5142 [self deleteWorkingText];
5143 emacs_event->kind = FOCUS_IN_EVENT;
5144 EV_TRAILER ((id)nil);
5149 - (void)windowWillMiniaturize: sender
5151 NSTRACE (windowWillMiniaturize);
5167 - initFrameFromEmacs: (struct frame *)f
5172 NSButton *toggleButton;
5173 int vbextra = NS_SCROLL_BAR_WIDTH (f);
5178 NSTRACE (initFrameFromEmacs);
5181 processingCompose = NO;
5182 scrollbarsNeedingUpdate = 0;
5184 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
5186 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
5187 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
5188 [self initWithFrame: r];
5190 FRAME_NS_VIEW (f) = self;
5194 win = [[EmacsWindow alloc]
5195 initWithContentRect: r
5196 styleMask: (NSResizableWindowMask |
5197 NSMiniaturizableWindowMask |
5198 NSClosableWindowMask)
5199 backing: NSBackingStoreBuffered
5203 f->border_width = wr.size.width - r.size.width;
5204 FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
5206 [win setAcceptsMouseMovedEvents: YES];
5207 [win setDelegate: self];
5208 [win useOptimizedDrawing: YES];
5210 sz.width = FRAME_COLUMN_WIDTH (f);
5211 sz.height = FRAME_LINE_HEIGHT (f);
5212 [win setResizeIncrements: sz];
5214 [[win contentView] addSubview: self];
5217 [self registerForDraggedTypes: ns_drag_types];
5220 name = [NSString stringWithUTF8String:
5221 NILP (tem) ? (unsigned char *)"Emacs" : SDATA (tem)];
5222 [win setTitle: name];
5224 /* toolbar support */
5225 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
5226 [NSString stringWithFormat: @"Emacs Frame %d",
5228 [win setToolbar: toolbar];
5229 [toolbar setVisible: NO];
5230 #ifdef NS_IMPL_COCOA
5231 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
5232 [toggleButton setTarget: self];
5233 [toggleButton setAction: @selector (toggleToolbar: )];
5235 FRAME_NS_TOOLBAR_HEIGHT (f) = 0;
5239 [win setMiniwindowTitle:
5240 [NSString stringWithUTF8String: SDATA (tem)]];
5243 NSScreen *screen = [win screen];
5246 [win setFrameTopLeftPoint: NSMakePoint
5247 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
5248 IN_BOUND (-SCREENMAX,
5249 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
5252 [win makeFirstResponder: self];
5254 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5255 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
5256 [win setBackgroundColor: col];
5257 if ([col alphaComponent] != 1.0)
5258 [win setOpaque: NO];
5260 [self allocateGState];
5267 - (void)windowDidMove: sender
5269 NSWindow *win = [self window];
5270 NSRect r = [win frame];
5271 NSScreen *screen = [win screen];
5272 NSRect sr = [screen frame];
5274 NSTRACE (windowDidMove);
5276 if (!emacsframe->output_data.ns)
5280 emacsframe->left_pos = r.origin.x; /* - sr.origin.x; */
5281 emacsframe->top_pos = sr.size.height -
5282 (r.origin.y + r.size.height); /* + sr.origin.y; */
5286 #ifdef NS_IMPL_COCOA
5287 /* if we don't do this manually, the window will resize but not move */
5288 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
5290 NSTRACE (windowShouldZoom);
5291 [[self window] setFrame: newFrame display: NO];
5297 /* Override to do something slightly nonstandard, but nice. First click on
5298 zoom button will zoom vertically. Second will zoom completely. Third
5299 returns to original. */
5300 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
5301 defaultFrame:(NSRect)defaultFrame
5303 NSRect result = [sender frame];
5304 NSTRACE (windowWillUseStandardFrame);
5306 if (result.size.height == defaultFrame.size.height) {
5307 result = defaultFrame;
5309 result.size.height = defaultFrame.size.height;
5310 result.origin.y = defaultFrame.origin.y;
5313 /* A windowWillResize does not get generated at least on Tiger. */
5314 [self windowWillResize: sender toSize: result.size];
5319 - (void)windowDidDeminiaturize: sender
5321 NSTRACE (windowDidDeminiaturize);
5322 if (!emacsframe->output_data.ns)
5324 emacsframe->async_iconified = 0;
5325 emacsframe->async_visible = 1;
5326 windows_or_buffers_changed++;
5330 emacs_event->kind = ICONIFY_EVENT;
5331 EV_TRAILER ((id)nil);
5336 - (void)windowDidExpose: sender
5338 NSTRACE (windowDidExpose);
5339 if (!emacsframe->output_data.ns)
5341 emacsframe->async_visible = 1;
5342 SET_FRAME_GARBAGED (emacsframe);
5344 if (send_appdefined)
5345 ns_send_appdefined (-1);
5349 - (void)windowDidMiniaturize: sender
5351 NSTRACE (windowDidMiniaturize);
5352 if (!emacsframe->output_data.ns)
5355 emacsframe->async_iconified = 1;
5356 emacsframe->async_visible = 0;
5360 emacs_event->kind = ICONIFY_EVENT;
5361 EV_TRAILER ((id)nil);
5366 - (void)mouseEntered: (NSEvent *)theEvent
5368 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5369 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5370 NSTRACE (mouseEntered);
5372 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5376 - (void)mouseExited: (NSEvent *)theEvent
5378 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5380 struct ns_display_info *dpyinfo
5381 = emacsframe ? FRAME_NS_DISPLAY_INFO (emacsframe) : NULL;
5383 NSTRACE (mouseExited);
5385 if (dpyinfo || !emacsframe)
5388 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5390 if (emacsframe == dpyinfo->mouse_face_mouse_frame)
5392 clear_mouse_face (dpyinfo);
5393 dpyinfo->mouse_face_mouse_frame = 0;
5401 if (context_menu_value == -1)
5402 context_menu_value = [sender tag];
5404 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
5405 emacsframe->menu_bar_vector,
5406 (void *)[sender tag]);
5407 ns_send_appdefined (-1);
5412 - (EmacsToolbar *)toolbar
5418 /* this gets called on toolbar button click */
5419 - toolbarClicked: (id)item
5422 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
5424 NSTRACE (toolbarClicked);
5429 /* send first event (for some reason two needed) */
5430 theEvent = [[self window] currentEvent];
5431 emacs_event->kind = TOOL_BAR_EVENT;
5432 XSETFRAME (emacs_event->arg, emacsframe);
5433 EV_TRAILER (theEvent);
5435 emacs_event->kind = TOOL_BAR_EVENT;
5436 /* XSETINT (emacs_event->code, 0); */
5437 emacs_event->arg = AREF (emacsframe->tool_bar_items,
5438 idx + TOOL_BAR_ITEM_KEY);
5439 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5440 EV_TRAILER (theEvent);
5445 - toggleToolbar: (id)sender
5450 emacs_event->kind = NS_NONKEY_EVENT;
5451 emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
5452 EV_TRAILER ((id)nil);
5457 - (void)drawRect: (NSRect)rect
5459 int x = NSMinX (rect), y = NSMinY (rect);
5460 int width = NSWidth (rect), height = NSHeight (rect);
5464 if (!emacsframe || !emacsframe->output_data.ns || ns_in_resize)
5467 ns_clear_frame_area (emacsframe, x, y, width, height);
5468 expose_frame (emacsframe, x, y, width, height);
5469 emacsframe->async_visible = 1;
5470 emacsframe->async_iconified = 0;
5474 /* NSDraggingDestination protocol methods. Actually this is not really a
5475 protocol, but a category of Object. O well... */
5477 -(unsigned int) draggingEntered: (id <NSDraggingInfo>) sender
5479 NSTRACE (draggingEntered);
5480 return NSDragOperationGeneric;
5484 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
5490 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
5495 NSEvent *theEvent = [[self window] currentEvent];
5498 NSTRACE (performDragOperation);
5503 position = [self convertPoint: [sender draggingLocation] fromView: nil];
5504 x = lrint (position.x); y = lrint (position.y);
5506 pb = [sender draggingPasteboard];
5507 type = [pb availableTypeFromArray: ns_drag_types];
5512 else if ([type isEqualToString: NSFilenamesPboardType])
5515 NSEnumerator *fenum;
5518 if (!(files = [pb propertyListForType: type]))
5521 fenum = [files objectEnumerator];
5522 while ( (file = [fenum nextObject]) )
5524 emacs_event->kind = NS_NONKEY_EVENT;
5525 emacs_event->code = KEY_NS_DRAG_FILE;
5526 XSETINT (emacs_event->x, x);
5527 XSETINT (emacs_event->y, y);
5528 ns_input_file = append2 (ns_input_file,
5529 build_string ([file UTF8String]));
5530 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5531 EV_TRAILER (theEvent);
5535 else if ([type isEqualToString: NSURLPboardType])
5540 if (!(fileURL = [NSURL URLFromPasteboard: pb]) ||
5541 [fileURL isFileURL] == NO)
5544 file = [fileURL path];
5545 emacs_event->kind = NS_NONKEY_EVENT;
5546 emacs_event->code = KEY_NS_DRAG_FILE;
5547 XSETINT (emacs_event->x, x);
5548 XSETINT (emacs_event->y, y);
5549 ns_input_file = append2 (ns_input_file, build_string ([file UTF8String]));
5550 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5551 EV_TRAILER (theEvent);
5554 else if ([type isEqualToString: NSStringPboardType]
5555 || [type isEqualToString: NSTabularTextPboardType])
5559 if (! (data = [pb stringForType: type]))
5562 emacs_event->kind = NS_NONKEY_EVENT;
5563 emacs_event->code = KEY_NS_DRAG_TEXT;
5564 XSETINT (emacs_event->x, x);
5565 XSETINT (emacs_event->y, y);
5566 ns_input_text = build_string ([data UTF8String]);
5567 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5568 EV_TRAILER (theEvent);
5571 else if ([type isEqualToString: NSColorPboardType])
5573 NSColor *c = [NSColor colorFromPasteboard: pb];
5574 emacs_event->kind = NS_NONKEY_EVENT;
5575 emacs_event->code = KEY_NS_DRAG_COLOR;
5576 XSETINT (emacs_event->x, x);
5577 XSETINT (emacs_event->y, y);
5578 ns_input_color = ns_color_to_lisp (c);
5579 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5580 EV_TRAILER (theEvent);
5583 else if ([type isEqualToString: NSFontPboardType])
5585 /* impl based on GNUstep NSTextView.m */
5586 NSData *data = [pb dataForType: NSFontPboardType];
5587 NSDictionary *dict = [NSUnarchiver unarchiveObjectWithData: data];
5588 NSFont *font = [dict objectForKey: NSFontAttributeName];
5594 emacs_event->kind = NS_NONKEY_EVENT;
5595 emacs_event->code = KEY_NS_CHANGE_FONT;
5596 XSETINT (emacs_event->x, x);
5597 XSETINT (emacs_event->y, y);
5598 ns_input_font = build_string ([[font fontName] UTF8String]);
5599 snprintf (fontSize, 10, "%f", [font pointSize]);
5600 ns_input_fontsize = build_string (fontSize);
5601 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5602 EV_TRAILER (theEvent);
5607 error ("Invalid data type in dragging pasteboard.");
5613 - validRequestorForSendType: (NSString *)typeSent
5614 returnType: (NSString *)typeReturned
5616 NSTRACE (validRequestorForSendType);
5617 if ([ns_send_types indexOfObjectIdenticalTo: typeSent] != NSNotFound &&
5618 [ns_return_types indexOfObjectIdenticalTo: typeSent] != NSNotFound)
5621 return [super validRequestorForSendType: typeSent
5622 returnType: typeReturned];
5626 /* The next two methods are part of NSServicesRequests informal protocol,
5627 supposedly called when a services menu item is chosen from this app.
5628 But this should not happen because we override the services menu with our
5629 own entries which call ns-perform-service.
5630 Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
5631 So let's at least stub them out until further investigation can be done. */
5633 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
5635 /* we could call ns_string_from_pasteboard(pboard) here but then it should
5636 be written into the buffer in place of the existing selection..
5637 ordinary service calls go through functions defined in ns-win.el */
5641 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
5643 /* supposed to write for as many of types as we are able */
5648 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
5649 (gives a miniaturized version of the window); currently we use the latter for
5650 frames whose active buffer doesn't correspond to any file
5651 (e.g., '*scratch*') */
5652 - setMiniwindowImage: (BOOL) setMini
5654 id image = [[self window] miniwindowImage];
5655 NSTRACE (setMiniwindowImage);
5657 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
5658 about "AppleDockIconEnabled" notwithstanding, however the set message
5659 below has its effect nonetheless. */
5660 if (image != emacsframe->output_data.ns->miniimage)
5662 if (image && [image isKindOfClass: [EmacsImage class]])
5664 [[self window] setMiniwindowImage:
5665 setMini ? emacsframe->output_data.ns->miniimage : nil];
5672 - (void) setRows: (int) r andColumns: (int) c
5678 @end /* EmacsView */
5682 /* ==========================================================================
5684 EmacsWindow implementation
5686 ========================================================================== */
5688 @implementation EmacsWindow
5690 /* called only on resize clicks by special case in EmacsApp-sendEvent */
5691 - (void)mouseDown: (NSEvent *)theEvent
5695 NSSize size = [[theEvent window] frame].size;
5696 grabOffset = [theEvent locationInWindow];
5697 grabOffset.x = size.width - grabOffset.x;
5700 [super mouseDown: theEvent];
5705 - (void)mouseUp: (NSEvent *)theEvent
5709 struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
5711 ns_set_name_as_filename (f);
5713 ns_send_appdefined (-1);
5716 [super mouseUp: theEvent];
5720 /* send resize events */
5721 - (void)mouseDragged: (NSEvent *)theEvent
5725 NSPoint p = [theEvent locationInWindow];
5726 NSSize size, vettedSize, origSize = [self frame].size;
5728 size.width = p.x + grabOffset.x;
5729 size.height = origSize.height - p.y + grabOffset.y;
5731 if (size.width == origSize.width && size.height == origSize.height)
5734 vettedSize = [[self delegate] windowWillResize: self toSize: size];
5735 if (vettedSize.width != size.width || vettedSize.height != size.height)
5737 [[NSNotificationCenter defaultCenter]
5738 postNotificationName: NSWindowDidResizeNotification
5743 [super mouseDragged: theEvent];
5746 @end /* EmacsWindow */
5749 /* ==========================================================================
5751 EmacsScroller implementation
5753 ========================================================================== */
5756 @implementation EmacsScroller
5758 /* for repeat button push */
5759 #define SCROLL_BAR_FIRST_DELAY 0.5
5760 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
5762 + (float) scrollerWidth
5764 /* TODO: if we want to allow variable widths, this is the place to do it,
5765 however neither GNUstep nor Cocoa support it very well */
5766 return [NSScroller scrollerWidth];
5770 - initFrame: (NSRect )r window: (Lisp_Object)nwin
5772 NSTRACE (EmacsScroller_initFrame);
5774 r.size.width = [EmacsScroller scrollerWidth];
5775 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
5776 [self setContinuous: YES];
5777 [self setEnabled: YES];
5779 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
5780 locked against the right, top and bottom edges. */
5781 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
5785 pixel_height = NSHeight (r);
5786 min_portion = 20 / pixel_height;
5788 frame = XFRAME (XWINDOW (win)->frame);
5789 if (FRAME_LIVE_P (frame))
5792 EmacsView *view = FRAME_NS_VIEW (frame);
5793 NSView *sview = [[view window] contentView];
5794 NSArray *subs = [sview subviews];
5796 /* disable optimization stopping redraw of other scrollbars */
5797 view->scrollbarsNeedingUpdate = 0;
5798 for (i =[subs count]-1; i >= 0; i--)
5799 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
5800 view->scrollbarsNeedingUpdate++;
5801 [sview addSubview: self];
5804 /* [self setFrame: r]; */
5810 - (void)setFrame: (NSRect)newRect
5812 NSTRACE (EmacsScroller_setFrame);
5814 pixel_height = NSHeight (newRect);
5815 min_portion = 20 / pixel_height;
5816 [super setFrame: newRect];
5818 /* UNBLOCK_INPUT; */
5824 NSTRACE (EmacsScroller_dealloc);
5826 XWINDOW (win)->vertical_scroll_bar = Qnil;
5853 /* ensure other scrollbar updates after deletion */
5854 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
5856 view->scrollbarsNeedingUpdate++;
5857 [self removeFromSuperview];
5865 - (void)resetCursorRects
5867 NSRect visible = [self visibleRect];
5868 NSTRACE (resetCursorRects);
5870 if (!NSIsEmptyRect (visible))
5871 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
5872 [[NSCursor arrowCursor] setOnMouseEntered: YES];
5876 - (int) checkSamePosition: (int) position portion: (int) portion
5879 return em_position ==position && em_portion ==portion && em_whole ==whole
5880 && portion != whole; /* needed for resize empty buf */
5884 - setPosition: (int)position portion: (int)portion whole: (int)whole
5886 NSTRACE (setPosition);
5888 em_position = position;
5889 em_portion = portion;
5892 if (portion >= whole)
5893 [self setFloatValue: 0.0 knobProportion: 1.0];
5897 portion = max ((float)whole*min_portion/pixel_height, portion);
5898 pos = (float)position / (whole - portion);
5899 por = (float)portion/whole;
5900 [self setFloatValue: pos knobProportion: por];
5902 #ifdef NS_IMPL_GNUSTEP
5908 /* FIXME: unused at moment (see ns_mouse_position) at the moment because
5909 drag events will go directly to the EmacsScroller. Leaving in for now. */
5910 -(void)getMouseMotionPart: (int *)part window: (Lisp_Object *)window
5911 x: (Lisp_Object *)x y: ( Lisp_Object *)y
5913 *part = last_hit_part;
5915 XSETINT (*y, pixel_height);
5916 if ([self floatValue] > 0.999)
5917 XSETINT (*x, pixel_height);
5919 XSETINT (*x, pixel_height * [self floatValue]);
5923 /* set up emacs_event */
5924 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
5929 emacs_event->part = last_hit_part;
5930 emacs_event->code = 0;
5931 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
5932 emacs_event->frame_or_window = win;
5933 emacs_event->timestamp = EV_TIMESTAMP (e);
5934 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
5935 emacs_event->arg = Qnil;
5936 XSETINT (emacs_event->x, loc * pixel_height);
5937 XSETINT (emacs_event->y, pixel_height-20);
5939 n_emacs_events_pending++;
5940 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
5941 EVENT_INIT (*emacs_event);
5942 ns_send_appdefined (-1);
5946 /* called manually thru timer to implement repeated button action w/hold-down */
5947 - repeatScroll: (NSTimer *)scrollEntry
5949 NSEvent *e = [[self window] currentEvent];
5950 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
5951 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
5953 /* clear timer if need be */
5954 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
5956 [scroll_repeat_entry invalidate];
5957 [scroll_repeat_entry release];
5958 scroll_repeat_entry = nil;
5964 = [[NSTimer scheduledTimerWithTimeInterval:
5965 SCROLL_BAR_CONTINUOUS_DELAY
5967 selector: @selector (repeatScroll:)
5973 [self sendScrollEventAtLoc: 0 fromEvent: e];
5978 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
5979 mouseDragged events without going into a modal loop. */
5980 - (void)mouseDown: (NSEvent *)e
5983 /* hitPart is only updated AFTER event is passed on */
5984 NSScrollerPart part = [self testPart: [e locationInWindow]];
5985 double inc = 0.0, loc, kloc, pos;
5988 NSTRACE (EmacsScroller_mouseDown);
5992 case NSScrollerDecrementPage:
5993 last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
5994 case NSScrollerIncrementPage:
5995 last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
5996 case NSScrollerDecrementLine:
5997 last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
5998 case NSScrollerIncrementLine:
5999 last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
6000 case NSScrollerKnob:
6001 last_hit_part = scroll_bar_handle; break;
6002 case NSScrollerKnobSlot: /* GNUstep-only */
6003 last_hit_part = scroll_bar_move_ratio; break;
6004 default: /* NSScrollerNoPart? */
6005 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %d\n", part);
6011 pos = 0; /* ignored */
6013 /* set a timer to repeat, as we can't let superclass do this modally */
6015 = [[NSTimer scheduledTimerWithTimeInterval: 0.5
6017 selector: @selector (repeatScroll:)
6024 /* handle, or on GNUstep possibly slot */
6025 NSEvent *fake_event;
6027 /* compute float loc in slot and mouse offset on knob */
6028 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6030 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6036 else if (loc >= NSHeight (sr))
6038 loc = NSHeight (sr);
6046 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
6048 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
6050 last_mouse_offset = kloc;
6052 /* if knob, tell emacs a location offset by knob pos
6053 (to indicate top of handle) */
6054 if (part == NSScrollerKnob)
6055 pos = (loc - last_mouse_offset) / NSHeight (sr);
6057 /* else this is a slot click on GNUstep: go straight there */
6058 pos = loc / NSHeight (sr);
6060 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
6061 fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
6062 location: [e locationInWindow]
6063 modifierFlags: [e modifierFlags]
6064 timestamp: [e timestamp]
6065 windowNumber: [e windowNumber]
6066 context: [e context]
6067 eventNumber: [e eventNumber]
6068 clickCount: [e clickCount]
6069 pressure: [e pressure]];
6070 [super mouseUp: fake_event];
6073 if (part != NSScrollerKnob)
6074 [self sendScrollEventAtLoc: pos fromEvent: e];
6078 /* Called as we manually track scroller drags, rather than superclass. */
6079 - (void)mouseDragged: (NSEvent *)e
6085 NSTRACE (EmacsScroller_mouseDragged);
6087 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6089 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6096 else if (loc >= NSHeight (sr) + last_mouse_offset)
6098 loc = NSHeight (sr) + last_mouse_offset;
6102 pos = /*(edge ? loc :*/ (loc - last_mouse_offset) / NSHeight (sr);
6103 [self sendScrollEventAtLoc: pos fromEvent: e];
6107 - (void)mouseUp: (NSEvent *)e
6109 if (scroll_repeat_entry)
6111 [scroll_repeat_entry invalidate];
6112 [scroll_repeat_entry release];
6113 scroll_repeat_entry = nil;
6119 /* treat scrollwheel events in the bar as though they were in the main window */
6120 - (void) scrollWheel: (NSEvent *)theEvent
6122 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
6123 [view mouseDown: theEvent];
6126 @end /* EmacsScroller */
6131 /* ==========================================================================
6133 Font-related functions; these used to be in nsfaces.m
6135 ========================================================================== */
6139 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
6141 struct font *font = XFONT_OBJECT (font_object);
6144 fontset = fontset_from_font (font_object);
6145 FRAME_FONTSET (f) = fontset;
6147 if (FRAME_FONT (f) == font)
6148 /* This font is already set in frame F. There's nothing more to
6152 FRAME_FONT (f) = font;
6154 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
6155 FRAME_COLUMN_WIDTH (f) = font->average_width;
6156 FRAME_SPACE_WIDTH (f) = font->space_width;
6157 FRAME_LINE_HEIGHT (f) = font->height;
6159 compute_fringe_widths (f, 1);
6161 /* Compute the scroll bar width in character columns. */
6162 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
6164 int wid = FRAME_COLUMN_WIDTH (f);
6165 FRAME_CONFIG_SCROLL_BAR_COLS (f)
6166 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
6170 int wid = FRAME_COLUMN_WIDTH (f);
6171 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
6174 /* Now make the frame display the given font. */
6175 if (FRAME_NS_WINDOW (f) != 0)
6176 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
6182 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
6183 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
6187 ns_xlfd_to_fontname (const char *xlfd)
6188 /* --------------------------------------------------------------------------
6189 Convert an X font name (XLFD) to an NS font name.
6190 Only family is used.
6191 The string returned is temporarily allocated.
6192 -------------------------------------------------------------------------- */
6194 char *name = xmalloc (180);
6198 if (!strncmp (xlfd, "--", 2))
6199 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
6201 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
6203 /* stopgap for malformed XLFD input */
6204 if (strlen (name) == 0)
6205 strcpy (name, "Monaco");
6207 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
6208 also uppercase after '-' or ' ' */
6209 name[0] = toupper (name[0]);
6210 for (len =strlen (name), i =0; i<len; i++)
6216 name[i+1] = toupper (name[i+1]);
6218 else if (name[i] == '_')
6222 name[i+1] = toupper (name[i+1]);
6225 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
6226 ret = [[NSString stringWithUTF8String: name] UTF8String];
6235 NSTRACE (syms_of_nsterm);
6236 DEFVAR_LISP ("ns-input-file", &ns_input_file,
6237 "The file specified in the last NS event.");
6238 ns_input_file =Qnil;
6240 DEFVAR_LISP ("ns-input-text", &ns_input_text,
6241 "The data received in the last NS text drag event.");
6242 ns_input_text =Qnil;
6244 DEFVAR_LISP ("ns-working-text", &ns_working_text,
6245 "String for visualizing working composition sequence.");
6246 ns_working_text =Qnil;
6248 DEFVAR_LISP ("ns-input-font", &ns_input_font,
6249 "The font specified in the last NS event.");
6250 ns_input_font =Qnil;
6252 DEFVAR_LISP ("ns-input-fontsize", &ns_input_fontsize,
6253 "The fontsize specified in the last NS event.");
6254 ns_input_fontsize =Qnil;
6256 DEFVAR_LISP ("ns-input-line", &ns_input_line,
6257 "The line specified in the last NS event.");
6258 ns_input_line =Qnil;
6260 DEFVAR_LISP ("ns-input-color", &ns_input_color,
6261 "The color specified in the last NS event.");
6262 ns_input_color =Qnil;
6264 DEFVAR_LISP ("ns-input-spi-name", &ns_input_spi_name,
6265 "The service name specified in the last NS event.");
6266 ns_input_spi_name =Qnil;
6268 DEFVAR_LISP ("ns-input-spi-arg", &ns_input_spi_arg,
6269 "The service argument specified in the last NS event.");
6270 ns_input_spi_arg =Qnil;
6272 DEFVAR_LISP ("ns-alternate-modifier", &ns_alternate_modifier,
6273 "This variable describes the behavior of the alternate or option key.\n\
6274 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6275 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6276 at all, allowing it to be used at a lower level for accented character entry.");
6278 DEFVAR_LISP ("ns-command-modifier", &ns_command_modifier,
6279 "This variable describes the behavior of the command key.\n\
6280 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6282 DEFVAR_LISP ("ns-control-modifier", &ns_control_modifier,
6283 "This variable describes the behavior of the control key.\n\
6284 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6286 DEFVAR_LISP ("ns-function-modifier", &ns_function_modifier,
6287 "This variable describes the behavior of the function key (on laptops).\n\
6288 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6289 Set to none means that the function key is not interpreted by Emacs at all,\n\
6290 allowing it to be used at a lower level for accented character entry.");
6292 DEFVAR_LISP ("ns-antialias-text", &ns_antialias_text,
6293 "Non-nil (the default) means to render text antialiased. Only has an effect on OS X Panther and above.");
6295 DEFVAR_LISP ("ns-use-qd-smoothing", &ns_use_qd_smoothing,
6296 "Whether to render text using QuickDraw (less heavy) antialiasing. Only has an effect on OS X Panther and above. Default is nil (use Quartz smoothing).");
6298 DEFVAR_LISP ("ns-use-system-highlight-color",
6299 &ns_use_system_highlight_color,
6300 "Whether to use the system default (on OS X only) for the highlight color. Nil means to use standard emacs (prior to version 21) 'grey'.");
6302 DEFVAR_LISP ("ns-confirm-quit", &ns_confirm_quit,
6303 "Whether to confirm application quit using dialog.");
6305 staticpro (&ns_display_name_list);
6306 ns_display_name_list = Qnil;
6308 staticpro (&last_mouse_motion_frame);
6309 last_mouse_motion_frame = Qnil;
6311 /* from 23+ we need to tell emacs what modifiers there are.. */
6312 Qmodifier_value = intern ("modifier-value");
6313 Qalt = intern ("alt");
6314 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
6315 Qhyper = intern ("hyper");
6316 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
6317 Qmeta = intern ("meta");
6318 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
6319 Qsuper = intern ("super");
6320 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
6321 Qcontrol = intern ("control");
6322 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
6324 /* TODO: move to common code */
6325 DEFVAR_LISP ("x-toolkit-scroll-bars", &Vx_toolkit_scroll_bars,
6326 doc: /* If not nil, Emacs uses toolkit scroll bars. */);
6327 #ifdef USE_TOOLKIT_SCROLL_BARS
6328 Vx_toolkit_scroll_bars = Qt;
6330 Vx_toolkit_scroll_bars = Qnil;
6333 /* these are unsupported but we need the declarations to avoid whining
6334 messages from cus-start.el */
6335 DEFVAR_BOOL ("x-use-underline-position-properties",
6336 &x_use_underline_position_properties,
6337 doc: /* NOT SUPPORTED UNDER NS.
6338 *Non-nil means make use of UNDERLINE_POSITION font properties.
6339 A value of nil means ignore them. If you encounter fonts with bogus
6340 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
6341 to 4.1, set this to nil.
6343 NOTE: Not supported on Mac yet. */);
6344 x_use_underline_position_properties = 0;
6346 DEFVAR_BOOL ("x-underline-at-descent-line",
6347 &x_underline_at_descent_line,
6348 doc: /* NOT SUPPORTED UNDER NS.
6349 *Non-nil means to draw the underline at the same place as the descent line.
6350 A value of nil means to draw the underline according to the value of the
6351 variable `x-use-underline-position-properties', which is usually at the
6352 baseline level. The default value is nil. */);
6353 x_underline_at_descent_line = 0;
6355 /* Tell emacs about this window system. */
6356 Fprovide (intern ("ns"), Qnil);
6360 // arch-tag: 6eaa8f7d-a69b-4e1c-b43d-ab31defbe0d2