1 /* NeXT/Open/GNUstep / MacOSX communication module.
3 Copyright (C) 1989, 1993-1994, 2005-2006, 2008-2012
4 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 Originally by Carl Edman
23 Updated by Christian Limpach (chris@nice.ch)
24 OpenStep/Rhapsody port by Scott Bender (sbender@harmony-ds.com)
25 MacOSX/Aqua port by Christophe de Dinechin (descubes@earthlink.net)
26 GNUstep port and post-20 update by Adrian Robert (arobert@cogsci.ucsd.edu)
29 /* This should be the first include, as it may set up #defines affecting
30 interpretation of even the system includes. */
34 #include <sys/types.h>
41 #include "blockinput.h"
42 #include "sysselect.h"
45 #include "character.h"
47 #include "composite.h"
50 #include "termhooks.h"
61 int term_trace_num = 0;
62 #define NSTRACE(x) fprintf (stderr, "%s:%d: [%d] " #x "\n", \
63 __FILE__, __LINE__, ++term_trace_num)
68 extern NSString *NSMenuDidBeginTrackingNotification;
70 /* ==========================================================================
74 ========================================================================== */
76 /* Convert a symbol indexed with an NSxxx value to a value as defined
77 in keyboard.c (lispy_function_key). I hope this is a correct way
79 static unsigned convert_ns_to_X_keysym[] =
81 NSHomeFunctionKey, 0x50,
82 NSLeftArrowFunctionKey, 0x51,
83 NSUpArrowFunctionKey, 0x52,
84 NSRightArrowFunctionKey, 0x53,
85 NSDownArrowFunctionKey, 0x54,
86 NSPageUpFunctionKey, 0x55,
87 NSPageDownFunctionKey, 0x56,
88 NSEndFunctionKey, 0x57,
89 NSBeginFunctionKey, 0x58,
90 NSSelectFunctionKey, 0x60,
91 NSPrintFunctionKey, 0x61,
92 NSExecuteFunctionKey, 0x62,
93 NSInsertFunctionKey, 0x63,
94 NSUndoFunctionKey, 0x65,
95 NSRedoFunctionKey, 0x66,
96 NSMenuFunctionKey, 0x67,
97 NSFindFunctionKey, 0x68,
98 NSHelpFunctionKey, 0x6A,
99 NSBreakFunctionKey, 0x6B,
101 NSF1FunctionKey, 0xBE,
102 NSF2FunctionKey, 0xBF,
103 NSF3FunctionKey, 0xC0,
104 NSF4FunctionKey, 0xC1,
105 NSF5FunctionKey, 0xC2,
106 NSF6FunctionKey, 0xC3,
107 NSF7FunctionKey, 0xC4,
108 NSF8FunctionKey, 0xC5,
109 NSF9FunctionKey, 0xC6,
110 NSF10FunctionKey, 0xC7,
111 NSF11FunctionKey, 0xC8,
112 NSF12FunctionKey, 0xC9,
113 NSF13FunctionKey, 0xCA,
114 NSF14FunctionKey, 0xCB,
115 NSF15FunctionKey, 0xCC,
116 NSF16FunctionKey, 0xCD,
117 NSF17FunctionKey, 0xCE,
118 NSF18FunctionKey, 0xCF,
119 NSF19FunctionKey, 0xD0,
120 NSF20FunctionKey, 0xD1,
121 NSF21FunctionKey, 0xD2,
122 NSF22FunctionKey, 0xD3,
123 NSF23FunctionKey, 0xD4,
124 NSF24FunctionKey, 0xD5,
126 NSBackspaceCharacter, 0x08, /* 8: Not on some KBs. */
127 NSDeleteCharacter, 0xFF, /* 127: Big 'delete' key upper right. */
128 NSDeleteFunctionKey, 0x9F, /* 63272: Del forw key off main array. */
130 NSTabCharacter, 0x09,
131 0x19, 0x09, /* left tab->regular since pass shift */
132 NSCarriageReturnCharacter, 0x0D,
133 NSNewlineCharacter, 0x0D,
134 NSEnterCharacter, 0x8D,
136 0x1B, 0x1B /* escape */
139 static Lisp_Object Qmodifier_value;
140 Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper, Qnone;
141 extern Lisp_Object Qcursor_color, Qcursor_type, Qns, Qleft;
143 static Lisp_Object QUTF8_STRING;
145 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
146 the maximum font size to NOT antialias. On GNUstep there is currently
147 no way to control this behavior. */
148 float ns_antialias_threshold;
150 /* Used to pick up AppleHighlightColor on OS X */
151 NSString *ns_selection_color;
153 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
154 NSString *ns_app_name = @"Emacs"; /* default changed later */
156 /* Display variables */
157 struct ns_display_info *x_display_list; /* Chain of existing displays */
158 Lisp_Object ns_display_name_list;
159 long context_menu_value = 0;
162 NSPoint last_mouse_motion_position;
163 static NSRect last_mouse_glyph;
164 static Time last_mouse_movement_time = 0;
165 static Lisp_Object last_mouse_motion_frame;
166 static EmacsScroller *last_mouse_scroll_bar = nil;
167 static struct frame *ns_updating_frame;
168 static NSView *focus_view = NULL;
169 static int ns_window_num = 0;
171 static BOOL gsaved = NO;
172 BOOL ns_in_resize = NO;
173 static BOOL ns_fake_keydown = NO;
174 int ns_tmp_flags; /* FIXME */
175 struct nsfont_info *ns_tmp_font; /* FIXME */
176 static BOOL ns_menu_bar_is_hidden = NO;
177 /*static int debug_lock = 0; */
180 static BOOL send_appdefined = YES;
181 static NSEvent *last_appdefined_event = 0;
182 static NSTimer *timed_entry = 0;
183 static NSTimer *fd_entry = nil;
184 static NSTimer *scroll_repeat_entry = nil;
185 static fd_set select_readfds, t_readfds;
186 static struct timeval select_timeout;
187 static int select_nfds;
188 static NSAutoreleasePool *outerpool;
189 static struct input_event *emacs_event = NULL;
190 static struct input_event *q_event_ptr = NULL;
191 static int n_emacs_events_pending = 0;
192 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
193 *ns_pending_service_args;
194 static BOOL inNsSelect = 0;
196 /* Convert modifiers in a NeXTstep event to emacs style modifiers. */
197 #define NS_FUNCTION_KEY_MASK 0x800000
198 #define NSLeftControlKeyMask (0x000001 | NSControlKeyMask)
199 #define NSRightControlKeyMask (0x002000 | NSControlKeyMask)
200 #define NSLeftCommandKeyMask (0x000008 | NSCommandKeyMask)
201 #define NSRightCommandKeyMask (0x000010 | NSCommandKeyMask)
202 #define NSLeftAlternateKeyMask (0x000020 | NSAlternateKeyMask)
203 #define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
204 #define EV_MODIFIERS(e) \
205 ((([e modifierFlags] & NSHelpKeyMask) ? \
206 hyper_modifier : 0) \
207 | (!EQ (ns_right_alternate_modifier, Qleft) && \
208 (([e modifierFlags] & NSRightAlternateKeyMask) \
209 == NSRightAlternateKeyMask) ? \
210 parse_solitary_modifier (ns_right_alternate_modifier) : 0) \
211 | (([e modifierFlags] & NSAlternateKeyMask) ? \
212 parse_solitary_modifier (ns_alternate_modifier) : 0) \
213 | (([e modifierFlags] & NSShiftKeyMask) ? \
214 shift_modifier : 0) \
215 | (!EQ (ns_right_control_modifier, Qleft) && \
216 (([e modifierFlags] & NSRightControlKeyMask) \
217 == NSRightControlKeyMask) ? \
218 parse_solitary_modifier (ns_right_control_modifier) : 0) \
219 | (([e modifierFlags] & NSControlKeyMask) ? \
220 parse_solitary_modifier (ns_control_modifier) : 0) \
221 | (([e modifierFlags] & NS_FUNCTION_KEY_MASK) ? \
222 parse_solitary_modifier (ns_function_modifier) : 0) \
223 | (!EQ (ns_right_command_modifier, Qleft) && \
224 (([e modifierFlags] & NSRightCommandKeyMask) \
225 == NSRightCommandKeyMask) ? \
226 parse_solitary_modifier (ns_right_command_modifier) : 0) \
227 | (([e modifierFlags] & NSCommandKeyMask) ? \
228 parse_solitary_modifier (ns_command_modifier):0))
230 #define EV_UDMODIFIERS(e) \
231 ((([e type] == NSLeftMouseDown) ? down_modifier : 0) \
232 | (([e type] == NSRightMouseDown) ? down_modifier : 0) \
233 | (([e type] == NSOtherMouseDown) ? down_modifier : 0) \
234 | (([e type] == NSLeftMouseDragged) ? down_modifier : 0) \
235 | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
236 | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
237 | (([e type] == NSLeftMouseUp) ? up_modifier : 0) \
238 | (([e type] == NSRightMouseUp) ? up_modifier : 0) \
239 | (([e type] == NSOtherMouseUp) ? up_modifier : 0))
241 #define EV_BUTTON(e) \
242 ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 : \
243 (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
244 [e buttonNumber] - 1)
246 /* Convert the time field to a timestamp in milliseconds. */
247 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
249 /* This is a piece of code which is common to all the event handling
250 methods. Maybe it should even be a function. */
251 #define EV_TRAILER(e) \
253 XSETFRAME (emacs_event->frame_or_window, emacsframe); \
254 if (e) emacs_event->timestamp = EV_TIMESTAMP (e); \
255 n_emacs_events_pending++; \
256 kbd_buffer_store_event_hold (emacs_event, q_event_ptr); \
257 EVENT_INIT (*emacs_event); \
258 ns_send_appdefined (-1); \
261 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
263 /* TODO: get rid of need for these forward declarations */
264 static void ns_condemn_scroll_bars (struct frame *f);
265 static void ns_judge_scroll_bars (struct frame *f);
266 void x_set_frame_alpha (struct frame *f);
269 /* ==========================================================================
273 ========================================================================== */
277 append2 (Lisp_Object list, Lisp_Object item)
278 /* --------------------------------------------------------------------------
279 Utility to append to a list
280 -------------------------------------------------------------------------- */
282 Lisp_Object array[2];
284 array[1] = Fcons (item, Qnil);
285 return Fnconc (2, &array[0]);
291 /* --------------------------------------------------------------------------
292 Used to allow emacs to find its resources under Emacs.app
293 Called from emacs.c at startup.
294 -------------------------------------------------------------------------- */
296 NSBundle *bundle = [NSBundle mainBundle];
297 NSString *binDir = [bundle bundlePath], *resourceDir = [bundle resourcePath];
298 NSString *resourcePath, *resourcePaths;
300 BOOL onWindows = NO; /* how do I determine this? */
301 NSString *pathSeparator = onWindows ? @";" : @":";
302 NSFileManager *fileManager = [NSFileManager defaultManager];
304 /*NSLog (@"ns_init_paths: '%@'\n%@\n", [[NSBundle mainBundle] bundlePath], [[NSBundle mainBundle] resourcePath]); */
306 /* get bindir from base */
307 range = [resourceDir rangeOfString: @"Contents"];
308 if (range.location != NSNotFound)
310 binDir = [binDir stringByAppendingPathComponent: @"Contents"];
312 binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
316 /* the following based on Andrew Choi's init_mac_osx_environment () */
317 if (!getenv ("EMACSLOADPATH"))
319 NSArray *paths = [resourceDir stringsByAppendingPaths:
320 [NSArray arrayWithObjects:
321 @"site-lisp", @"lisp", @"leim", nil]];
322 NSEnumerator *pathEnum = [paths objectEnumerator];
324 while (resourcePath = [pathEnum nextObject])
326 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
329 if ([resourcePaths length] > 0)
331 = [resourcePaths stringByAppendingString: pathSeparator];
333 = [resourcePaths stringByAppendingString: resourcePath];
336 if ([resourcePaths length] > 0)
337 setenv ("EMACSLOADPATH", [resourcePaths UTF8String], 1);
338 /*NSLog (@"loadPath: '%@'\n", resourcePaths); */
341 /* Normally, Emacs does not add its own bin/ directory to the PATH.
342 However, a self-contained NS build has a different layout, with
343 bin/ and libexec/ subdirectories in the directory that contains
345 We put libexec first, because init_callproc_1 uses the first
346 element to initialize exec-directory. An alternative would be
347 for init_callproc to check for invocation-directory/libexec. */
348 if (!getenv ("EMACSPATH"))
350 NSArray *paths = [binDir stringsByAppendingPaths:
351 [NSArray arrayWithObjects: @"libexec",
353 NSEnumerator *pathEnum = [paths objectEnumerator];
355 while (resourcePath = [pathEnum nextObject])
357 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
360 if ([resourcePaths length] > 0)
362 = [resourcePaths stringByAppendingString: pathSeparator];
364 = [resourcePaths stringByAppendingString: resourcePath];
367 if ([resourcePaths length] > 0)
368 setenv ("EMACSPATH", [resourcePaths UTF8String], 1);
371 resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
372 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
376 if (!getenv ("EMACSDATA"))
377 setenv ("EMACSDATA", [resourcePath UTF8String], 1);
378 if (!getenv ("EMACSDOC"))
379 setenv ("EMACSDOC", [resourcePath UTF8String], 1);
383 if (!getenv ("INFOPATH"))
385 resourcePath = [resourceDir stringByAppendingPathComponent: @"info"];
386 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
388 setenv ("INFOPATH", [[resourcePath stringByAppendingString: @":"]
390 /* Note, extra colon needed to cause merge w/later user additions. */
396 timeval_subtract (struct timeval *result, struct timeval x, struct timeval y)
397 /* --------------------------------------------------------------------------
398 Subtract the `struct timeval' values X and Y, storing the result in RESULT.
399 Return 1 if the difference is negative, otherwise 0.
400 -------------------------------------------------------------------------- */
402 /* Perform the carry for the later subtraction by updating y.
403 This is safer because on some systems
404 the tv_sec member is unsigned. */
405 if (x.tv_usec < y.tv_usec)
407 int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
408 y.tv_usec -= 1000000 * nsec;
411 if (x.tv_usec - y.tv_usec > 1000000)
413 int nsec = (y.tv_usec - x.tv_usec) / 1000000;
414 y.tv_usec += 1000000 * nsec;
418 /* Compute the time remaining to wait. tv_usec is certainly positive. */
419 result->tv_sec = x.tv_sec - y.tv_sec;
420 result->tv_usec = x.tv_usec - y.tv_usec;
422 /* Return indication of whether the result should be considered negative. */
423 return x.tv_sec < y.tv_sec;
427 ns_timeout (int usecs)
428 /* --------------------------------------------------------------------------
429 Blocking timer utility used by ns_ring_bell
430 -------------------------------------------------------------------------- */
432 struct timeval wakeup;
434 EMACS_GET_TIME (wakeup);
436 /* Compute time to wait until, propagating carry from usecs. */
437 wakeup.tv_usec += usecs;
438 wakeup.tv_sec += (wakeup.tv_usec / 1000000);
439 wakeup.tv_usec %= 1000000;
441 /* Keep waiting until past the time wakeup. */
444 struct timeval timeout;
446 EMACS_GET_TIME (timeout);
448 /* In effect, timeout = wakeup - timeout.
449 Break if result would be negative. */
450 if (timeval_subtract (&timeout, wakeup, timeout))
453 /* Try to wait that long--but we might wake up sooner. */
454 select (0, NULL, NULL, NULL, &timeout);
460 ns_release_object (void *obj)
461 /* --------------------------------------------------------------------------
462 Release an object (callable from C)
463 -------------------------------------------------------------------------- */
470 ns_retain_object (void *obj)
471 /* --------------------------------------------------------------------------
472 Retain an object (callable from C)
473 -------------------------------------------------------------------------- */
480 ns_alloc_autorelease_pool (void)
481 /* --------------------------------------------------------------------------
482 Allocate a pool for temporary objects (callable from C)
483 -------------------------------------------------------------------------- */
485 return [[NSAutoreleasePool alloc] init];
490 ns_release_autorelease_pool (void *pool)
491 /* --------------------------------------------------------------------------
492 Free a pool and temporary objects it refers to (callable from C)
493 -------------------------------------------------------------------------- */
495 ns_release_object (pool);
500 /* ==========================================================================
502 Focus (clipping) and screen update
504 ========================================================================== */
507 ns_resize_handle_rect (NSWindow *window)
509 NSRect r = [window frame];
510 r.origin.x = r.size.width - RESIZE_HANDLE_SIZE;
512 r.size.width = r.size.height = RESIZE_HANDLE_SIZE;
518 // Window constraining
519 // -------------------
521 // To ensure that the windows are not placed under the menu bar, they
522 // are typically moved by the call-back constrainFrameRect. However,
523 // by overriding it, it's possible to inhibit this, leaving the window
524 // in it's original position.
526 // It's possible to hide the menu bar. However, technically, it's only
527 // possible to hide it when the application is active. To ensure that
528 // this work properly, the menu bar and window constraining are
529 // deferred until the application becomes active.
531 // Even though it's not possible to manually move a window above the
532 // top of the screen, it is allowed if it's done programmatically,
533 // when the menu is hidden. This allows the editable area to cover the
534 // full screen height.
539 // Use the following extra files:
542 // ;; Hide menu and place frame slightly above the top of the screen.
543 // (setq ns-auto-hide-menu-bar t)
544 // (set-frame-position (selected-frame) 0 -20)
548 // emacs -Q -l init.el
550 // Result: No menu bar, and the title bar should be above the screen.
556 // Result: Menu bar visible, frame placed immediately below the menu.
560 ns_constrain_all_frames (void)
562 Lisp_Object tail, frame;
564 FOR_EACH_FRAME (tail, frame)
566 struct frame *f = XFRAME (frame);
569 NSView *view = FRAME_NS_VIEW (f);
570 /* This no-op will trigger the default window placing
571 * constraint system. */
572 f->output_data.ns->dont_constrain = 0;
573 [[view window] setFrameOrigin:[[view window] frame].origin];
579 /* True, if the menu bar should be hidden. */
582 ns_menu_bar_should_be_hidden (void)
584 return !NILP (ns_auto_hide_menu_bar)
585 && [NSApp respondsToSelector:@selector(setPresentationOptions:)];
589 /* Show or hide the menu bar, based on user setting. */
592 ns_update_auto_hide_menu_bar (void)
594 #ifndef MAC_OS_X_VERSION_10_6
595 #define MAC_OS_X_VERSION_10_6 1060
598 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
601 NSTRACE (ns_update_auto_hide_menu_bar);
605 && [NSApp respondsToSelector:@selector(setPresentationOptions:)])
607 // Note, "setPresentationOptions" triggers an error unless the
608 // application is active.
609 BOOL menu_bar_should_be_hidden = ns_menu_bar_should_be_hidden ();
611 if (menu_bar_should_be_hidden != ns_menu_bar_is_hidden)
613 NSApplicationPresentationOptions options
614 = NSApplicationPresentationAutoHideDock;
616 if (menu_bar_should_be_hidden)
617 options |= NSApplicationPresentationAutoHideMenuBar;
619 [NSApp setPresentationOptions: options];
621 ns_menu_bar_is_hidden = menu_bar_should_be_hidden;
623 if (!ns_menu_bar_is_hidden)
625 ns_constrain_all_frames ();
637 ns_update_begin (struct frame *f)
638 /* --------------------------------------------------------------------------
639 Prepare for a grouped sequence of drawing calls
640 external (RIF) call; whole frame, called before update_window_begin
641 -------------------------------------------------------------------------- */
643 NSView *view = FRAME_NS_VIEW (f);
644 NSTRACE (ns_update_begin);
646 ns_update_auto_hide_menu_bar ();
648 ns_updating_frame = f;
651 #ifdef NS_IMPL_GNUSTEP
652 uRect = NSMakeRect (0, 0, 0, 0);
658 ns_update_window_begin (struct window *w)
659 /* --------------------------------------------------------------------------
660 Prepare for a grouped sequence of drawing calls
661 external (RIF) call; for one window, called after update_begin
662 -------------------------------------------------------------------------- */
664 struct frame *f = XFRAME (WINDOW_FRAME (w));
665 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
666 NSTRACE (ns_update_window_begin);
669 set_output_cursor (&w->cursor);
673 if (f == hlinfo->mouse_face_mouse_frame)
675 /* Don't do highlighting for mouse motion during the update. */
676 hlinfo->mouse_face_defer = 1;
678 /* If the frame needs to be redrawn,
679 simply forget about any prior mouse highlighting. */
680 if (FRAME_GARBAGED_P (f))
681 hlinfo->mouse_face_window = Qnil;
683 /* (further code for mouse faces ifdef'd out in other terms elided) */
691 ns_update_window_end (struct window *w, int cursor_on_p,
692 int mouse_face_overwritten_p)
693 /* --------------------------------------------------------------------------
694 Finished a grouped sequence of drawing calls
695 external (RIF) call; for one window called before update_end
696 -------------------------------------------------------------------------- */
698 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (XFRAME (w->frame));
700 /* note: this fn is nearly identical in all terms */
701 if (!w->pseudo_window_p)
706 display_and_set_cursor (w, 1,
707 output_cursor.hpos, output_cursor.vpos,
708 output_cursor.x, output_cursor.y);
710 if (draw_window_fringes (w, 1))
711 x_draw_vertical_border (w);
716 /* If a row with mouse-face was overwritten, arrange for
717 frame_up_to_date to redisplay the mouse highlight. */
718 if (mouse_face_overwritten_p)
720 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
721 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
722 hlinfo->mouse_face_window = Qnil;
725 updated_window = NULL;
726 NSTRACE (update_window_end);
731 ns_update_end (struct frame *f)
732 /* --------------------------------------------------------------------------
733 Finished a grouped sequence of drawing calls
734 external (RIF) call; for whole frame, called after update_window_end
735 -------------------------------------------------------------------------- */
737 NSView *view = FRAME_NS_VIEW (f);
739 /* if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
740 MOUSE_HL_INFO (f)->mouse_face_defer = 0;
744 #ifdef NS_IMPL_GNUSTEP
745 /* trigger flush only in the rectangle we tracked as being drawn */
746 [view unlockFocusNeedsFlush: NO];
747 /*fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", uRect.origin.x, uRect.origin.y, uRect.size.width, uRect.size.height); */
748 [view lockFocusInRect: uRect];
752 [[view window] flushWindow];
755 ns_updating_frame = NULL;
756 NSTRACE (ns_update_end);
761 ns_flush (struct frame *f)
762 /* --------------------------------------------------------------------------
764 NS impl is no-op since currently we flush in ns_update_end and elsewhere
765 -------------------------------------------------------------------------- */
772 ns_focus (struct frame *f, NSRect *r, int n)
773 /* --------------------------------------------------------------------------
774 Internal: Focus on given frame. During small local updates this is used to
775 draw, however during large updates, ns_update_begin and ns_update_end are
776 called to wrap the whole thing, in which case these calls are stubbed out.
777 Except, on GNUstep, we accumulate the rectangle being drawn into, because
778 the back end won't do this automatically, and will just end up flushing
780 -------------------------------------------------------------------------- */
782 // NSTRACE (ns_focus);
783 #ifdef NS_IMPL_GNUSTEP
786 u = NSUnionRect (r[0], r[1]);
791 fprintf (stderr, "focus: %d", c++);
792 if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
793 fprintf (stderr, "\n"); */
795 if (f != ns_updating_frame)
797 NSView *view = FRAME_NS_VIEW (f);
798 if (view != focus_view)
800 if (focus_view != NULL)
802 [focus_view unlockFocus];
803 [[focus_view window] flushWindow];
808 #ifdef NS_IMPL_GNUSTEP
809 r ? [view lockFocusInRect: u] : [view lockFocus];
814 /*if (view) debug_lock++; */
816 #ifdef NS_IMPL_GNUSTEP
819 /* more than one rect being drawn into */
822 [view unlockFocus]; /* add prev rect to redraw list */
823 [view lockFocusInRect: u]; /* focus for draw in new rect */
828 #ifdef NS_IMPL_GNUSTEP
831 /* in batch mode, but in GNUstep must still track rectangles explicitly */
832 uRect = (r ? NSUnionRect (uRect, u) : [FRAME_NS_VIEW (f) visibleRect]);
839 [[NSGraphicsContext currentContext] saveGraphicsState];
841 NSRectClipList (r, 2);
850 ns_unfocus (struct frame *f)
851 /* --------------------------------------------------------------------------
852 Internal: Remove focus on given frame
853 -------------------------------------------------------------------------- */
855 // NSTRACE (ns_unfocus);
859 [[NSGraphicsContext currentContext] restoreGraphicsState];
863 if (f != ns_updating_frame)
865 if (focus_view != NULL)
867 [focus_view unlockFocus];
868 [[focus_view window] flushWindow];
877 ns_clip_to_row (struct window *w, struct glyph_row *row, int area, BOOL gc)
878 /* --------------------------------------------------------------------------
879 Internal (but parallels other terms): Focus drawing on given row
880 -------------------------------------------------------------------------- */
882 struct frame *f = XFRAME (WINDOW_FRAME (w));
884 int window_x, window_y, window_width;
886 window_box (w, area, &window_x, &window_y, &window_width, 0);
888 clip_rect.origin.x = window_x - FRAME_INTERNAL_BORDER_WIDTH (f);
889 clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
890 clip_rect.origin.y = max (clip_rect.origin.y, window_y);
891 clip_rect.size.width = window_width + 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
892 clip_rect.size.height = row->visible_height;
894 /* allow a full-height row at the top when requested
895 (used to draw fringe all the way through internal border area) */
896 if (gc && clip_rect.origin.y < 5)
898 clip_rect.origin.y -= FRAME_INTERNAL_BORDER_WIDTH (f);
899 clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
902 /* likewise at bottom */
904 FRAME_PIXEL_HEIGHT (f) - (clip_rect.origin.y + clip_rect.size.height) < 5)
905 clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
907 ns_focus (f, &clip_rect, 1);
912 ns_ring_bell (struct frame *f)
913 /* --------------------------------------------------------------------------
915 -------------------------------------------------------------------------- */
917 NSTRACE (ns_ring_bell);
920 NSAutoreleasePool *pool;
921 struct frame *frame = SELECTED_FRAME ();
925 pool = [[NSAutoreleasePool alloc] init];
927 view = FRAME_NS_VIEW (frame);
931 NSPoint dim = NSMakePoint (128, 128);
934 r.origin.x += (r.size.width - dim.x) / 2;
935 r.origin.y += (r.size.height - dim.y) / 2;
936 r.size.width = dim.x;
937 r.size.height = dim.y;
938 surr = NSInsetRect (r, -2, -2);
939 ns_focus (frame, &surr, 1);
940 [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
941 [ns_lookup_indexed_color (NS_FACE_FOREGROUND
942 (FRAME_DEFAULT_FACE (frame)), frame) set];
944 [[view window] flushWindow];
946 [[view window] restoreCachedImage];
947 [[view window] flushWindow];
961 ns_reset_terminal_modes (struct terminal *terminal)
962 /* Externally called as hook */
964 NSTRACE (ns_reset_terminal_modes);
969 ns_set_terminal_modes (struct terminal *terminal)
970 /* Externally called as hook */
972 NSTRACE (ns_set_terminal_modes);
977 /* ==========================================================================
979 Frame / window manager related functions
981 ========================================================================== */
985 ns_raise_frame (struct frame *f)
986 /* --------------------------------------------------------------------------
987 Bring window to foreground and make it active
988 -------------------------------------------------------------------------- */
990 NSView *view = FRAME_NS_VIEW (f);
993 FRAME_SAMPLE_VISIBILITY (f);
994 if (FRAME_VISIBLE_P (f))
996 [[view window] makeKeyAndOrderFront: NSApp];
1003 ns_lower_frame (struct frame *f)
1004 /* --------------------------------------------------------------------------
1006 -------------------------------------------------------------------------- */
1008 NSView *view = FRAME_NS_VIEW (f);
1011 [[view window] orderBack: NSApp];
1017 ns_frame_raise_lower (struct frame *f, int raise)
1018 /* --------------------------------------------------------------------------
1020 -------------------------------------------------------------------------- */
1022 NSTRACE (ns_frame_raise_lower);
1032 ns_frame_rehighlight (struct frame *frame)
1033 /* --------------------------------------------------------------------------
1034 External (hook): called on things like window switching within frame
1035 -------------------------------------------------------------------------- */
1037 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
1038 struct frame *old_highlight = dpyinfo->x_highlight_frame;
1040 NSTRACE (ns_frame_rehighlight);
1041 if (dpyinfo->x_focus_frame)
1043 dpyinfo->x_highlight_frame
1044 = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1045 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1046 : dpyinfo->x_focus_frame);
1047 if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
1049 FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
1050 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
1054 dpyinfo->x_highlight_frame = 0;
1056 if (dpyinfo->x_highlight_frame &&
1057 dpyinfo->x_highlight_frame != old_highlight)
1061 x_update_cursor (old_highlight, 1);
1062 x_set_frame_alpha (old_highlight);
1064 if (dpyinfo->x_highlight_frame)
1066 x_update_cursor (dpyinfo->x_highlight_frame, 1);
1067 x_set_frame_alpha (dpyinfo->x_highlight_frame);
1074 x_make_frame_visible (struct frame *f)
1075 /* --------------------------------------------------------------------------
1076 External: Show the window (X11 semantics)
1077 -------------------------------------------------------------------------- */
1079 NSTRACE (x_make_frame_visible);
1080 /* XXX: at some points in past this was not needed, as the only place that
1081 called this (frame.c:Fraise_frame ()) also called raise_lower;
1082 if this ends up the case again, comment this out again. */
1083 if (!FRAME_VISIBLE_P (f))
1085 f->async_visible = 1;
1092 x_make_frame_invisible (struct frame *f)
1093 /* --------------------------------------------------------------------------
1094 External: Hide the window (X11 semantics)
1095 -------------------------------------------------------------------------- */
1097 NSView * view = FRAME_NS_VIEW (f);
1098 NSTRACE (x_make_frame_invisible);
1100 [[view window] orderOut: NSApp];
1101 f->async_visible = 0;
1102 f->async_iconified = 0;
1107 x_iconify_frame (struct frame *f)
1108 /* --------------------------------------------------------------------------
1109 External: Iconify window
1110 -------------------------------------------------------------------------- */
1112 NSView * view = FRAME_NS_VIEW (f);
1113 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1114 NSTRACE (x_iconify_frame);
1117 if (dpyinfo->x_highlight_frame == f)
1118 dpyinfo->x_highlight_frame = 0;
1120 if ([[view window] windowNumber] <= 0)
1122 /* the window is still deferred. Make it very small, bring it
1123 on screen and order it out. */
1124 NSRect s = { { 100, 100}, {0, 0} };
1126 t = [[view window] frame];
1127 [[view window] setFrame: s display: NO];
1128 [[view window] orderBack: NSApp];
1129 [[view window] orderOut: NSApp];
1130 [[view window] setFrame: t display: NO];
1132 [[view window] miniaturize: NSApp];
1135 /* Free X resources of frame F. */
1138 x_free_frame_resources (struct frame *f)
1140 NSView *view = FRAME_NS_VIEW (f);
1141 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1142 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1143 NSTRACE (x_destroy_window);
1146 [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1150 free_frame_menubar (f);
1152 if (FRAME_FACE_CACHE (f))
1153 free_frame_faces (f);
1155 if (f == dpyinfo->x_focus_frame)
1156 dpyinfo->x_focus_frame = 0;
1157 if (f == dpyinfo->x_highlight_frame)
1158 dpyinfo->x_highlight_frame = 0;
1159 if (f == hlinfo->mouse_face_mouse_frame)
1161 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
1162 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
1163 hlinfo->mouse_face_window = Qnil;
1164 hlinfo->mouse_face_deferred_gc = 0;
1165 hlinfo->mouse_face_mouse_frame = 0;
1168 xfree (f->output_data.ns);
1170 if (f->output_data.ns->miniimage != nil)
1171 [f->output_data.ns->miniimage release];
1173 [[view window] close];
1180 x_destroy_window (struct frame *f)
1181 /* --------------------------------------------------------------------------
1182 External: Delete the window
1183 -------------------------------------------------------------------------- */
1185 NSTRACE (x_destroy_window);
1187 x_free_frame_resources (f);
1193 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1194 /* --------------------------------------------------------------------------
1195 External: Position the window
1196 -------------------------------------------------------------------------- */
1198 NSView *view = FRAME_NS_VIEW (f);
1199 NSArray *screens = [NSScreen screens];
1200 NSScreen *fscreen = [screens objectAtIndex: 0];
1201 NSScreen *screen = [[view window] screen];
1203 NSTRACE (x_set_offset);
1210 if (view != nil && screen && fscreen)
1212 f->left_pos = f->size_hint_flags & XNegative
1213 ? [screen visibleFrame].size.width + f->left_pos - FRAME_PIXEL_WIDTH (f)
1215 /* We use visibleFrame here to take menu bar into account.
1216 Ideally we should also adjust left/top with visibleFrame.origin. */
1218 f->top_pos = f->size_hint_flags & YNegative
1219 ? ([screen visibleFrame].size.height + f->top_pos
1220 - FRAME_PIXEL_HEIGHT (f) - FRAME_NS_TITLEBAR_HEIGHT (f)
1221 - FRAME_TOOLBAR_HEIGHT (f))
1223 #ifdef NS_IMPL_GNUSTEP
1224 if (f->left_pos < 100)
1225 f->left_pos = 100; /* don't overlap menu */
1227 /* Constrain the setFrameTopLeftPoint so we don't move behind the
1229 f->output_data.ns->dont_constrain = 0;
1230 [[view window] setFrameTopLeftPoint:
1231 NSMakePoint (SCREENMAXBOUND (f->left_pos),
1232 SCREENMAXBOUND ([fscreen frame].size.height
1233 - NS_TOP_POS (f)))];
1234 f->size_hint_flags &= ~(XNegative|YNegative);
1242 x_set_window_size (struct frame *f, int change_grav, int cols, int rows)
1243 /* --------------------------------------------------------------------------
1244 Adjust window pixel size based on given character grid size
1245 Impl is a bit more complex than other terms, need to do some
1247 -------------------------------------------------------------------------- */
1249 EmacsView *view = FRAME_NS_VIEW (f);
1250 EmacsToolbar *toolbar = [view toolbar];
1251 NSWindow *window = [view window];
1252 NSRect wr = [window frame];
1253 int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1254 int pixelwidth, pixelheight;
1255 static int oldRows, oldCols, oldFontWidth, oldFontHeight;
1257 static struct frame *oldF;
1259 NSTRACE (x_set_window_size);
1263 && rows == oldRows && cols == oldCols
1264 && oldFontWidth == FRAME_COLUMN_WIDTH (f)
1265 && oldFontHeight == FRAME_LINE_HEIGHT (f)
1269 /*fprintf (stderr, "\tsetWindowSize: %d x %d, font size %d x %d\n", cols, rows, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f)); */
1273 check_frame_size (f, &rows, &cols);
1277 oldFontWidth = FRAME_COLUMN_WIDTH (f);
1278 oldFontHeight = FRAME_LINE_HEIGHT (f);
1281 f->scroll_bar_actual_width = NS_SCROLL_BAR_WIDTH (f);
1282 compute_fringe_widths (f, 0);
1284 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols);
1285 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
1287 /* If we have a toolbar, take its height into account. */
1289 /* NOTE: previously this would generate wrong result if toolbar not
1290 yet displayed and fixing toolbar_height=32 helped, but
1291 now (200903) seems no longer needed */
1292 FRAME_TOOLBAR_HEIGHT (f) =
1293 NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1294 - FRAME_NS_TITLEBAR_HEIGHT (f);
1296 FRAME_TOOLBAR_HEIGHT (f) = 0;
1298 wr.size.width = pixelwidth + f->border_width;
1299 wr.size.height = pixelheight + FRAME_NS_TITLEBAR_HEIGHT (f)
1300 + FRAME_TOOLBAR_HEIGHT (f);
1302 /* Do not try to constrain to this screen. We may have multiple
1303 screens, and want Emacs to span those. Constraining to screen
1304 prevents that, and that is not nice to the user. */
1305 if (f->output_data.ns->zooming)
1306 f->output_data.ns->zooming = 0;
1308 wr.origin.y += FRAME_PIXEL_HEIGHT (f) - pixelheight;
1310 [view setRows: rows andColumns: cols];
1311 [window setFrame: wr display: YES];
1313 /*fprintf (stderr, "\tx_set_window_size %d, %d\t%d, %d\n", cols, rows, pixelwidth, pixelheight); */
1315 /* This is a trick to compensate for Emacs' managing the scrollbar area
1316 as a fixed number of standard character columns. Instead of leaving
1317 blank space for the extra, we chopped it off above. Now for
1318 left-hand scrollbars, we shift all rendering to the left by the
1319 difference between the real width and Emacs' imagined one. For
1320 right-hand bars, don't worry about it since the extra is never used.
1321 (Obviously doesn't work for vertically split windows tho..) */
1323 NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1324 ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1325 - NS_SCROLL_BAR_WIDTH (f), 0)
1326 : NSMakePoint (0, 0);
1327 [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1328 [view setBoundsOrigin: origin];
1331 change_frame_size (f, rows, cols, 0, 1, 0); /* pretend, delay, safe */
1332 FRAME_PIXEL_WIDTH (f) = pixelwidth;
1333 FRAME_PIXEL_HEIGHT (f) = pixelheight;
1334 /* SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */
1336 mark_window_cursors_off (XWINDOW (f->root_window));
1337 cancel_mouse_face (f);
1344 /* ==========================================================================
1348 ========================================================================== */
1352 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1354 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1355 if (idx < 1 || idx >= color_table->avail)
1357 return color_table->colors[idx];
1362 ns_index_color (NSColor *color, struct frame *f)
1364 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1368 if (!color_table->colors)
1370 color_table->size = NS_COLOR_CAPACITY;
1371 color_table->avail = 1; /* skip idx=0 as marker */
1373 = (NSColor **)xmalloc (color_table->size * sizeof (NSColor *));
1374 color_table->colors[0] = nil;
1375 color_table->empty_indices = [[NSMutableSet alloc] init];
1378 /* do we already have this color ? */
1379 for (i = 1; i < color_table->avail; i++)
1380 if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1383 if ([color_table->empty_indices count] > 0)
1385 NSNumber *index = [color_table->empty_indices anyObject];
1386 [color_table->empty_indices removeObject: index];
1387 idx = [index unsignedLongValue];
1391 if (color_table->avail == color_table->size)
1392 color_table->colors =
1393 xpalloc (color_table->colors, &color_table->size, 1,
1394 min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1395 idx = color_table->avail++;
1398 color_table->colors[idx] = color;
1400 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1406 ns_free_indexed_color (unsigned long idx, struct frame *f)
1408 struct ns_color_table *color_table;
1415 color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1417 if (idx <= 0 || idx >= color_table->size) {
1418 message1 ("ns_free_indexed_color: Color index out of range.\n");
1422 index = [NSNumber numberWithUnsignedInt: idx];
1423 if ([color_table->empty_indices containsObject: index]) {
1424 message1 ("ns_free_indexed_color: attempt to free already freed color.\n");
1428 color = color_table->colors[idx];
1430 color_table->colors[idx] = nil;
1431 [color_table->empty_indices addObject: index];
1432 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1437 ns_get_color (const char *name, NSColor **col)
1438 /* --------------------------------------------------------------------------
1440 -------------------------------------------------------------------------- */
1441 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1442 X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1443 See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1446 static char hex[20];
1448 float r = -1.0, g, b;
1449 NSString *nsname = [NSString stringWithUTF8String: name];
1451 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1454 if ([nsname isEqualToString: @"ns_selection_color"])
1456 nsname = ns_selection_color;
1457 name = [ns_selection_color UTF8String];
1460 /* First, check for some sort of numeric specification. */
1463 if (name[0] == '0' || name[0] == '1' || name[0] == '.') /* RGB decimal */
1465 NSScanner *scanner = [NSScanner scannerWithString: nsname];
1466 [scanner scanFloat: &r];
1467 [scanner scanFloat: &g];
1468 [scanner scanFloat: &b];
1470 else if (!strncmp(name, "rgb:", 4)) /* A newer X11 format -- rgb:r/g/b */
1472 strncpy (hex, name + 4, 19);
1474 scaling = (strlen(hex) - 2) / 3;
1476 else if (name[0] == '#') /* An old X11 format; convert to newer */
1478 int len = (strlen(name) - 1);
1479 int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1481 scaling = strlen(name+start) / 3;
1482 for (i=0; i<3; i++) {
1483 strncpy(hex + i * (scaling + 1), name + start + i * scaling, scaling);
1484 hex[(i+1) * (scaling + 1) - 1] = '/';
1486 hex[3 * (scaling + 1) - 1] = '\0';
1492 float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1493 if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1503 *col = [NSColor colorWithCalibratedRed: r green: g blue: b alpha: 1.0];
1508 /* Otherwise, color is expected to be from a list */
1510 NSEnumerator *lenum, *cenum;
1514 #ifdef NS_IMPL_GNUSTEP
1515 /* XXX: who is wrong, the requestor or the implementation? */
1516 if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1518 nsname = @"highlightColor";
1521 lenum = [[NSColorList availableColorLists] objectEnumerator];
1522 while ( (clist = [lenum nextObject]) && new == nil)
1524 cenum = [[clist allKeys] objectEnumerator];
1525 while ( (name = [cenum nextObject]) && new == nil )
1527 if ([name compare: nsname
1528 options: NSCaseInsensitiveSearch] == NSOrderedSame )
1529 new = [clist colorWithKey: name];
1535 *col = [new colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1542 ns_get_color_default (const char *name, NSColor *dflt)
1543 /* --------------------------------------------------------------------------
1544 Parse a color or use a default value
1545 -------------------------------------------------------------------------- */
1549 if (ns_get_color (name, &col))
1557 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1558 /* --------------------------------------------------------------------------
1559 Convert a Lisp string object to a NS color
1560 -------------------------------------------------------------------------- */
1562 NSTRACE (ns_lisp_to_color);
1563 if (STRINGP (color))
1564 return ns_get_color (SDATA (color), col);
1565 else if (SYMBOLP (color))
1566 return ns_get_color (SDATA (SYMBOL_NAME (color)), col);
1572 ns_color_to_lisp (NSColor *col)
1573 /* --------------------------------------------------------------------------
1574 Convert a color to a lisp string with the RGB equivalent
1575 -------------------------------------------------------------------------- */
1577 CGFloat red, green, blue, alpha, gray;
1580 NSTRACE (ns_color_to_lisp);
1583 if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1585 if ((str =[[col colorNameComponent] UTF8String]))
1588 return build_string ((char *)str);
1591 [[col colorUsingColorSpaceName: NSCalibratedRGBColorSpace]
1592 getRed: &red green: &green blue: &blue alpha: &alpha];
1593 if (red ==green && red ==blue)
1595 [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1596 getWhite: &gray alpha: &alpha];
1597 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1598 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1600 return build_string (buf);
1603 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1604 lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1607 return build_string (buf);
1612 ns_query_color(void *col, XColor *color_def, int setPixel)
1613 /* --------------------------------------------------------------------------
1614 Get ARGB values out of NSColor col and put them into color_def.
1615 If setPixel, set the pixel to a concatenated version.
1616 and set color_def pixel to the resulting index.
1617 -------------------------------------------------------------------------- */
1621 [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1622 color_def->red = r * 65535;
1623 color_def->green = g * 65535;
1624 color_def->blue = b * 65535;
1626 if (setPixel == YES)
1628 = ARGB_TO_ULONG((int)(a*255),
1629 (int)(r*255), (int)(g*255), (int)(b*255));
1634 ns_defined_color (struct frame *f,
1639 /* --------------------------------------------------------------------------
1640 Return 1 if named color found, and set color_def rgb accordingly.
1641 If makeIndex and alloc are nonzero put the color in the color_table,
1642 and set color_def pixel to the resulting index.
1643 If makeIndex is zero, set color_def pixel to ARGB.
1644 Return 0 if not found
1645 -------------------------------------------------------------------------- */
1648 NSTRACE (ns_defined_color);
1651 if (ns_get_color (name, &col) != 0) /* Color not found */
1656 if (makeIndex && alloc)
1657 color_def->pixel = ns_index_color (col, f);
1658 ns_query_color (col, color_def, !makeIndex);
1665 ns_get_rgb_color (struct frame *f, float r, float g, float b, float a)
1666 /* --------------------------------------------------------------------------
1667 return an autoreleased RGB color
1668 -------------------------------------------------------------------------- */
1670 /*static int c = 1; fprintf (stderr, "color request %d\n", c++); */
1671 if (r < 0.0) r = 0.0;
1672 else if (r > 1.0) r = 1.0;
1673 if (g < 0.0) g = 0.0;
1674 else if (g > 1.0) g = 1.0;
1675 if (b < 0.0) b = 0.0;
1676 else if (b > 1.0) b = 1.0;
1677 if (a < 0.0) a = 0.0;
1678 else if (a > 1.0) a = 1.0;
1679 return (unsigned long) ns_index_color(
1680 [NSColor colorWithCalibratedRed: r green: g blue: b alpha: a], f);
1685 x_set_frame_alpha (struct frame *f)
1686 /* --------------------------------------------------------------------------
1687 change the entire-frame transparency
1688 -------------------------------------------------------------------------- */
1690 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1691 EmacsView *view = FRAME_NS_VIEW (f);
1693 double alpha_min = 1.0;
1695 if (dpyinfo->x_highlight_frame == f)
1696 alpha = f->alpha[0];
1698 alpha = f->alpha[1];
1700 if (FLOATP (Vframe_alpha_lower_limit))
1701 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1702 else if (INTEGERP (Vframe_alpha_lower_limit))
1703 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1707 else if (1.0 < alpha)
1709 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1712 #ifdef NS_IMPL_COCOA
1713 [[view window] setAlphaValue: alpha];
1718 /* ==========================================================================
1722 ========================================================================== */
1726 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1727 /* --------------------------------------------------------------------------
1728 Programmatically reposition mouse pointer in pixel coordinates
1729 -------------------------------------------------------------------------- */
1731 NSTRACE (x_set_mouse_pixel_position);
1734 /* FIXME: this does not work, and what about GNUstep? */
1735 #ifdef NS_IMPL_COCOA
1736 [FRAME_NS_VIEW (f) lockFocus];
1737 PSsetmouse ((float)pix_x, (float)pix_y);
1738 [FRAME_NS_VIEW (f) unlockFocus];
1745 x_set_mouse_position (struct frame *f, int h, int v)
1746 /* --------------------------------------------------------------------------
1747 Programmatically reposition mouse pointer in character coordinates
1748 -------------------------------------------------------------------------- */
1752 pix_x = FRAME_COL_TO_PIXEL_X (f, h) + FRAME_COLUMN_WIDTH (f) / 2;
1753 pix_y = FRAME_LINE_TO_PIXEL_Y (f, v) + FRAME_LINE_HEIGHT (f) / 2;
1755 if (pix_x < 0) pix_x = 0;
1756 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
1758 if (pix_y < 0) pix_y = 0;
1759 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
1761 x_set_mouse_pixel_position (f, pix_x, pix_y);
1766 note_mouse_movement (struct frame *frame, float x, float y)
1767 /* ------------------------------------------------------------------------
1768 Called by EmacsView on mouseMovement events. Passes on
1769 to emacs mainstream code if we moved off of a rect of interest
1770 known as last_mouse_glyph.
1771 ------------------------------------------------------------------------ */
1773 // NSTRACE (note_mouse_movement);
1775 XSETFRAME (last_mouse_motion_frame, frame);
1777 /* Note, this doesn't get called for enter/leave, since we don't have a
1778 position. Those are taken care of in the corresponding NSView methods. */
1780 /* has movement gone beyond last rect we were tracking? */
1781 if (x < last_mouse_glyph.origin.x ||
1782 x >= (last_mouse_glyph.origin.x + last_mouse_glyph.size.width) ||
1783 y < last_mouse_glyph.origin.y ||
1784 y >= (last_mouse_glyph.origin.y + last_mouse_glyph.size.height))
1786 ns_update_begin(frame);
1787 frame->mouse_moved = 1;
1788 note_mouse_highlight (frame, x, y);
1789 remember_mouse_glyph (frame, x, y, &last_mouse_glyph);
1790 ns_update_end(frame);
1799 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1800 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1802 /* --------------------------------------------------------------------------
1803 External (hook): inform emacs about mouse position and hit parts.
1804 If a scrollbar is being dragged, set bar_window, part, x, y, time.
1805 x & y should be position in the scrollbar (the whole bar, not the handle)
1806 and length of scrollbar respectively
1807 -------------------------------------------------------------------------- */
1812 Lisp_Object frame, tail;
1814 struct ns_display_info *dpyinfo;
1816 NSTRACE (ns_mouse_position);
1820 fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1824 dpyinfo = FRAME_NS_DISPLAY_INFO (*fp);
1828 if (last_mouse_scroll_bar != nil && insist == 0)
1830 /* TODO: we do not use this path at the moment because drag events will
1831 go directly to the EmacsScroller. Leaving code in for now. */
1832 [last_mouse_scroll_bar getMouseMotionPart: (int *)part window: bar_window
1834 if (time) *time = last_mouse_movement_time;
1835 last_mouse_scroll_bar = nil;
1839 /* Clear the mouse-moved flag for every frame on this display. */
1840 FOR_EACH_FRAME (tail, frame)
1841 if (FRAME_NS_P (XFRAME (frame))
1842 && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1843 XFRAME (frame)->mouse_moved = 0;
1845 last_mouse_scroll_bar = nil;
1846 if (last_mouse_frame && FRAME_LIVE_P (last_mouse_frame))
1847 f = last_mouse_frame;
1849 f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame
1850 : SELECTED_FRAME ();
1852 if (f && f->output_data.ns) /* TODO: 2nd check no longer needed? */
1854 view = FRAME_NS_VIEW (*fp);
1856 position = [[view window] mouseLocationOutsideOfEventStream];
1857 position = [view convertPoint: position fromView: nil];
1858 remember_mouse_glyph (f, position.x, position.y, &last_mouse_glyph);
1859 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1861 if (bar_window) *bar_window = Qnil;
1862 if (part) *part = 0; /*scroll_bar_handle; */
1864 if (x) XSETINT (*x, lrint (position.x));
1865 if (y) XSETINT (*y, lrint (position.y));
1866 if (time) *time = last_mouse_movement_time;
1876 ns_frame_up_to_date (struct frame *f)
1877 /* --------------------------------------------------------------------------
1878 External (hook): Fix up mouse highlighting right after a full update.
1879 Some highlighting was deferred if GC was happening during
1880 note_mouse_highlight (), while other highlighting was deferred for update.
1881 -------------------------------------------------------------------------- */
1883 NSTRACE (ns_frame_up_to_date);
1887 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1888 if ((hlinfo->mouse_face_deferred_gc || f ==hlinfo->mouse_face_mouse_frame)
1889 /*&& hlinfo->mouse_face_mouse_frame*/)
1893 if (hlinfo->mouse_face_mouse_frame)
1894 note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
1895 hlinfo->mouse_face_mouse_x,
1896 hlinfo->mouse_face_mouse_y);
1897 hlinfo->mouse_face_deferred_gc = 0;
1906 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1907 /* --------------------------------------------------------------------------
1908 External (RIF): set frame mouse pointer type.
1909 -------------------------------------------------------------------------- */
1911 NSTRACE (ns_define_frame_cursor);
1912 if (FRAME_POINTER_TYPE (f) != cursor)
1914 EmacsView *view = FRAME_NS_VIEW (f);
1915 FRAME_POINTER_TYPE (f) = cursor;
1916 [[view window] invalidateCursorRectsForView: view];
1917 /* Redisplay assumes this function also draws the changed frame
1918 cursor, but this function doesn't, so do it explicitly. */
1919 x_update_cursor (f, 1);
1925 /* ==========================================================================
1929 ========================================================================== */
1933 ns_convert_key (unsigned code)
1934 /* --------------------------------------------------------------------------
1935 Internal call used by NSView-keyDown.
1936 -------------------------------------------------------------------------- */
1938 const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym)
1939 / sizeof (convert_ns_to_X_keysym[0]));
1941 /* An array would be faster, but less easy to read. */
1942 for (keysym = 0; keysym < last_keysym; keysym += 2)
1943 if (code == convert_ns_to_X_keysym[keysym])
1944 return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
1946 /* if decide to use keyCode and Carbon table, use this line:
1947 return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
1952 x_get_keysym_name (int keysym)
1953 /* --------------------------------------------------------------------------
1954 Called by keyboard.c. Not sure if the return val is important, except
1956 -------------------------------------------------------------------------- */
1958 static char value[16];
1959 NSTRACE (x_get_keysym_name);
1960 sprintf (value, "%d", keysym);
1966 /* ==========================================================================
1968 Block drawing operations
1970 ========================================================================== */
1974 ns_redraw_scroll_bars (struct frame *f)
1978 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
1979 NSTRACE (ns_judge_scroll_bars);
1980 for (i =[subviews count]-1; i >= 0; i--)
1982 view = [subviews objectAtIndex: i];
1983 if (![view isKindOfClass: [EmacsScroller class]]) continue;
1990 ns_clear_frame (struct frame *f)
1991 /* --------------------------------------------------------------------------
1992 External (hook): Erase the entire frame
1993 -------------------------------------------------------------------------- */
1995 NSView *view = FRAME_NS_VIEW (f);
1998 NSTRACE (ns_clear_frame);
2002 /* comes on initial frame because we have
2003 after-make-frame-functions = select-frame */
2004 if (!FRAME_DEFAULT_FACE (f))
2007 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2009 output_cursor.hpos = output_cursor.vpos = 0;
2010 output_cursor.x = -1;
2015 ns_focus (f, &r, 1);
2016 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
2020 #ifdef NS_IMPL_COCOA
2021 [[view window] display]; /* redraw resize handle */
2024 /* as of 2006/11 or so this is now needed */
2025 ns_redraw_scroll_bars (f);
2031 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2032 /* --------------------------------------------------------------------------
2033 External (RIF): Clear section of frame
2034 -------------------------------------------------------------------------- */
2036 NSRect r = NSMakeRect (x, y, width, height);
2037 NSView *view = FRAME_NS_VIEW (f);
2038 struct face *face = FRAME_DEFAULT_FACE (f);
2043 NSTRACE (ns_clear_frame_area);
2045 r = NSIntersectionRect (r, [view frame]);
2046 ns_focus (f, &r, 1);
2047 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2049 #ifdef NS_IMPL_COCOA
2051 /* clip out the resize handle */
2052 NSWindow *window = [FRAME_NS_VIEW (f) window];
2054 = [view convertRect: ns_resize_handle_rect (window) fromView: nil];
2056 ir = NSIntersectionRect (r, ir);
2057 if (NSIsEmptyRect (ir))
2063 #ifdef NS_IMPL_COCOA
2067 NSRect r1 = r, r2 = r; /* upper and lower non-intersecting */
2068 r1.size.height -= ir.size.height;
2069 r2.origin.y += r1.size.height;
2070 r2.size.width -= ir.size.width;
2071 r2.size.height = ir.size.height;
2084 ns_scroll_run (struct window *w, struct run *run)
2085 /* --------------------------------------------------------------------------
2086 External (RIF): Insert or delete n lines at line vpos
2087 -------------------------------------------------------------------------- */
2089 struct frame *f = XFRAME (w->frame);
2090 int x, y, width, height, from_y, to_y, bottom_y;
2092 NSTRACE (ns_scroll_run);
2094 /* begin copy from other terms */
2095 /* Get frame-relative bounding box of the text display area of W,
2096 without mode lines. Include in this box the left and right
2098 window_box (w, -1, &x, &y, &width, &height);
2100 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2101 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2102 bottom_y = y + height;
2106 /* Scrolling up. Make sure we don't copy part of the mode
2107 line at the bottom. */
2108 if (from_y + run->height > bottom_y)
2109 height = bottom_y - from_y;
2111 height = run->height;
2115 /* Scrolling down. Make sure we don't copy over the mode line.
2117 if (to_y + run->height > bottom_y)
2118 height = bottom_y - to_y;
2120 height = run->height;
2122 /* end copy from other terms */
2133 NSRect srcRect = NSMakeRect (x, from_y, width, height);
2134 NSRect dstRect = NSMakeRect (x, to_y, width, height);
2135 NSPoint dstOrigin = NSMakePoint (x, to_y);
2137 ns_focus (f, &dstRect, 1);
2138 NSCopyBits (0, srcRect , dstOrigin);
2147 ns_after_update_window_line (struct glyph_row *desired_row)
2148 /* --------------------------------------------------------------------------
2149 External (RIF): preparatory to fringe update after text was updated
2150 -------------------------------------------------------------------------- */
2152 struct window *w = updated_window;
2156 NSTRACE (ns_after_update_window_line);
2158 /* begin copy from other terms */
2161 if (!desired_row->mode_line_p && !w->pseudo_window_p)
2162 desired_row->redraw_fringe_bitmaps_p = 1;
2164 /* When a window has disappeared, make sure that no rest of
2165 full-width rows stays visible in the internal border.
2166 Under NS this is drawn inside the fringes. */
2167 if (windows_or_buffers_changed
2168 && (f = XFRAME (w->frame),
2169 width = FRAME_INTERNAL_BORDER_WIDTH (f),
2171 && (height = desired_row->visible_height,
2174 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2176 /* Internal border is drawn below the tool bar. */
2177 if (WINDOWP (f->tool_bar_window)
2178 && w == XWINDOW (f->tool_bar_window))
2180 /* end copy from other terms */
2183 if (!desired_row->full_width_p)
2185 int x1 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2186 + WINDOW_LEFT_FRINGE_WIDTH (w);
2187 int x2 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2188 + FRAME_PIXEL_WIDTH (f) - NS_SCROLL_BAR_WIDTH (f)
2189 - WINDOW_RIGHT_FRINGE_WIDTH (w)
2190 - FRAME_INTERNAL_BORDER_WIDTH (f);
2191 ns_clear_frame_area (f, x1, y, width, height);
2192 ns_clear_frame_area (f, x2, y, width, height);
2200 ns_shift_glyphs_for_insert (struct frame *f,
2201 int x, int y, int width, int height,
2203 /* --------------------------------------------------------------------------
2204 External (RIF): copy an area horizontally, don't worry about clearing src
2205 -------------------------------------------------------------------------- */
2207 NSRect srcRect = NSMakeRect (x, y, width, height);
2208 NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2209 NSPoint dstOrigin = dstRect.origin;
2211 NSTRACE (ns_shift_glyphs_for_insert);
2213 ns_focus (f, &dstRect, 1);
2214 NSCopyBits (0, srcRect, dstOrigin);
2220 /* ==========================================================================
2222 Character encoding and metrics
2224 ========================================================================== */
2228 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2229 /* --------------------------------------------------------------------------
2230 External (RIF); compute left/right overhang of whole string and set in s
2231 -------------------------------------------------------------------------- */
2233 struct face *face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2234 struct font *font = s->font; /*face->font; */
2238 struct font_metrics metrics;
2239 unsigned int codes[2];
2240 codes[0] = *(s->char2b);
2241 codes[1] = *(s->char2b + s->nchars - 1);
2243 font->driver->text_extents (font, codes, 2, &metrics);
2244 s->left_overhang = -metrics.lbearing;
2246 = metrics.rbearing > metrics.width
2247 ? metrics.rbearing - metrics.width : 0;
2251 s->left_overhang = 0;
2252 s->right_overhang = ((struct nsfont_info *)font)->ital ?
2253 FONT_HEIGHT (font) * 0.2 : 0;
2259 /* ==========================================================================
2261 Fringe and cursor drawing
2263 ========================================================================== */
2266 extern int max_used_fringe_bitmap;
2268 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2269 struct draw_fringe_bitmap_params *p)
2270 /* --------------------------------------------------------------------------
2271 External (RIF); fringe-related
2272 -------------------------------------------------------------------------- */
2274 struct frame *f = XFRAME (WINDOW_FRAME (w));
2275 struct face *face = p->face;
2277 static EmacsImage **bimgs = NULL;
2278 static int nBimgs = 0;
2279 /* NS-specific: move internal border inside fringe */
2280 int x = p->bx < 0 ? p->x : p->bx;
2281 int wd = p->bx < 0 ? p->wd : p->nx;
2282 BOOL fringeOnVeryLeft
2283 = x - WINDOW_LEFT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w)
2284 - FRAME_INTERNAL_BORDER_WIDTH (f) < 10;
2285 BOOL fringeOnVeryRight
2286 = FRAME_PIXEL_WIDTH (f) - x - wd - FRAME_INTERNAL_BORDER_WIDTH (f)
2287 - WINDOW_RIGHT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w) < 10;
2288 int xAdjust = FRAME_INTERNAL_BORDER_WIDTH (f) *
2289 (fringeOnVeryLeft ? -1 : (fringeOnVeryRight ? 1 : 0));
2291 /* grow bimgs if needed */
2292 if (nBimgs < max_used_fringe_bitmap)
2294 EmacsImage **newBimgs
2295 = xmalloc (max_used_fringe_bitmap * sizeof (EmacsImage *));
2296 memset (newBimgs, 0, max_used_fringe_bitmap * sizeof (EmacsImage *));
2300 memcpy (newBimgs, bimgs, nBimgs * sizeof (EmacsImage *));
2305 nBimgs = max_used_fringe_bitmap;
2308 /* Must clip because of partially visible lines. */
2309 rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
2310 ns_clip_to_row (w, row, -1, YES);
2312 if (p->bx >= 0 && !p->overlay_p)
2314 int yAdjust = rowY - FRAME_INTERNAL_BORDER_WIDTH (f) < 5 ?
2315 -FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2316 int yIncr = FRAME_PIXEL_HEIGHT (f) - (p->by+yAdjust + p->ny) < 5 ?
2317 FRAME_INTERNAL_BORDER_WIDTH (f) : 0
2318 + (yAdjust ? FRAME_INTERNAL_BORDER_WIDTH (f) : 0);
2319 NSRect r = NSMakeRect (p->bx+xAdjust, p->by+yAdjust, p->nx, p->ny+yIncr);
2321 [ns_lookup_indexed_color(face->background, f) set];
2327 NSRect r = NSMakeRect (p->x+xAdjust, p->y, p->wd, p->h);
2328 NSPoint pt = r.origin;
2329 EmacsImage *img = bimgs[p->which - 1];
2333 unsigned short *bits = p->bits + p->dh;
2336 unsigned char *cbits = xmalloc (len);
2338 for (i =0; i<len; i++)
2339 cbits[i] = ~(bits[i] & 0xff);
2340 img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2342 bimgs[p->which - 1] = img;
2347 /* Since we composite the bitmap instead of just blitting it, we need
2348 to erase the whole background. */
2349 [ns_lookup_indexed_color(face->background, f) set];
2352 [img setXBMColor: ns_lookup_indexed_color(face->foreground, f)];
2353 [img compositeToPoint: pt operation: NSCompositeSourceOver];
2360 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2361 int x, int y, int cursor_type, int cursor_width,
2362 int on_p, int active_p)
2363 /* --------------------------------------------------------------------------
2364 External call (RIF): draw cursor.
2365 Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2366 -------------------------------------------------------------------------- */
2369 int fx, fy, h, cursor_height;
2370 struct frame *f = WINDOW_XFRAME (w);
2371 struct glyph *phys_cursor_glyph;
2373 struct glyph *cursor_glyph;
2375 NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2377 /* If cursor is out of bounds, don't draw garbage. This can happen
2378 in mini-buffer windows when switching between echo area glyphs
2381 NSTRACE (dumpcursor);
2386 w->phys_cursor_type = cursor_type;
2387 w->phys_cursor_on_p = on_p;
2389 if (cursor_type == NO_CURSOR)
2391 w->phys_cursor_width = 0;
2395 if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2397 if (glyph_row->exact_window_width_line_p
2398 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2400 glyph_row->cursor_in_fringe_p = 1;
2401 draw_fringe_bitmap (w, glyph_row, 0);
2406 /* We draw the cursor (with NSRectFill), then draw the glyph on top
2407 (other terminals do it the other way round). We must set
2408 w->phys_cursor_width to the cursor width. For bar cursors, that
2409 is CURSOR_WIDTH; for box cursors, it is the glyph width. */
2410 get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2412 /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2413 to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2414 if (cursor_type == BAR_CURSOR)
2416 if (cursor_width < 1)
2417 cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2418 w->phys_cursor_width = cursor_width;
2420 /* If we have an HBAR, "cursor_width" MAY specify height. */
2421 else if (cursor_type == HBAR_CURSOR)
2423 cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2424 fy += h - cursor_height;
2428 r.origin.x = fx, r.origin.y = fy;
2430 r.size.width = w->phys_cursor_width;
2432 /* FIXME: if we overwrite the internal border area, it does not get erased;
2433 fix by truncating cursor, but better would be to erase properly */
2434 overspill = r.origin.x + r.size.width -
2435 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, WINDOW_BOX_RIGHT_EDGE_X (w)
2436 - WINDOW_TOTAL_FRINGE_WIDTH (w) - FRAME_INTERNAL_BORDER_WIDTH (f));
2438 r.size.width -= overspill;
2440 /* TODO: only needed in rare cases with last-resort font in HELLO..
2441 should we do this more efficiently? */
2442 ns_clip_to_row (w, glyph_row, -1, NO); /* do ns_focus(f, &r, 1); if remove */
2445 face = FACE_FROM_ID (f, phys_cursor_glyph->face_id);
2446 if (face && NS_FACE_BACKGROUND (face)
2447 == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2449 [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2450 hollow_color = FRAME_CURSOR_COLOR (f);
2453 [FRAME_CURSOR_COLOR (f) set];
2455 #ifdef NS_IMPL_COCOA
2456 /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2457 atomic. Cleaner ways of doing this should be investigated.
2458 One way would be to set a global variable DRAWING_CURSOR
2459 when making the call to draw_phys..(), don't focus in that
2460 case, then move the ns_unfocus() here after that call. */
2461 NSDisableScreenUpdates ();
2464 switch (cursor_type)
2468 case FILLED_BOX_CURSOR:
2471 case HOLLOW_BOX_CURSOR:
2474 NSRectFill (NSInsetRect (r, 1, 1));
2475 [FRAME_CURSOR_COLOR (f) set];
2482 /* If the character under cursor is R2L, draw the bar cursor
2483 on the right of its glyph, rather than on the left. */
2484 cursor_glyph = get_phys_cursor_glyph (w);
2485 if ((cursor_glyph->resolved_level & 1) != 0)
2486 s.origin.x += cursor_glyph->pixel_width - s.size.width;
2493 /* draw the character under the cursor */
2494 if (cursor_type != NO_CURSOR)
2495 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2497 #ifdef NS_IMPL_COCOA
2498 NSEnableScreenUpdates ();
2505 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2506 /* --------------------------------------------------------------------------
2507 External (RIF): Draw a vertical line.
2508 -------------------------------------------------------------------------- */
2510 struct frame *f = XFRAME (WINDOW_FRAME (w));
2512 NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2514 NSTRACE (ns_draw_vertical_window_border);
2516 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2518 [ns_lookup_indexed_color(face->foreground, f) set];
2520 ns_focus (f, &r, 1);
2527 show_hourglass (struct atimer *timer)
2529 if (hourglass_shown_p)
2534 /* TODO: add NSProgressIndicator to selected frame (see macfns.c) */
2536 hourglass_shown_p = 1;
2542 hide_hourglass (void)
2544 if (!hourglass_shown_p)
2549 /* TODO: remove NSProgressIndicator from all frames */
2551 hourglass_shown_p = 0;
2557 /* ==========================================================================
2559 Glyph drawing operations
2561 ========================================================================== */
2564 static inline NSRect
2565 ns_fix_rect_ibw (NSRect r, int fibw, int frame_pixel_width)
2566 /* --------------------------------------------------------------------------
2567 Under NS we draw internal borders inside fringes, and want full-width
2568 rendering to go all the way to edge. This function makes that correction.
2569 -------------------------------------------------------------------------- */
2571 if (r.origin.y <= fibw+1)
2573 r.size.height += r.origin.y;
2576 if (r.origin.x <= fibw+1)
2578 r.size.width += r.origin.x;
2581 if (frame_pixel_width - (r.origin.x+r.size.width) <= fibw+1)
2582 r.size.width += fibw;
2589 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2590 /* --------------------------------------------------------------------------
2591 Wrapper utility to account for internal border width on full-width lines,
2592 and allow top full-width rows to hit the frame top. nr should be pointer
2593 to two successive NSRects. Number of rects actually used is returned.
2594 -------------------------------------------------------------------------- */
2596 int n = get_glyph_string_clip_rects (s, nr, 2);
2597 if (s->row->full_width_p)
2599 *nr = ns_fix_rect_ibw (*nr, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2600 FRAME_PIXEL_WIDTH (s->f));
2602 *nr = ns_fix_rect_ibw (*(nr+1), FRAME_INTERNAL_BORDER_WIDTH (s->f),
2603 FRAME_PIXEL_WIDTH (s->f));
2609 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
2610 NSColor *defaultCol, CGFloat width, CGFloat x)
2611 /* --------------------------------------------------------------------------
2612 Draw underline, overline, and strike-through on glyph string s.
2613 -------------------------------------------------------------------------- */
2615 if (s->for_overlaps)
2619 if (face->underline_p)
2622 unsigned long thickness, position;
2624 /* If the prev was underlined, match its appearance. */
2625 if (s->prev && s->prev->face->underline_p
2626 && s->prev->underline_thickness > 0)
2628 thickness = s->prev->underline_thickness;
2629 position = s->prev->underline_position;
2634 unsigned long descent;
2637 descent = s->y + s->height - s->ybase;
2639 /* Use underline thickness of font, defaulting to 1. */
2640 thickness = (font && font->underline_thickness > 0)
2641 ? font->underline_thickness : 1;
2643 /* Determine the offset of underlining from the baseline. */
2644 if (x_underline_at_descent_line)
2645 position = descent - thickness;
2646 else if (x_use_underline_position_properties
2647 && font && font->underline_position >= 0)
2648 position = font->underline_position;
2650 position = lround (font->descent / 2);
2652 position = underline_minimum_offset;
2654 position = max (position, underline_minimum_offset);
2656 /* Ensure underlining is not cropped. */
2657 if (descent <= position)
2659 position = descent - 1;
2662 else if (descent < position + thickness)
2666 s->underline_thickness = thickness;
2667 s->underline_position = position;
2669 r = NSMakeRect (x, s->ybase + position, width, thickness);
2671 if (face->underline_defaulted_p)
2674 [ns_lookup_indexed_color (face->underline_color, s->f) set];
2678 /* Do overline. We follow other terms in using a thickness of 1
2679 and ignoring overline_margin. */
2680 if (face->overline_p)
2683 r = NSMakeRect (x, s->y, width, 1);
2685 if (face->overline_color_defaulted_p)
2688 [ns_lookup_indexed_color (face->overline_color, s->f) set];
2692 /* Do strike-through. We follow other terms for thickness and
2693 vertical position.*/
2694 if (face->strike_through_p)
2699 dy = lrint ((s->height - 1) / 2);
2700 r = NSMakeRect (x, s->y + dy, width, 1);
2702 if (face->strike_through_color_defaulted_p)
2705 [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
2711 ns_draw_box (NSRect r, float thickness, NSColor *col, char left_p, char right_p)
2712 /* --------------------------------------------------------------------------
2713 Draw an unfilled rect inside r, optionally leaving left and/or right open.
2714 Note we can't just use an NSDrawRect command, because of the possibility
2715 of some sides not being drawn, and because the rect will be filled.
2716 -------------------------------------------------------------------------- */
2722 s.size.height = thickness;
2724 s.origin.y += r.size.height - thickness;
2727 s.size.height = r.size.height;
2728 s.origin.y = r.origin.y;
2730 /* left, right (optional) */
2731 s.size.width = thickness;
2736 s.origin.x += r.size.width - thickness;
2743 ns_draw_relief (NSRect r, int thickness, char raised_p,
2744 char top_p, char bottom_p, char left_p, char right_p,
2745 struct glyph_string *s)
2746 /* --------------------------------------------------------------------------
2747 Draw a relief rect inside r, optionally leaving some sides open.
2748 Note we can't just use an NSDrawBezel command, because of the possibility
2749 of some sides not being drawn, and because the rect will be filled.
2750 -------------------------------------------------------------------------- */
2752 static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2753 NSColor *newBaseCol = nil;
2756 NSTRACE (ns_draw_relief);
2760 if (s->face->use_box_color_for_shadows_p)
2762 newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2764 /* else if (s->first_glyph->type == IMAGE_GLYPH
2766 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2768 newBaseCol = IMAGE_BACKGROUND (s->img, s->f, 0);
2772 newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2775 if (newBaseCol == nil)
2776 newBaseCol = [NSColor grayColor];
2778 if (newBaseCol != baseCol) /* TODO: better check */
2781 baseCol = [newBaseCol retain];
2783 lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2785 darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2788 [(raised_p ? lightCol : darkCol) set];
2790 /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2793 sr.size.height = thickness;
2794 if (top_p) NSRectFill (sr);
2797 sr.size.height = r.size.height;
2798 sr.size.width = thickness;
2799 if (left_p) NSRectFill (sr);
2801 [(raised_p ? darkCol : lightCol) set];
2804 sr.size.width = r.size.width;
2805 sr.size.height = thickness;
2806 sr.origin.y += r.size.height - thickness;
2807 if (bottom_p) NSRectFill (sr);
2810 sr.size.height = r.size.height;
2811 sr.origin.y = r.origin.y;
2812 sr.size.width = thickness;
2813 sr.origin.x += r.size.width - thickness;
2814 if (right_p) NSRectFill (sr);
2819 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2820 /* --------------------------------------------------------------------------
2821 Function modeled after x_draw_glyph_string_box ().
2822 Sets up parameters for drawing.
2823 -------------------------------------------------------------------------- */
2825 int right_x, last_x;
2826 char left_p, right_p;
2827 struct glyph *last_glyph;
2832 if (s->hl == DRAW_MOUSE_FACE)
2834 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2836 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2841 thickness = face->box_line_width;
2843 NSTRACE (ns_dumpglyphs_box_or_relief);
2845 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2846 ? WINDOW_RIGHT_EDGE_X (s->w)
2847 : window_box_right (s->w, s->area));
2848 last_glyph = (s->cmp || s->img
2849 ? s->first_glyph : s->first_glyph + s->nchars-1);
2851 right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2852 ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2854 left_p = (s->first_glyph->left_box_line_p
2855 || (s->hl == DRAW_MOUSE_FACE
2856 && (s->prev == NULL || s->prev->hl != s->hl)));
2857 right_p = (last_glyph->right_box_line_p
2858 || (s->hl == DRAW_MOUSE_FACE
2859 && (s->next == NULL || s->next->hl != s->hl)));
2861 r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2863 /* expand full-width row over internal borders */
2864 if (s->row->full_width_p)
2865 r = ns_fix_rect_ibw (r, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2866 FRAME_PIXEL_WIDTH (s->f));
2868 /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
2869 if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
2871 ns_draw_box (r, abs (thickness),
2872 ns_lookup_indexed_color (face->box_color, s->f),
2877 ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2878 1, 1, left_p, right_p, s);
2884 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2885 /* --------------------------------------------------------------------------
2886 Modeled after x_draw_glyph_string_background, which draws BG in
2887 certain cases. Others are left to the text rendering routine.
2888 -------------------------------------------------------------------------- */
2890 NSTRACE (ns_maybe_dumpglyphs_background);
2892 if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2894 int box_line_width = max (s->face->box_line_width, 0);
2895 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2896 || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2899 if (s->hl == DRAW_MOUSE_FACE)
2901 face = FACE_FROM_ID (s->f,
2902 MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2904 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2907 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2909 [(NS_FACE_BACKGROUND (face) != 0
2910 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2911 : FRAME_BACKGROUND_COLOR (s->f)) set];
2914 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (s->f);
2915 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2918 if (s->hl != DRAW_CURSOR)
2920 NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2921 s->background_width,
2922 s->height-2*box_line_width);
2924 /* expand full-width row over internal borders */
2925 if (s->row->full_width_p)
2927 int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2928 if (r.origin.y <= fibw+1 + box_line_width)
2930 r.size.height += r.origin.y;
2933 if (r.origin.x <= fibw+1)
2935 r.size.width += 2*r.origin.x;
2938 if (FRAME_PIXEL_WIDTH (s->f) - (r.origin.x + r.size.width)
2940 r.size.width += fibw;
2946 s->background_filled_p = 1;
2953 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2954 /* --------------------------------------------------------------------------
2955 Renders an image and associated borders.
2956 -------------------------------------------------------------------------- */
2958 EmacsImage *img = s->img->pixmap;
2959 int box_line_vwidth = max (s->face->box_line_width, 0);
2960 int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2961 int bg_x, bg_y, bg_height;
2968 NSTRACE (ns_dumpglyphs_image);
2970 if (s->face->box != FACE_NO_BOX
2971 && s->first_glyph->left_box_line_p && s->slice.x == 0)
2972 x += abs (s->face->box_line_width);
2975 bg_y = s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2976 bg_height = s->height;
2977 /* other terms have this, but was causing problems w/tabbar mode */
2978 /* - 2 * box_line_vwidth; */
2980 if (s->slice.x == 0) x += s->img->hmargin;
2981 if (s->slice.y == 0) y += s->img->vmargin;
2983 /* Draw BG: if we need larger area than image itself cleared, do that,
2984 otherwise, since we composite the image under NS (instead of mucking
2985 with its background color), we must clear just the image area. */
2986 if (s->hl == DRAW_MOUSE_FACE)
2988 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2990 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2993 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2995 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
2997 if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
2998 || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
3000 br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
3001 s->background_filled_p = 1;
3005 br = NSMakeRect (x, y, s->slice.width, s->slice.height);
3008 /* expand full-width row over internal borders */
3009 if (s->row->full_width_p)
3011 int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
3012 if (br.origin.y <= fibw+1 + box_line_vwidth)
3014 br.size.height += br.origin.y;
3017 if (br.origin.x <= fibw+1 + box_line_vwidth)
3019 br.size.width += br.origin.x;
3022 if (FRAME_PIXEL_WIDTH (s->f) - (br.origin.x + br.size.width) <= fibw+1)
3023 br.size.width += fibw;
3028 /* Draw the image.. do we need to draw placeholder if img ==nil? */
3030 [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3031 operation: NSCompositeSourceOver];
3033 if (s->hl == DRAW_CURSOR)
3035 [FRAME_CURSOR_COLOR (s->f) set];
3036 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3037 tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3039 /* Currently on NS img->mask is always 0. Since
3040 get_window_cursor_type specifies a hollow box cursor when on
3041 a non-masked image we never reach this clause. But we put it
3042 in in anticipation of better support for image masks on
3044 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3048 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3051 /* Draw underline, overline, strike-through. */
3052 ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3054 /* Draw relief, if requested */
3055 if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3057 if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3059 th = tool_bar_button_relief >= 0 ?
3060 tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3061 raised_p = (s->hl == DRAW_IMAGE_RAISED);
3065 th = abs (s->img->relief);
3066 raised_p = (s->img->relief > 0);
3069 r.origin.x = x - th;
3070 r.origin.y = y - th;
3071 r.size.width = s->slice.width + 2*th-1;
3072 r.size.height = s->slice.height + 2*th-1;
3073 ns_draw_relief (r, th, raised_p,
3075 s->slice.y + s->slice.height == s->img->height,
3077 s->slice.x + s->slice.width == s->img->width, s);
3080 /* If there is no mask, the background won't be seen,
3081 so draw a rectangle on the image for the cursor.
3082 Do this for all images, getting transparency right is not reliable. */
3083 if (s->hl == DRAW_CURSOR)
3085 int thickness = abs (s->img->relief);
3086 if (thickness == 0) thickness = 1;
3087 ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3093 ns_dumpglyphs_stretch (struct glyph_string *s)
3098 NSColor *fgCol, *bgCol;
3100 if (!s->background_filled_p)
3102 n = ns_get_glyph_string_clip_rect (s, r);
3103 *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3105 ns_focus (s->f, r, n);
3107 if (s->hl == DRAW_MOUSE_FACE)
3109 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3111 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3114 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3116 bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3117 fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3121 if (!s->row->full_width_p)
3123 int overrun, leftoverrun;
3125 /* truncate to avoid overwriting fringe and/or scrollbar */
3126 overrun = max (0, (s->x + s->background_width)
3127 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3128 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3129 r[i].size.width -= overrun;
3131 /* truncate to avoid overwriting to left of the window box */
3132 leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3133 + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3135 if (leftoverrun > 0)
3137 r[i].origin.x += leftoverrun;
3138 r[i].size.width -= leftoverrun;
3141 /* XXX: Try to work between problem where a stretch glyph on
3142 a partially-visible bottom row will clear part of the
3143 modeline, and another where list-buffers headers and similar
3144 rows erroneously have visible_height set to 0. Not sure
3145 where this is coming from as other terms seem not to show. */
3146 r[i].size.height = min (s->height, s->row->visible_height);
3149 /* expand full-width rows over internal borders */
3152 r[i] = ns_fix_rect_ibw (r[i], FRAME_INTERNAL_BORDER_WIDTH (s->f),
3153 FRAME_PIXEL_WIDTH (s->f));
3158 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3159 overwriting cursor (usually when cursor on a tab) */
3160 if (s->hl == DRAW_CURSOR)
3165 width = s->w->phys_cursor_width;
3166 r[i].size.width -= width;
3167 r[i].origin.x += width;
3171 /* Draw overlining, etc. on the cursor. */
3172 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3173 ns_draw_text_decoration (s, face, bgCol, width, x);
3175 ns_draw_text_decoration (s, face, fgCol, width, x);
3182 /* Draw overlining, etc. on the stretch glyph (or the part
3183 of the stretch glyph after the cursor). */
3184 ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3188 s->background_filled_p = 1;
3194 ns_draw_glyph_string (struct glyph_string *s)
3195 /* --------------------------------------------------------------------------
3196 External (RIF): Main draw-text call.
3197 -------------------------------------------------------------------------- */
3199 /* TODO (optimize): focus for box and contents draw */
3202 char box_drawn_p = 0;
3204 NSTRACE (ns_draw_glyph_string);
3206 if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3209 struct glyph_string *next;
3211 for (width = 0, next = s->next;
3212 next && width < s->right_overhang;
3213 width += next->width, next = next->next)
3214 if (next->first_glyph->type != IMAGE_GLYPH)
3216 if (next->first_glyph->type != STRETCH_GLYPH)
3218 n = ns_get_glyph_string_clip_rect (s->next, r);
3219 ns_focus (s->f, r, n);
3220 ns_maybe_dumpglyphs_background (s->next, 1);
3225 ns_dumpglyphs_stretch (s->next);
3227 next->num_clips = 0;
3231 if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3232 && (s->first_glyph->type == CHAR_GLYPH
3233 || s->first_glyph->type == COMPOSITE_GLYPH))
3235 n = ns_get_glyph_string_clip_rect (s, r);
3236 ns_focus (s->f, r, n);
3237 ns_maybe_dumpglyphs_background (s, 1);
3238 ns_dumpglyphs_box_or_relief (s);
3243 switch (s->first_glyph->type)
3247 n = ns_get_glyph_string_clip_rect (s, r);
3248 ns_focus (s->f, r, n);
3249 ns_dumpglyphs_image (s, r[0]);
3254 ns_dumpglyphs_stretch (s);
3258 case COMPOSITE_GLYPH:
3259 n = ns_get_glyph_string_clip_rect (s, r);
3260 ns_focus (s->f, r, n);
3262 if (s->for_overlaps || (s->cmp_from > 0
3263 && ! s->first_glyph->u.cmp.automatic))
3264 s->background_filled_p = 1;
3266 ns_maybe_dumpglyphs_background
3267 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3269 ns_tmp_flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3270 (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3271 (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3272 NS_DUMPGLYPH_NORMAL));
3273 ns_tmp_font = (struct nsfont_info *)s->face->font;
3274 if (ns_tmp_font == NULL)
3275 ns_tmp_font = (struct nsfont_info *)FRAME_FONT (s->f);
3277 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3279 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3280 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3281 NS_FACE_FOREGROUND (s->face) = tmp;
3284 ns_tmp_font->font.driver->draw
3285 (s, 0, s->nchars, s->x, s->y,
3286 (ns_tmp_flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3287 || ns_tmp_flags == NS_DUMPGLYPH_MOUSEFACE);
3289 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3291 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3292 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3293 NS_FACE_FOREGROUND (s->face) = tmp;
3299 case GLYPHLESS_GLYPH:
3300 n = ns_get_glyph_string_clip_rect (s, r);
3301 ns_focus (s->f, r, n);
3303 if (s->for_overlaps || (s->cmp_from > 0
3304 && ! s->first_glyph->u.cmp.automatic))
3305 s->background_filled_p = 1;
3307 ns_maybe_dumpglyphs_background
3308 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3310 /* Not yet implemented. */
3319 /* Draw box if not done already. */
3320 if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3322 n = ns_get_glyph_string_clip_rect (s, r);
3323 ns_focus (s->f, r, n);
3324 ns_dumpglyphs_box_or_relief (s);
3333 /* ==========================================================================
3337 ========================================================================== */
3341 ns_send_appdefined (int value)
3342 /* --------------------------------------------------------------------------
3343 Internal: post an appdefined event which EmacsApp-sendEvent will
3344 recognize and take as a command to halt the event loop.
3345 -------------------------------------------------------------------------- */
3347 /*NSTRACE (ns_send_appdefined); */
3349 /* Only post this event if we haven't already posted one. This will end
3350 the [NXApp run] main loop after having processed all events queued at
3352 if (send_appdefined)
3356 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
3357 send_appdefined = NO;
3359 /* Don't need wakeup timer any more */
3362 [timed_entry invalidate];
3363 [timed_entry release];
3367 /* Ditto for file descriptor poller */
3370 [fd_entry invalidate];
3375 nxev = [NSEvent otherEventWithType: NSApplicationDefined
3376 location: NSMakePoint (0, 0)
3379 windowNumber: [[NSApp mainWindow] windowNumber]
3380 context: [NSApp context]
3385 /* Post an application defined event on the event queue. When this is
3386 received the [NXApp run] will return, thus having processed all
3387 events which are currently queued. */
3388 [NSApp postEvent: nxev atStart: NO];
3394 ns_read_socket (struct terminal *terminal, int expected,
3395 struct input_event *hold_quit)
3396 /* --------------------------------------------------------------------------
3397 External (hook): Post an event to ourself and keep reading events until
3398 we read it back again. In effect process all events which were waiting.
3399 From 21+ we have to manage the event buffer ourselves.
3400 -------------------------------------------------------------------------- */
3402 struct input_event ev;
3405 /* NSTRACE (ns_read_socket); */
3407 if (interrupt_input_blocked)
3409 interrupt_input_pending = 1;
3411 pending_signals = 1;
3416 interrupt_input_pending = 0;
3418 pending_signals = pending_atimers;
3422 n_emacs_events_pending = 0;
3425 q_event_ptr = hold_quit;
3427 /* we manage autorelease pools by allocate/reallocate each time around
3428 the loop; strict nesting is occasionally violated but seems not to
3429 matter.. earlier methods using full nesting caused major memory leaks */
3430 [outerpool release];
3431 outerpool = [[NSAutoreleasePool alloc] init];
3433 /* If have pending open-file requests, attend to the next one of those. */
3434 if (ns_pending_files && [ns_pending_files count] != 0
3435 && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3437 [ns_pending_files removeObjectAtIndex: 0];
3439 /* Deal with pending service requests. */
3440 else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3442 NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3443 withArg: [ns_pending_service_args objectAtIndex: 0]])
3445 [ns_pending_service_names removeObjectAtIndex: 0];
3446 [ns_pending_service_args removeObjectAtIndex: 0];
3450 /* Run and wait for events. We must always send one NX_APPDEFINED event
3451 to ourself, otherwise [NXApp run] will never exit. */
3452 send_appdefined = YES;
3454 /* If called via ns_select, this is called once with expected=1,
3455 because we expect either the timeout or file descriptor activity.
3456 In this case the first event through will either be real input or
3457 one of these. read_avail_input() then calls once more with expected=0
3458 and in that case we need to return quickly if there is nothing.
3459 If we're being called outside of that, it's also OK to return quickly
3460 after one iteration through the event loop, since other terms do
3461 this and emacs expects it. */
3462 if (!(inNsSelect && expected))
3464 /* Post an application defined event on the event queue. When this is
3465 received the [NXApp run] will return, thus having processed all
3466 events which are currently queued, if any. */
3467 ns_send_appdefined (-1);
3473 nevents = n_emacs_events_pending;
3474 n_emacs_events_pending = 0;
3475 emacs_event = q_event_ptr = NULL;
3483 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3484 fd_set *exceptfds, struct timeval *timeout)
3485 /* --------------------------------------------------------------------------
3486 Replacement for select, checking for events
3487 -------------------------------------------------------------------------- */
3492 /* NSTRACE (ns_select); */
3494 if (NSApp == nil || inNsSelect == 1 /* || ([NSApp isActive] == NO &&
3495 [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
3496 inMode:NSDefaultRunLoopMode dequeue:NO] == nil) */)
3497 return select (nfds, readfds, writefds, exceptfds, timeout);
3499 /* Save file descriptor set, which gets overwritten in calls to select ()
3500 Note, this is called from process.c, and only readfds is ever set */
3503 memcpy (&select_readfds, readfds, sizeof (fd_set));
3509 /* Try an initial select for pending data on input files */
3510 select_timeout.tv_sec = select_timeout.tv_usec = 0;
3511 result = select (nfds, readfds, writefds, exceptfds, &select_timeout);
3515 /* if (!timeout || timed_entry || fd_entry)
3516 fprintf (stderr, "assertion failed: timeout null or timed_entry/fd_entry non-null in ns_select\n"); */
3518 /* set a timeout and run the main AppKit event loop while continuing
3519 to monitor the files */
3520 time = ((double) timeout->tv_sec) + ((double) timeout->tv_usec)/1000000.0;
3521 timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3523 selector: @selector (timeout_handler:)
3525 repeats: YES] /* for safe removal */
3528 /* set a periodic task to try the select () again */
3529 fd_entry = [[NSTimer scheduledTimerWithTimeInterval: 0.1
3531 selector: @selector (fd_handler:)
3536 /* Let Application dispatch events until it receives an event of the type
3537 NX_APPDEFINED, which should only be sent by timeout_handler.
3538 We tell read_avail_input() that input is "expected" because we do expect
3539 either the timeout or fd handler to fire, and if they don't, the original
3540 call from process.c that got us here expects us to wait until some input
3544 ev = last_appdefined_event;
3550 if ([ev type] != NSApplicationDefined)
3554 last_appdefined_event = 0;
3558 /* The NX_APPDEFINED event we received was a timeout. */
3563 /* The NX_APPDEFINED event we received was the result of
3564 at least one real input event arriving. */
3570 /* Received back from select () in fd_handler; copy the results */
3572 memcpy (readfds, &select_readfds, sizeof (fd_set));
3576 /* never reached, shut compiler up */
3582 /* ==========================================================================
3586 ========================================================================== */
3590 ns_set_vertical_scroll_bar (struct window *window,
3591 int portion, int whole, int position)
3592 /* --------------------------------------------------------------------------
3593 External (hook): Update or add scrollbar
3594 -------------------------------------------------------------------------- */
3598 struct frame *f = XFRAME (WINDOW_FRAME (window));
3599 EmacsView *view = FRAME_NS_VIEW (f);
3600 int window_y, window_height;
3601 BOOL barOnVeryLeft, barOnVeryRight;
3602 int top, left, height, width, sb_width, sb_left;
3604 static int count = 0;
3606 /* optimization; display engine sends WAY too many of these.. */
3607 if (!NILP (window->vertical_scroll_bar))
3609 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3610 if ([bar checkSamePosition: position portion: portion whole: whole])
3612 if (view->scrollbarsNeedingUpdate == 0)
3614 if (!windows_or_buffers_changed)
3618 view->scrollbarsNeedingUpdate--;
3622 NSTRACE (ns_set_vertical_scroll_bar);
3624 /* Get dimensions. */
3625 window_box (window, -1, 0, &window_y, 0, &window_height);
3627 height = window_height;
3628 width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3629 left = WINDOW_SCROLL_BAR_AREA_X (window);
3631 if (top < 5) /* top scrollbar adjustment */
3633 top -= FRAME_INTERNAL_BORDER_WIDTH (f);
3634 height += FRAME_INTERNAL_BORDER_WIDTH (f);
3637 /* allow for displaying a skinnier scrollbar than char area allotted */
3638 sb_width = (WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) > 0) ?
3639 WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) : width;
3641 barOnVeryLeft = left < 5;
3642 barOnVeryRight = FRAME_PIXEL_WIDTH (f) - left - width < 5;
3643 sb_left = left + FRAME_INTERNAL_BORDER_WIDTH (f)
3644 * (barOnVeryLeft ? -1 : (barOnVeryRight ? 1 : 0));
3646 r = NSMakeRect (sb_left, top, sb_width, height);
3647 /* the parent view is flipped, so we need to flip y value */
3649 r.origin.y = (v.size.height - r.size.height - r.origin.y);
3651 XSETWINDOW (win, window);
3654 /* we want at least 5 lines to display a scrollbar */
3655 if (WINDOW_TOTAL_LINES (window) < 5)
3657 if (!NILP (window->vertical_scroll_bar))
3659 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3660 [bar removeFromSuperview];
3661 window->vertical_scroll_bar = Qnil;
3663 ns_clear_frame_area (f, sb_left, top, width, height);
3668 if (NILP (window->vertical_scroll_bar))
3670 ns_clear_frame_area (f, sb_left, top, width, height);
3671 bar = [[EmacsScroller alloc] initFrame: r window: win];
3672 window->vertical_scroll_bar = make_save_value (bar, 0);
3677 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3678 oldRect = [bar frame];
3679 r.size.width = oldRect.size.width;
3680 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3682 if (oldRect.origin.x != r.origin.x)
3683 ns_clear_frame_area (f, sb_left, top, width, height);
3688 [bar setPosition: position portion: portion whole: whole];
3694 ns_condemn_scroll_bars (struct frame *f)
3695 /* --------------------------------------------------------------------------
3696 External (hook): arrange for all frame's scrollbars to be removed
3697 at next call to judge_scroll_bars, except for those redeemed.
3698 -------------------------------------------------------------------------- */
3702 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3704 NSTRACE (ns_condemn_scroll_bars);
3706 for (i =[subviews count]-1; i >= 0; i--)
3708 view = [subviews objectAtIndex: i];
3709 if ([view isKindOfClass: [EmacsScroller class]])
3716 ns_redeem_scroll_bar (struct window *window)
3717 /* --------------------------------------------------------------------------
3718 External (hook): arrange to spare this window's scrollbar
3719 at next call to judge_scroll_bars.
3720 -------------------------------------------------------------------------- */
3723 NSTRACE (ns_redeem_scroll_bar);
3724 if (!NILP (window->vertical_scroll_bar))
3726 bar =XNS_SCROLL_BAR (window->vertical_scroll_bar);
3733 ns_judge_scroll_bars (struct frame *f)
3734 /* --------------------------------------------------------------------------
3735 External (hook): destroy all scrollbars on frame that weren't
3736 redeemed after call to condemn_scroll_bars.
3737 -------------------------------------------------------------------------- */
3741 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3742 NSTRACE (ns_judge_scroll_bars);
3743 for (i =[subviews count]-1; i >= 0; i--)
3745 view = [subviews objectAtIndex: i];
3746 if (![view isKindOfClass: [EmacsScroller class]]) continue;
3753 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
3755 /* XXX irrelevant under NS */
3760 /* ==========================================================================
3764 ========================================================================== */
3767 x_display_pixel_height (struct ns_display_info *dpyinfo)
3769 NSScreen *screen = [NSScreen mainScreen];
3770 return [screen frame].size.height;
3774 x_display_pixel_width (struct ns_display_info *dpyinfo)
3776 NSScreen *screen = [NSScreen mainScreen];
3777 return [screen frame].size.width;
3781 static Lisp_Object ns_string_to_lispmod (const char *s)
3782 /* --------------------------------------------------------------------------
3783 Convert modifier name to lisp symbol
3784 -------------------------------------------------------------------------- */
3786 if (!strncmp (SDATA (SYMBOL_NAME (Qmeta)), s, 10))
3788 else if (!strncmp (SDATA (SYMBOL_NAME (Qsuper)), s, 10))
3790 else if (!strncmp (SDATA (SYMBOL_NAME (Qcontrol)), s, 10))
3792 else if (!strncmp (SDATA (SYMBOL_NAME (Qalt)), s, 10))
3794 else if (!strncmp (SDATA (SYMBOL_NAME (Qhyper)), s, 10))
3796 else if (!strncmp (SDATA (SYMBOL_NAME (Qnone)), s, 10))
3803 static Lisp_Object ns_mod_to_lisp (int m)
3804 /* --------------------------------------------------------------------------
3805 Convert modifier code (see lisp.h) to lisp symbol
3806 -------------------------------------------------------------------------- */
3810 else if (m == CHAR_SUPER)
3812 else if (m == CHAR_CTL)
3814 else if (m == CHAR_ALT)
3816 else if (m == CHAR_HYPER)
3818 else /* if (m == 0) */
3824 ns_default (const char *parameter, Lisp_Object *result,
3825 Lisp_Object yesval, Lisp_Object noval,
3826 BOOL is_float, BOOL is_modstring)
3827 /* --------------------------------------------------------------------------
3828 Check a parameter value in user's preferences
3829 -------------------------------------------------------------------------- */
3831 const char *value = ns_get_defaults_value (parameter);
3837 if (strcasecmp (value, "YES") == 0)
3839 else if (strcasecmp (value, "NO") == 0)
3841 else if (is_float && (f = strtod (value, &pos), pos != value))
3842 *result = make_float (f);
3843 else if (is_modstring && value)
3844 *result = ns_string_to_lispmod (value);
3845 else fprintf (stderr,
3846 "Bad value for default \"%s\": \"%s\"\n", parameter, value);
3852 ns_initialize_display_info (struct ns_display_info *dpyinfo)
3853 /* --------------------------------------------------------------------------
3854 Initialize global info and storage for display.
3855 -------------------------------------------------------------------------- */
3857 NSScreen *screen = [NSScreen mainScreen];
3858 NSWindowDepth depth = [screen depth];
3859 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
3861 dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
3862 dpyinfo->resy = 72.27;
3863 dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
3864 NSColorSpaceFromDepth (depth)]
3865 && ![NSCalibratedWhiteColorSpace isEqualToString:
3866 NSColorSpaceFromDepth (depth)];
3867 dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
3868 dpyinfo->image_cache = make_image_cache ();
3869 dpyinfo->color_table
3870 = (struct ns_color_table *)xmalloc (sizeof (struct ns_color_table));
3871 dpyinfo->color_table->colors = NULL;
3872 dpyinfo->root_window = 42; /* a placeholder.. */
3874 hlinfo->mouse_face_mouse_frame = NULL;
3875 hlinfo->mouse_face_deferred_gc = 0;
3876 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
3877 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
3878 hlinfo->mouse_face_face_id = DEFAULT_FACE_ID;
3879 hlinfo->mouse_face_window = hlinfo->mouse_face_overlay = Qnil;
3880 hlinfo->mouse_face_hidden = 0;
3882 hlinfo->mouse_face_mouse_x = hlinfo->mouse_face_mouse_y = 0;
3883 hlinfo->mouse_face_defer = 0;
3885 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
3887 dpyinfo->n_fonts = 0;
3888 dpyinfo->smallest_font_height = 1;
3889 dpyinfo->smallest_char_width = 1;
3893 /* This and next define (many of the) public functions in this file. */
3894 /* x_... are generic versions in xdisp.c that we, and other terms, get away
3895 with using despite presence in the "system dependent" redisplay
3896 interface. In addition, many of the ns_ methods have code that is
3897 shared with all terms, indicating need for further refactoring. */
3898 extern frame_parm_handler ns_frame_parm_handlers[];
3899 static struct redisplay_interface ns_redisplay_interface =
3901 ns_frame_parm_handlers,
3905 x_clear_end_of_line,
3907 ns_after_update_window_line,
3908 ns_update_window_begin,
3909 ns_update_window_end,
3912 0, /* flush_display_optional */
3913 x_clear_window_mouse_face,
3914 x_get_glyph_overhangs,
3915 x_fix_overlapping_area,
3916 ns_draw_fringe_bitmap,
3917 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
3918 0, /* destroy_fringe_bitmap */
3919 ns_compute_glyph_string_overhangs,
3920 ns_draw_glyph_string, /* interface to nsfont.m */
3921 ns_define_frame_cursor,
3922 ns_clear_frame_area,
3923 ns_draw_window_cursor,
3924 ns_draw_vertical_window_border,
3925 ns_shift_glyphs_for_insert
3930 ns_delete_display (struct ns_display_info *dpyinfo)
3936 /* This function is called when the last frame on a display is deleted. */
3938 ns_delete_terminal (struct terminal *terminal)
3940 struct ns_display_info *dpyinfo = terminal->display_info.ns;
3943 /* Protect against recursive calls. delete_frame in
3944 delete_terminal calls us back when it deletes our last frame. */
3945 if (!terminal->name)
3950 x_destroy_all_bitmaps (dpyinfo);
3951 ns_delete_display (dpyinfo);
3956 static struct terminal *
3957 ns_create_terminal (struct ns_display_info *dpyinfo)
3958 /* --------------------------------------------------------------------------
3959 Set up use of NS before we make the first connection.
3960 -------------------------------------------------------------------------- */
3962 struct terminal *terminal;
3964 NSTRACE (ns_create_terminal);
3966 terminal = create_terminal ();
3968 terminal->type = output_ns;
3969 terminal->display_info.ns = dpyinfo;
3970 dpyinfo->terminal = terminal;
3972 terminal->rif = &ns_redisplay_interface;
3974 terminal->clear_frame_hook = ns_clear_frame;
3975 terminal->ins_del_lines_hook = 0; /* XXX vestigial? */
3976 terminal->delete_glyphs_hook = 0; /* XXX vestigial? */
3977 terminal->ring_bell_hook = ns_ring_bell;
3978 terminal->reset_terminal_modes_hook = ns_reset_terminal_modes;
3979 terminal->set_terminal_modes_hook = ns_set_terminal_modes;
3980 terminal->update_begin_hook = ns_update_begin;
3981 terminal->update_end_hook = ns_update_end;
3982 terminal->set_terminal_window_hook = NULL; /* XXX vestigial? */
3983 terminal->read_socket_hook = ns_read_socket;
3984 terminal->frame_up_to_date_hook = ns_frame_up_to_date;
3985 terminal->mouse_position_hook = ns_mouse_position;
3986 terminal->frame_rehighlight_hook = ns_frame_rehighlight;
3987 terminal->frame_raise_lower_hook = ns_frame_raise_lower;
3989 terminal->fullscreen_hook = 0; /* see XTfullscreen_hook */
3991 terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
3992 terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
3993 terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
3994 terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
3996 terminal->delete_frame_hook = x_destroy_window;
3997 terminal->delete_terminal_hook = ns_delete_terminal;
3999 terminal->scroll_region_ok = 1;
4000 terminal->char_ins_del_ok = 1;
4001 terminal->line_ins_del_ok = 1;
4002 terminal->fast_clear_end_of_line = 1;
4003 terminal->memory_below_frame = 0;
4009 struct ns_display_info *
4010 ns_term_init (Lisp_Object display_name)
4011 /* --------------------------------------------------------------------------
4012 Start the Application and get things rolling.
4013 -------------------------------------------------------------------------- */
4015 struct terminal *terminal;
4016 struct ns_display_info *dpyinfo;
4017 static int ns_initialized = 0;
4020 NSTRACE (ns_term_init);
4022 /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4023 /*GSDebugAllocationActive (YES); */
4025 handling_signal = 0;
4027 if (!ns_initialized)
4030 Fset_input_interrupt_mode (Qnil);
4034 ns_pending_files = [[NSMutableArray alloc] init];
4035 ns_pending_service_names = [[NSMutableArray alloc] init];
4036 ns_pending_service_args = [[NSMutableArray alloc] init];
4038 /* Start app and create the main menu, window, view.
4039 Needs to be here because ns_initialize_display_info () uses AppKit classes.
4040 The view will then ask the NSApp to stop and return to Emacs. */
4041 [EmacsApp sharedApplication];
4044 [NSApp setDelegate: NSApp];
4046 /* debugging: log all notifications */
4047 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
4048 selector: @selector (logNotification:)
4049 name: nil object: nil]; */
4051 dpyinfo = (struct ns_display_info *)xmalloc (sizeof (struct ns_display_info));
4052 memset (dpyinfo, 0, sizeof (struct ns_display_info));
4054 ns_initialize_display_info (dpyinfo);
4055 terminal = ns_create_terminal (dpyinfo);
4057 terminal->kboard = (KBOARD *) xmalloc (sizeof (KBOARD));
4058 init_kboard (terminal->kboard);
4059 KVAR (terminal->kboard, Vwindow_system) = Qns;
4060 terminal->kboard->next_kboard = all_kboards;
4061 all_kboards = terminal->kboard;
4062 /* Don't let the initial kboard remain current longer than necessary.
4063 That would cause problems if a file loaded on startup tries to
4064 prompt in the mini-buffer. */
4065 if (current_kboard == initial_kboard)
4066 current_kboard = terminal->kboard;
4067 terminal->kboard->reference_count++;
4069 dpyinfo->next = x_display_list;
4070 x_display_list = dpyinfo;
4072 /* Put it on ns_display_name_list */
4073 ns_display_name_list = Fcons (Fcons (display_name, Qnil),
4074 ns_display_name_list);
4075 dpyinfo->name_list_element = XCAR (ns_display_name_list);
4077 /* Set the name of the terminal. */
4078 terminal->name = (char *) xmalloc (SBYTES (display_name) + 1);
4079 strncpy (terminal->name, SDATA (display_name), SBYTES (display_name));
4080 terminal->name[SBYTES (display_name)] = 0;
4084 if (!inhibit_x_resources)
4086 ns_default ("GSFontAntiAlias", &ns_antialias_text,
4089 /* this is a standard variable */
4090 ns_default ("AppleAntiAliasingThreshold", &tmp,
4091 make_float (10.0), make_float (6.0), YES, NO);
4092 ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4095 ns_selection_color = [[NSUserDefaults standardUserDefaults]
4096 stringForKey: @"AppleHighlightColor"];
4097 if (ns_selection_color == nil)
4098 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
4101 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4105 Lisp_Object color_file, color_map, color;
4110 color_file = Fexpand_file_name (build_string ("rgb.txt"),
4111 Fsymbol_value (intern ("data-directory")));
4112 if (NILP (Ffile_readable_p (color_file)))
4113 fatal ("Could not find %s.\n", SDATA (color_file));
4115 color_map = Fx_load_color_file (color_file);
4116 if (NILP (color_map))
4117 fatal ("Could not read %s.\n", SDATA (color_file));
4119 cl = [[NSColorList alloc] initWithName: @"Emacs"];
4120 for ( ; CONSP (color_map); color_map = XCDR (color_map))
4122 color = XCAR (color_map);
4123 name = SDATA (XCAR (color));
4124 c = XINT (XCDR (color));
4126 [NSColor colorWithCalibratedRed: RED_FROM_ULONG (c) / 255.0
4127 green: GREEN_FROM_ULONG (c) / 255.0
4128 blue: BLUE_FROM_ULONG (c) / 255.0
4130 forKey: [NSString stringWithUTF8String: name]];
4132 [cl writeToFile: nil];
4138 #ifdef NS_IMPL_GNUSTEP
4139 strncpy (c, gnustep_base_version, sizeof (c));
4141 /*PSnextrelease (128, c); */
4142 snprintf (c, sizeof (c), "%g", NSAppKitVersionNumber);
4144 Vwindow_system_version = build_string (c);
4147 delete_keyboard_wait_descriptor (0);
4149 ns_app_name = [[NSProcessInfo processInfo] processName];
4151 /* Set up OS X app menu */
4152 #ifdef NS_IMPL_COCOA
4156 /* set up the application menu */
4157 svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4158 [svcsMenu setAutoenablesItems: NO];
4159 appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4160 [appMenu setAutoenablesItems: NO];
4161 mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4162 dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4164 [appMenu insertItemWithTitle: @"About Emacs"
4165 action: @selector (orderFrontStandardAboutPanel:)
4168 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4169 [appMenu insertItemWithTitle: @"Preferences..."
4170 action: @selector (showPreferencesWindow:)
4173 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4174 item = [appMenu insertItemWithTitle: @"Services"
4175 action: @selector (menuDown:)
4178 [appMenu setSubmenu: svcsMenu forItem: item];
4179 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4180 [appMenu insertItemWithTitle: @"Hide Emacs"
4181 action: @selector (hide:)
4184 item = [appMenu insertItemWithTitle: @"Hide Others"
4185 action: @selector (hideOtherApplications:)
4188 [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4189 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4190 [appMenu insertItemWithTitle: @"Quit Emacs"
4191 action: @selector (terminate:)
4195 item = [mainMenu insertItemWithTitle: ns_app_name
4196 action: @selector (menuDown:)
4199 [mainMenu setSubmenu: appMenu forItem: item];
4200 [dockMenu insertItemWithTitle: @"New Frame"
4201 action: @selector (newFrame:)
4205 [NSApp setMainMenu: mainMenu];
4206 [NSApp setAppleMenu: appMenu];
4207 [NSApp setServicesMenu: svcsMenu];
4208 /* Needed at least on Cocoa, to get dock menu to show windows */
4209 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4211 [[NSNotificationCenter defaultCenter]
4212 addObserver: mainMenu
4213 selector: @selector (trackingNotification:)
4214 name: NSMenuDidBeginTrackingNotification object: mainMenu];
4215 [[NSNotificationCenter defaultCenter]
4216 addObserver: mainMenu
4217 selector: @selector (trackingNotification:)
4218 name: NSMenuDidEndTrackingNotification object: mainMenu];
4220 #endif /* MAC OS X menu setup */
4229 ns_term_shutdown (int sig)
4231 [[NSUserDefaults standardUserDefaults] synchronize];
4233 /* code not reached in emacs.c after this is called by shut_down_emacs: */
4234 if (STRINGP (Vauto_save_list_file_name))
4235 unlink (SDATA (Vauto_save_list_file_name));
4237 if (sig == 0 || sig == SIGTERM)
4239 [NSApp terminate: NSApp];
4241 else // force a stack trace to happen
4248 /* ==========================================================================
4250 EmacsApp implementation
4252 ========================================================================== */
4255 @implementation EmacsApp
4257 - (void)logNotification: (NSNotification *)notification
4259 const char *name = [[notification name] UTF8String];
4260 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4261 && !strstr (name, "WindowNumber"))
4262 NSLog (@"notification: '%@'", [notification name]);
4266 - (void)sendEvent: (NSEvent *)theEvent
4267 /* --------------------------------------------------------------------------
4268 Called when NSApp is running for each event received. Used to stop
4269 the loop when we choose, since there's no way to just run one iteration.
4270 -------------------------------------------------------------------------- */
4272 int type = [theEvent type];
4273 NSWindow *window = [theEvent window];
4274 /* NSTRACE (sendEvent); */
4275 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4277 #ifdef NS_IMPL_COCOA
4278 if (type == NSApplicationDefined
4279 && [theEvent data2] == NSAPP_DATA2_RUNASSCRIPT)
4287 if (type == NSCursorUpdate && window == nil)
4289 fprintf (stderr, "Dropping external cursor update event.\n");
4293 #ifdef NS_IMPL_COCOA
4294 /* pass mouse down in resize handle and subsequent drags directly to
4295 EmacsWindow so we can generate continuous redisplays */
4298 if (type == NSLeftMouseDragged)
4300 [window mouseDragged: theEvent];
4303 else if (type == NSLeftMouseUp)
4305 [window mouseUp: theEvent];
4309 else if (type == NSLeftMouseDown)
4311 NSRect r = ns_resize_handle_rect (window);
4312 if (NSPointInRect ([theEvent locationInWindow], r))
4315 [window mouseDown: theEvent];
4321 if (type == NSApplicationDefined)
4323 /* Events posted by ns_send_appdefined interrupt the run loop here.
4324 But, if a modal window is up, an appdefined can still come through,
4325 (e.g., from a makeKeyWindow event) but stopping self also stops the
4326 modal loop. Just defer it until later. */
4327 if ([NSApp modalWindow] == nil)
4329 last_appdefined_event = theEvent;
4334 send_appdefined = YES;
4338 [super sendEvent: theEvent];
4342 - (void)showPreferencesWindow: (id)sender
4344 struct frame *emacsframe = SELECTED_FRAME ();
4345 NSEvent *theEvent = [NSApp currentEvent];
4349 emacs_event->kind = NS_NONKEY_EVENT;
4350 emacs_event->code = KEY_NS_SHOW_PREFS;
4351 emacs_event->modifiers = 0;
4352 EV_TRAILER (theEvent);
4356 - (void)newFrame: (id)sender
4358 struct frame *emacsframe = SELECTED_FRAME ();
4359 NSEvent *theEvent = [NSApp currentEvent];
4363 emacs_event->kind = NS_NONKEY_EVENT;
4364 emacs_event->code = KEY_NS_NEW_FRAME;
4365 emacs_event->modifiers = 0;
4366 EV_TRAILER (theEvent);
4370 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4371 - (BOOL) openFile: (NSString *)fileName
4373 struct frame *emacsframe = SELECTED_FRAME ();
4374 NSEvent *theEvent = [NSApp currentEvent];
4379 emacs_event->kind = NS_NONKEY_EVENT;
4380 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4381 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4382 ns_input_line = Qnil; /* can be start or cons start,end */
4383 emacs_event->modifiers =0;
4384 EV_TRAILER (theEvent);
4390 /* **************************************************************************
4392 EmacsApp delegate implementation
4394 ************************************************************************** */
4396 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4397 /* --------------------------------------------------------------------------
4398 When application is loaded, terminate event loop in ns_term_init
4399 -------------------------------------------------------------------------- */
4401 NSTRACE (applicationDidFinishLaunching);
4402 [NSApp setServicesProvider: NSApp];
4403 ns_send_appdefined (-2);
4407 /* Termination sequences:
4410 MenuBar | File | Exit:
4411 Select Quit from App menubar:
4413 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4416 Select Quit from Dock menu:
4419 Cancel -> Nothing else
4423 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4428 - (void) terminate: (id)sender
4430 struct frame *emacsframe = SELECTED_FRAME ();
4435 emacs_event->kind = NS_NONKEY_EVENT;
4436 emacs_event->code = KEY_NS_POWER_OFF;
4437 emacs_event->arg = Qt; /* mark as non-key event */
4438 EV_TRAILER ((id)nil);
4442 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4446 if (NILP (ns_confirm_quit)) // || ns_shutdown_properly --> TO DO
4447 return NSTerminateNow;
4449 ret = NSRunAlertPanel(ns_app_name,
4450 [NSString stringWithUTF8String:"Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?"],
4451 @"Save Buffers and Exit", @"Cancel", nil);
4453 if (ret == NSAlertDefaultReturn)
4454 return NSTerminateNow;
4455 else if (ret == NSAlertAlternateReturn)
4456 return NSTerminateCancel;
4457 return NSTerminateNow; /* just in case */
4461 /* Notification from the Workspace to open a file */
4462 - (BOOL)application: sender openFile: (NSString *)file
4464 [ns_pending_files addObject: file];
4469 /* Open a file as a temporary file */
4470 - (BOOL)application: sender openTempFile: (NSString *)file
4472 [ns_pending_files addObject: file];
4477 /* Notification from the Workspace to open a file noninteractively (?) */
4478 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4480 [ns_pending_files addObject: file];
4485 /* Notification from the Workspace to open multiple files */
4486 - (void)application: sender openFiles: (NSArray *)fileList
4488 NSEnumerator *files = [fileList objectEnumerator];
4490 while ((file = [files nextObject]) != nil)
4491 [ns_pending_files addObject: file];
4493 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4498 /* Handle dock menu requests. */
4499 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4505 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4506 - (void)applicationWillBecomeActive: (NSNotification *)notification
4508 //ns_app_active=YES;
4510 - (void)applicationDidBecomeActive: (NSNotification *)notification
4512 NSTRACE (applicationDidBecomeActive);
4514 //ns_app_active=YES;
4516 ns_update_auto_hide_menu_bar ();
4517 // No constraining takes place when the application is not active.
4518 ns_constrain_all_frames ();
4520 - (void)applicationDidResignActive: (NSNotification *)notification
4523 ns_send_appdefined (-1);
4528 /* ==========================================================================
4530 EmacsApp aux handlers for managing event loop
4532 ========================================================================== */
4535 - (void)timeout_handler: (NSTimer *)timedEntry
4536 /* --------------------------------------------------------------------------
4537 The timeout specified to ns_select has passed.
4538 -------------------------------------------------------------------------- */
4540 /*NSTRACE (timeout_handler); */
4541 ns_send_appdefined (-2);
4544 - (void)fd_handler: (NSTimer *) fdEntry
4545 /* --------------------------------------------------------------------------
4546 Check data waiting on file descriptors and terminate if so
4547 -------------------------------------------------------------------------- */
4550 /* NSTRACE (fd_handler); */
4552 if (select_nfds == 0)
4555 memcpy (&t_readfds, &select_readfds, sizeof (fd_set));
4557 select_timeout.tv_sec = select_timeout.tv_usec = 0;
4558 result = select (select_nfds, &t_readfds, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
4562 memcpy (&select_readfds, &t_readfds, sizeof (fd_set));
4563 ns_send_appdefined (result);
4569 /* ==========================================================================
4573 ========================================================================== */
4575 /* called from system: queue for next pass through event loop */
4576 - (void)requestService: (NSPasteboard *)pboard
4577 userData: (NSString *)userData
4578 error: (NSString **)error
4580 [ns_pending_service_names addObject: userData];
4581 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
4582 SDATA (ns_string_from_pasteboard (pboard))]];
4586 /* called from ns_read_socket to clear queue */
4587 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
4589 struct frame *emacsframe = SELECTED_FRAME ();
4590 NSEvent *theEvent = [NSApp currentEvent];
4595 emacs_event->kind = NS_NONKEY_EVENT;
4596 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
4597 ns_input_spi_name = build_string ([name UTF8String]);
4598 ns_input_spi_arg = build_string ([arg UTF8String]);
4599 emacs_event->modifiers = EV_MODIFIERS (theEvent);
4600 EV_TRAILER (theEvent);
4610 /* ==========================================================================
4612 EmacsView implementation
4614 ========================================================================== */
4617 @implementation EmacsView
4619 /* needed to inform when window closed from LISP */
4620 - (void) setWindowClosing: (BOOL)closing
4622 windowClosing = closing;
4628 NSTRACE (EmacsView_dealloc);
4634 /* called on font panel selection */
4635 - (void)changeFont: (id)sender
4637 NSEvent *e =[[self window] currentEvent];
4638 struct face *face =FRAME_DEFAULT_FACE (emacsframe);
4642 NSTRACE (changeFont);
4646 if (newFont = [sender convertFont:
4647 ((struct nsfont_info *)face->font)->nsfont])
4649 SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
4651 emacs_event->kind = NS_NONKEY_EVENT;
4652 emacs_event->modifiers = 0;
4653 emacs_event->code = KEY_NS_CHANGE_FONT;
4655 size = [newFont pointSize];
4656 ns_input_fontsize = make_number (lrint (size));
4657 ns_input_font = build_string ([[newFont familyName] UTF8String]);
4663 - (BOOL)acceptsFirstResponder
4665 NSTRACE (acceptsFirstResponder);
4670 - (void)resetCursorRects
4672 NSRect visible = [self visibleRect];
4673 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
4674 NSTRACE (resetCursorRects);
4676 if (currentCursor == nil)
4677 currentCursor = [NSCursor arrowCursor];
4679 if (!NSIsEmptyRect (visible))
4680 [self addCursorRect: visible cursor: currentCursor];
4681 [currentCursor setOnMouseEntered: YES];
4686 /*****************************************************************************/
4687 /* Keyboard handling. */
4690 - (void)keyDown: (NSEvent *)theEvent
4692 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
4694 unsigned fnKeysym = 0;
4696 static NSMutableArray *nsEvArray;
4697 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
4698 static BOOL firstTime = YES;
4704 /* Rhapsody and OS X give up and down events for the arrow keys */
4705 if (ns_fake_keydown == YES)
4706 ns_fake_keydown = NO;
4707 else if ([theEvent type] != NSKeyDown)
4713 if (![[self window] isKeyWindow]
4714 && [[theEvent window] isKindOfClass: [EmacsWindow class]]
4715 /* we must avoid an infinite loop here. */
4716 && (EmacsView *)[[theEvent window] delegate] != self)
4718 /* XXX: There is an occasional condition in which, when Emacs display
4719 updates a different frame from the current one, and temporarily
4720 selects it, then processes some interrupt-driven input
4721 (dispnew.c:3878), OS will send the event to the correct NSWindow, but
4722 for some reason that window has its first responder set to the NSView
4723 most recently updated (I guess), which is not the correct one. */
4724 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
4728 if (nsEvArray == nil)
4729 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
4731 [NSCursor setHiddenUntilMouseMoves: YES];
4733 if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
4735 clear_mouse_face (hlinfo);
4736 hlinfo->mouse_face_hidden = 1;
4739 if (!processingCompose)
4741 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
4742 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
4743 /* (Carbon way: [theEvent keyCode]) */
4745 /* is it a "function key"? */
4746 fnKeysym = ns_convert_key (code);
4749 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
4750 because Emacs treats Delete and KP-Delete same (in simple.el). */
4751 if (fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
4752 code = 0xFF08; /* backspace */
4757 /* are there modifiers? */
4758 emacs_event->modifiers = 0;
4759 flags = [theEvent modifierFlags];
4761 if (flags & NSHelpKeyMask)
4762 emacs_event->modifiers |= hyper_modifier;
4764 if (flags & NSShiftKeyMask)
4765 emacs_event->modifiers |= shift_modifier;
4767 if ((flags & NSRightCommandKeyMask) == NSRightCommandKeyMask)
4768 emacs_event->modifiers |= parse_solitary_modifier
4769 (EQ (ns_right_command_modifier, Qleft)
4770 ? ns_command_modifier
4771 : ns_right_command_modifier);
4773 if ((flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask)
4775 emacs_event->modifiers |= parse_solitary_modifier
4776 (ns_command_modifier);
4778 /* if super (default), take input manager's word so things like
4779 dvorak / qwerty layout work */
4780 if (EQ (ns_command_modifier, Qsuper)
4782 && [[theEvent characters] length] != 0)
4784 /* XXX: the code we get will be unshifted, so if we have
4785 a shift modifier, must convert ourselves */
4786 if (!(flags & NSShiftKeyMask))
4787 code = [[theEvent characters] characterAtIndex: 0];
4789 /* this is ugly and also requires linking w/Carbon framework
4790 (for LMGetKbdType) so for now leave this rare (?) case
4791 undealt with.. in future look into CGEvent methods */
4794 long smv = GetScriptManagerVariable (smKeyScript);
4795 Handle uchrHandle = GetResource
4796 ('uchr', GetScriptVariable (smv, smScriptKeys));
4798 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
4799 [[theEvent characters] characterAtIndex: 0],
4800 kUCKeyActionDisplay,
4801 (flags & ~NSCommandKeyMask) >> 8,
4802 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
4803 &dummy, 1, &dummy, &code);
4810 if ((flags & NSRightControlKeyMask) == NSRightControlKeyMask)
4811 emacs_event->modifiers |= parse_solitary_modifier
4812 (EQ (ns_right_control_modifier, Qleft)
4813 ? ns_control_modifier
4814 : ns_right_control_modifier);
4816 if ((flags & NSLeftControlKeyMask) == NSLeftControlKeyMask)
4817 emacs_event->modifiers |= parse_solitary_modifier
4818 (ns_control_modifier);
4820 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
4821 emacs_event->modifiers |=
4822 parse_solitary_modifier (ns_function_modifier);
4824 left_is_none = NILP (ns_alternate_modifier)
4825 || EQ (ns_alternate_modifier, Qnone);
4827 if ((flags & NSRightAlternateKeyMask) == NSRightAlternateKeyMask)
4829 if ((NILP (ns_right_alternate_modifier)
4830 || EQ (ns_right_alternate_modifier, Qnone)
4831 || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
4833 { /* accept pre-interp alt comb */
4834 if ([[theEvent characters] length] > 0)
4835 code = [[theEvent characters] characterAtIndex: 0];
4836 /*HACK: clear lone shift modifier to stop next if from firing */
4837 if (emacs_event->modifiers == shift_modifier)
4838 emacs_event->modifiers = 0;
4841 emacs_event->modifiers |= parse_solitary_modifier
4842 (EQ (ns_right_alternate_modifier, Qleft)
4843 ? ns_alternate_modifier
4844 : ns_right_alternate_modifier);
4847 if ((flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask) /* default = meta */
4849 if (left_is_none && !fnKeysym)
4850 { /* accept pre-interp alt comb */
4851 if ([[theEvent characters] length] > 0)
4852 code = [[theEvent characters] characterAtIndex: 0];
4853 /*HACK: clear lone shift modifier to stop next if from firing */
4854 if (emacs_event->modifiers == shift_modifier)
4855 emacs_event->modifiers = 0;
4858 emacs_event->modifiers |=
4859 parse_solitary_modifier (ns_alternate_modifier);
4863 fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
4864 code, fnKeysym, flags, emacs_event->modifiers);
4866 /* if it was a function key or had modifiers, pass it directly to emacs */
4867 if (fnKeysym || (emacs_event->modifiers
4868 && (emacs_event->modifiers != shift_modifier)
4869 && [[theEvent charactersIgnoringModifiers] length] > 0))
4870 /*[[theEvent characters] length] */
4872 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4874 code |= (1<<28)|(3<<16);
4875 else if (code == 0x7f)
4876 code |= (1<<28)|(3<<16);
4878 emacs_event->kind = code > 0xFF
4879 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4881 emacs_event->code = code;
4882 EV_TRAILER (theEvent);
4888 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
4889 /* if we get here we should send the key for input manager processing */
4890 if (firstTime && [[NSInputManager currentInputManager]
4891 wantsToDelayTextChangeNotifications] == NO)
4893 "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
4896 if (NS_KEYLOG && !processingCompose)
4897 fprintf (stderr, "keyDown: Begin compose sequence.\n");
4899 processingCompose = YES;
4900 [nsEvArray addObject: theEvent];
4901 [self interpretKeyEvents: nsEvArray];
4902 [nsEvArray removeObject: theEvent];
4906 #ifdef NS_IMPL_COCOA
4907 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
4908 decided not to send key-down for.
4909 See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
4910 This only applies on Tiger and earlier.
4911 If it matches one of these, send it on to keyDown. */
4912 -(void)keyUp: (NSEvent *)theEvent
4914 int flags = [theEvent modifierFlags];
4915 int code = [theEvent keyCode];
4916 if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
4917 code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
4920 fprintf (stderr, "keyUp: passed test");
4921 ns_fake_keydown = YES;
4922 [self keyDown: theEvent];
4928 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
4931 /* <NSTextInput>: called when done composing;
4932 NOTE: also called when we delete over working text, followed immed.
4933 by doCommandBySelector: deleteBackward: */
4934 - (void)insertText: (id)aString
4937 int len = [(NSString *)aString length];
4941 NSLog (@"insertText '%@'\tlen = %d", aString, len);
4942 processingCompose = NO;
4947 /* first, clear any working text */
4948 if (workingText != nil)
4949 [self deleteWorkingText];
4951 /* now insert the string as keystrokes */
4952 for (i =0; i<len; i++)
4954 code = [aString characterAtIndex: i];
4955 /* TODO: still need this? */
4957 code = '~'; /* 0x7E */
4958 emacs_event->modifiers = 0;
4960 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4961 emacs_event->code = code;
4962 EV_TRAILER ((id)nil);
4967 /* <NSTextInput>: inserts display of composing characters */
4968 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
4970 NSString *str = [aString respondsToSelector: @selector (string)] ?
4971 [aString string] : aString;
4973 NSLog (@"setMarkedText '%@' len =%d range %d from %d", str, [str length],
4974 selRange.length, selRange.location);
4976 if (workingText != nil)
4977 [self deleteWorkingText];
4978 if ([str length] == 0)
4984 processingCompose = YES;
4985 workingText = [str copy];
4986 ns_working_text = build_string ([workingText UTF8String]);
4988 emacs_event->kind = NS_TEXT_EVENT;
4989 emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
4990 EV_TRAILER ((id)nil);
4994 /* delete display of composing characters [not in <NSTextInput>] */
4995 - (void)deleteWorkingText
4997 if (workingText == nil)
5000 NSLog(@"deleteWorkingText len =%d\n", [workingText length]);
5001 [workingText release];
5003 processingCompose = NO;
5008 emacs_event->kind = NS_TEXT_EVENT;
5009 emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
5010 EV_TRAILER ((id)nil);
5014 - (BOOL)hasMarkedText
5016 return workingText != nil;
5020 - (NSRange)markedRange
5022 NSRange rng = workingText != nil
5023 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
5025 NSLog (@"markedRange request");
5033 NSLog (@"unmark (accept) text");
5034 [self deleteWorkingText];
5035 processingCompose = NO;
5039 /* used to position char selection windows, etc. */
5040 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
5044 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
5046 NSLog (@"firstRectForCharRange request");
5048 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
5049 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
5050 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
5051 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
5052 +FRAME_LINE_HEIGHT (emacsframe));
5054 pt = [self convertPoint: pt toView: nil];
5055 pt = [[self window] convertBaseToScreen: pt];
5061 - (long)conversationIdentifier
5067 - (void)doCommandBySelector: (SEL)aSelector
5070 NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
5072 if (aSelector == @selector (deleteBackward:))
5074 /* happens when user backspaces over an ongoing composition:
5075 throw a 'delete' into the event queue */
5078 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5079 emacs_event->code = 0xFF08;
5080 EV_TRAILER ((id)nil);
5084 - (NSArray *)validAttributesForMarkedText
5086 static NSArray *arr = nil;
5087 if (arr == nil) arr = [NSArray new];
5088 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
5092 - (NSRange)selectedRange
5095 NSLog (@"selectedRange request");
5096 return NSMakeRange (NSNotFound, 0);
5099 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
5102 NSLog (@"characterIndexForPoint request");
5106 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
5108 static NSAttributedString *str = nil;
5109 if (str == nil) str = [NSAttributedString new];
5111 NSLog (@"attributedSubstringFromRange request");
5115 /* End <NSTextInput> impl. */
5116 /*****************************************************************************/
5119 /* This is what happens when the user presses a mouse button. */
5120 - (void)mouseDown: (NSEvent *)theEvent
5122 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5125 NSTRACE (mouseDown);
5127 [self deleteWorkingText];
5132 last_mouse_frame = emacsframe;
5133 /* appears to be needed to prevent spurious movement events generated on
5135 last_mouse_frame->mouse_moved = 0;
5137 if ([theEvent type] == NSScrollWheel)
5139 float delta = [theEvent deltaY];
5140 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
5143 emacs_event->kind = WHEEL_EVENT;
5144 emacs_event->code = 0;
5145 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
5146 ((delta > 0) ? up_modifier : down_modifier);
5150 emacs_event->kind = MOUSE_CLICK_EVENT;
5151 emacs_event->code = EV_BUTTON (theEvent);
5152 emacs_event->modifiers = EV_MODIFIERS (theEvent)
5153 | EV_UDMODIFIERS (theEvent);
5155 XSETINT (emacs_event->x, lrint (p.x));
5156 XSETINT (emacs_event->y, lrint (p.y));
5157 EV_TRAILER (theEvent);
5161 - (void)rightMouseDown: (NSEvent *)theEvent
5163 NSTRACE (rightMouseDown);
5164 [self mouseDown: theEvent];
5168 - (void)otherMouseDown: (NSEvent *)theEvent
5170 NSTRACE (otherMouseDown);
5171 [self mouseDown: theEvent];
5175 - (void)mouseUp: (NSEvent *)theEvent
5178 [self mouseDown: theEvent];
5182 - (void)rightMouseUp: (NSEvent *)theEvent
5184 NSTRACE (rightMouseUp);
5185 [self mouseDown: theEvent];
5189 - (void)otherMouseUp: (NSEvent *)theEvent
5191 NSTRACE (otherMouseUp);
5192 [self mouseDown: theEvent];
5196 - (void) scrollWheel: (NSEvent *)theEvent
5198 NSTRACE (scrollWheel);
5199 [self mouseDown: theEvent];
5203 /* Tell emacs the mouse has moved. */
5204 - (void)mouseMoved: (NSEvent *)e
5206 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5209 // NSTRACE (mouseMoved);
5211 last_mouse_movement_time = EV_TIMESTAMP (e);
5212 last_mouse_motion_position
5213 = [self convertPoint: [e locationInWindow] fromView: nil];
5215 /* update any mouse face */
5216 if (hlinfo->mouse_face_hidden)
5218 hlinfo->mouse_face_hidden = 0;
5219 clear_mouse_face (hlinfo);
5222 /* tooltip handling */
5223 previous_help_echo_string = help_echo_string;
5224 help_echo_string = Qnil;
5226 if (!note_mouse_movement (emacsframe, last_mouse_motion_position.x,
5227 last_mouse_motion_position.y))
5228 help_echo_string = previous_help_echo_string;
5230 XSETFRAME (frame, emacsframe);
5231 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
5233 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
5234 (note_mouse_highlight), which is called through the
5235 note_mouse_movement () call above */
5236 gen_help_event (help_echo_string, frame, help_echo_window,
5237 help_echo_object, help_echo_pos);
5241 help_echo_string = Qnil;
5242 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
5245 if (emacsframe->mouse_moved && send_appdefined)
5246 ns_send_appdefined (-1);
5250 - (void)mouseDragged: (NSEvent *)e
5252 NSTRACE (mouseDragged);
5253 [self mouseMoved: e];
5257 - (void)rightMouseDragged: (NSEvent *)e
5259 NSTRACE (rightMouseDragged);
5260 [self mouseMoved: e];
5264 - (void)otherMouseDragged: (NSEvent *)e
5266 NSTRACE (otherMouseDragged);
5267 [self mouseMoved: e];
5271 - (BOOL)windowShouldClose: (id)sender
5273 NSEvent *e =[[self window] currentEvent];
5275 NSTRACE (windowShouldClose);
5276 windowClosing = YES;
5279 emacs_event->kind = DELETE_WINDOW_EVENT;
5280 emacs_event->modifiers = 0;
5281 emacs_event->code = 0;
5283 /* Don't close this window, let this be done from lisp code. */
5288 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
5289 /* normalize frame to gridded text size */
5291 NSTRACE (windowWillResize);
5292 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
5294 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe,
5295 #ifdef NS_IMPL_GNUSTEP
5296 frameSize.width + 3);
5300 if (cols < MINWIDTH)
5303 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, frameSize.height
5304 #ifdef NS_IMPL_GNUSTEP
5305 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe) + 3
5306 - FRAME_TOOLBAR_HEIGHT (emacsframe));
5308 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5309 - FRAME_TOOLBAR_HEIGHT (emacsframe));
5311 if (rows < MINHEIGHT)
5313 #ifdef NS_IMPL_COCOA
5315 /* this sets window title to have size in it; the wm does this under GS */
5316 NSRect r = [[self window] frame];
5317 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
5328 NSWindow *window = [self window];
5331 const char *t = [[[self window] title] UTF8String];
5332 char *pos = strstr (t, " — ");
5335 old_title = (char *) xmalloc (strlen (t) + 1);
5336 strcpy (old_title, t);
5338 size_title = xmalloc (strlen (old_title) + 40);
5339 esprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
5340 [window setTitle: [NSString stringWithUTF8String: size_title]];
5345 #endif /* NS_IMPL_COCOA */
5346 /*fprintf (stderr," ...size became %.0f x %.0f (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
5352 - (void)windowDidResize: (NSNotification *)notification
5354 NSWindow *theWindow = [notification object];
5356 #ifdef NS_IMPL_GNUSTEP
5357 /* in GNUstep, at least currently, it's possible to get a didResize
5358 without getting a willResize.. therefore we need to act as if we got
5359 the willResize now */
5360 NSSize sz = [theWindow frame].size;
5361 sz = [self windowWillResize: theWindow toSize: sz];
5362 #endif /* NS_IMPL_GNUSTEP */
5364 NSTRACE (windowDidResize);
5365 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
5367 #ifdef NS_IMPL_COCOA
5373 #endif /* NS_IMPL_COCOA */
5375 /* Avoid loop under GNUstep due to call at beginning of this function.
5376 (x_set_window_size causes a resize which causes
5377 a "windowDidResize" which calls x_set_window_size). */
5378 #ifndef NS_IMPL_GNUSTEP
5379 if (cols > 0 && rows > 0)
5382 x_set_window_size (emacsframe, 0, cols, rows);
5385 NSWindow *window = [self window];
5386 NSRect wr = [window frame];
5387 FRAME_PIXEL_WIDTH (emacsframe) = (int)wr.size.width
5388 - emacsframe->border_width;
5389 FRAME_PIXEL_HEIGHT (emacsframe) = (int)wr.size.height
5390 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5391 - FRAME_TOOLBAR_HEIGHT (emacsframe);
5392 change_frame_size (emacsframe, rows, cols, 0, 0, 1);
5393 SET_FRAME_GARBAGED (emacsframe);
5394 cancel_mouse_face (emacsframe);
5399 ns_send_appdefined (-1);
5403 - (void)windowDidBecomeKey: (NSNotification *)notification
5404 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5406 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5407 struct frame *old_focus = dpyinfo->x_focus_frame;
5409 NSTRACE (windowDidBecomeKey);
5411 if (emacsframe != old_focus)
5412 dpyinfo->x_focus_frame = emacsframe;
5414 ns_frame_rehighlight (emacsframe);
5418 emacs_event->kind = FOCUS_IN_EVENT;
5419 EV_TRAILER ((id)nil);
5424 - (void)windowDidResignKey: (NSNotification *)notification
5425 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5427 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5428 NSTRACE (windowDidResignKey);
5430 if (dpyinfo->x_focus_frame == emacsframe)
5431 dpyinfo->x_focus_frame = 0;
5433 ns_frame_rehighlight (emacsframe);
5435 /* FIXME: for some reason needed on second and subsequent clicks away
5436 from sole-frame Emacs to get hollow box to show */
5437 if (!windowClosing && [[self window] isVisible] == YES)
5439 x_update_cursor (emacsframe, 1);
5440 x_set_frame_alpha (emacsframe);
5445 [self deleteWorkingText];
5446 emacs_event->kind = FOCUS_IN_EVENT;
5447 EV_TRAILER ((id)nil);
5452 - (void)windowWillMiniaturize: sender
5454 NSTRACE (windowWillMiniaturize);
5470 - initFrameFromEmacs: (struct frame *)f
5475 NSButton *toggleButton;
5476 int vbextra = NS_SCROLL_BAR_WIDTH (f);
5481 NSTRACE (initFrameFromEmacs);
5484 processingCompose = NO;
5485 scrollbarsNeedingUpdate = 0;
5487 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
5489 ns_userRect = NSMakeRect (0, 0, 0, 0);
5490 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
5491 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
5492 [self initWithFrame: r];
5493 [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
5495 FRAME_NS_VIEW (f) = self;
5499 win = [[EmacsWindow alloc]
5500 initWithContentRect: r
5501 styleMask: (NSResizableWindowMask |
5502 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
5503 NSTitledWindowMask |
5505 NSMiniaturizableWindowMask |
5506 NSClosableWindowMask)
5507 backing: NSBackingStoreBuffered
5511 f->border_width = wr.size.width - r.size.width;
5512 FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
5514 [win setAcceptsMouseMovedEvents: YES];
5515 [win setDelegate: self];
5516 [win useOptimizedDrawing: YES];
5518 sz.width = FRAME_COLUMN_WIDTH (f);
5519 sz.height = FRAME_LINE_HEIGHT (f);
5520 [win setResizeIncrements: sz];
5522 [[win contentView] addSubview: self];
5525 [self registerForDraggedTypes: ns_drag_types];
5528 name = [NSString stringWithUTF8String:
5529 NILP (tem) ? (unsigned char *)"Emacs" : SDATA (tem)];
5530 [win setTitle: name];
5532 /* toolbar support */
5533 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
5534 [NSString stringWithFormat: @"Emacs Frame %d",
5536 [win setToolbar: toolbar];
5537 [toolbar setVisible: NO];
5538 #ifdef NS_IMPL_COCOA
5539 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
5540 [toggleButton setTarget: self];
5541 [toggleButton setAction: @selector (toggleToolbar: )];
5543 FRAME_TOOLBAR_HEIGHT (f) = 0;
5547 [win setMiniwindowTitle:
5548 [NSString stringWithUTF8String: SDATA (tem)]];
5551 NSScreen *screen = [win screen];
5554 [win setFrameTopLeftPoint: NSMakePoint
5555 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
5556 IN_BOUND (-SCREENMAX,
5557 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
5560 [win makeFirstResponder: self];
5562 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5563 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
5564 [win setBackgroundColor: col];
5565 if ([col alphaComponent] != 1.0)
5566 [win setOpaque: NO];
5568 [self allocateGState];
5570 [NSApp registerServicesMenuSendTypes: ns_send_types
5578 - (void)windowDidMove: sender
5580 NSWindow *win = [self window];
5581 NSRect r = [win frame];
5582 NSArray *screens = [NSScreen screens];
5583 NSScreen *screen = [screens objectAtIndex: 0];
5585 NSTRACE (windowDidMove);
5587 if (!emacsframe->output_data.ns)
5591 emacsframe->left_pos = r.origin.x;
5592 emacsframe->top_pos =
5593 [screen frame].size.height - (r.origin.y + r.size.height);
5598 /* Called AFTER method below, but before our windowWillResize call there leads
5599 to windowDidResize -> x_set_window_size. Update emacs' notion of frame
5600 location so set_window_size moves the frame. */
5601 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
5603 emacsframe->output_data.ns->zooming = 1;
5608 /* Override to do something slightly nonstandard, but nice. First click on
5609 zoom button will zoom vertically. Second will zoom completely. Third
5610 returns to original. */
5611 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
5612 defaultFrame:(NSRect)defaultFrame
5614 NSRect result = [sender frame];
5616 NSTRACE (windowWillUseStandardFrame);
5618 if (abs (defaultFrame.size.height - result.size.height)
5619 > FRAME_LINE_HEIGHT (emacsframe))
5622 ns_userRect = result;
5623 result.size.height = defaultFrame.size.height;
5624 result.origin.y = defaultFrame.origin.y;
5628 if (abs (defaultFrame.size.width - result.size.width)
5629 > FRAME_COLUMN_WIDTH (emacsframe))
5630 result = defaultFrame; /* second click */
5634 result = ns_userRect.size.height ? ns_userRect : result;
5635 ns_userRect = NSMakeRect (0, 0, 0, 0);
5639 [self windowWillResize: sender toSize: result.size];
5644 - (void)windowDidDeminiaturize: sender
5646 NSTRACE (windowDidDeminiaturize);
5647 if (!emacsframe->output_data.ns)
5649 emacsframe->async_iconified = 0;
5650 emacsframe->async_visible = 1;
5651 windows_or_buffers_changed++;
5655 emacs_event->kind = ICONIFY_EVENT;
5656 EV_TRAILER ((id)nil);
5661 - (void)windowDidExpose: sender
5663 NSTRACE (windowDidExpose);
5664 if (!emacsframe->output_data.ns)
5666 emacsframe->async_visible = 1;
5667 SET_FRAME_GARBAGED (emacsframe);
5669 if (send_appdefined)
5670 ns_send_appdefined (-1);
5674 - (void)windowDidMiniaturize: sender
5676 NSTRACE (windowDidMiniaturize);
5677 if (!emacsframe->output_data.ns)
5680 emacsframe->async_iconified = 1;
5681 emacsframe->async_visible = 0;
5685 emacs_event->kind = ICONIFY_EVENT;
5686 EV_TRAILER ((id)nil);
5691 - (void)mouseEntered: (NSEvent *)theEvent
5693 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5694 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5695 NSTRACE (mouseEntered);
5697 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5701 - (void)mouseExited: (NSEvent *)theEvent
5703 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5705 Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
5707 NSTRACE (mouseExited);
5712 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5714 if (emacsframe == hlinfo->mouse_face_mouse_frame)
5716 clear_mouse_face (hlinfo);
5717 hlinfo->mouse_face_mouse_frame = 0;
5725 if (context_menu_value == -1)
5726 context_menu_value = [sender tag];
5728 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
5729 emacsframe->menu_bar_vector,
5730 (void *)[sender tag]);
5731 ns_send_appdefined (-1);
5736 - (EmacsToolbar *)toolbar
5742 /* this gets called on toolbar button click */
5743 - toolbarClicked: (id)item
5746 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
5748 NSTRACE (toolbarClicked);
5753 /* send first event (for some reason two needed) */
5754 theEvent = [[self window] currentEvent];
5755 emacs_event->kind = TOOL_BAR_EVENT;
5756 XSETFRAME (emacs_event->arg, emacsframe);
5757 EV_TRAILER (theEvent);
5759 emacs_event->kind = TOOL_BAR_EVENT;
5760 /* XSETINT (emacs_event->code, 0); */
5761 emacs_event->arg = AREF (emacsframe->tool_bar_items,
5762 idx + TOOL_BAR_ITEM_KEY);
5763 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5764 EV_TRAILER (theEvent);
5769 - toggleToolbar: (id)sender
5774 emacs_event->kind = NS_NONKEY_EVENT;
5775 emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
5776 EV_TRAILER ((id)nil);
5781 - (void)drawRect: (NSRect)rect
5783 int x = NSMinX (rect), y = NSMinY (rect);
5784 int width = NSWidth (rect), height = NSHeight (rect);
5788 if (!emacsframe || !emacsframe->output_data.ns || ns_in_resize)
5791 ns_clear_frame_area (emacsframe, x, y, width, height);
5792 expose_frame (emacsframe, x, y, width, height);
5795 drawRect: may be called (at least in OS X 10.5) for invisible
5796 views as well for some reason. Thus, do not infer visibility
5799 emacsframe->async_visible = 1;
5800 emacsframe->async_iconified = 0;
5805 /* NSDraggingDestination protocol methods. Actually this is not really a
5806 protocol, but a category of Object. O well... */
5808 -(NSUInteger) draggingEntered: (id <NSDraggingInfo>) sender
5810 NSTRACE (draggingEntered);
5811 return NSDragOperationGeneric;
5815 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
5821 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
5826 NSEvent *theEvent = [[self window] currentEvent];
5829 NSTRACE (performDragOperation);
5834 position = [self convertPoint: [sender draggingLocation] fromView: nil];
5835 x = lrint (position.x); y = lrint (position.y);
5837 pb = [sender draggingPasteboard];
5838 type = [pb availableTypeFromArray: ns_drag_types];
5843 else if ([type isEqualToString: NSFilenamesPboardType])
5846 NSEnumerator *fenum;
5849 if (!(files = [pb propertyListForType: type]))
5852 fenum = [files objectEnumerator];
5853 while ( (file = [fenum nextObject]) )
5855 emacs_event->kind = NS_NONKEY_EVENT;
5856 emacs_event->code = KEY_NS_DRAG_FILE;
5857 XSETINT (emacs_event->x, x);
5858 XSETINT (emacs_event->y, y);
5859 ns_input_file = append2 (ns_input_file,
5860 build_string ([file UTF8String]));
5861 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5862 EV_TRAILER (theEvent);
5866 else if ([type isEqualToString: NSURLPboardType])
5871 if (!(fileURL = [NSURL URLFromPasteboard: pb]) ||
5872 [fileURL isFileURL] == NO)
5875 file = [fileURL path];
5876 emacs_event->kind = NS_NONKEY_EVENT;
5877 emacs_event->code = KEY_NS_DRAG_FILE;
5878 XSETINT (emacs_event->x, x);
5879 XSETINT (emacs_event->y, y);
5880 ns_input_file = append2 (ns_input_file, build_string ([file UTF8String]));
5881 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5882 EV_TRAILER (theEvent);
5885 else if ([type isEqualToString: NSStringPboardType]
5886 || [type isEqualToString: NSTabularTextPboardType])
5890 if (! (data = [pb stringForType: type]))
5893 emacs_event->kind = NS_NONKEY_EVENT;
5894 emacs_event->code = KEY_NS_DRAG_TEXT;
5895 XSETINT (emacs_event->x, x);
5896 XSETINT (emacs_event->y, y);
5897 ns_input_text = build_string ([data UTF8String]);
5898 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5899 EV_TRAILER (theEvent);
5902 else if ([type isEqualToString: NSColorPboardType])
5904 NSColor *c = [NSColor colorFromPasteboard: pb];
5905 emacs_event->kind = NS_NONKEY_EVENT;
5906 emacs_event->code = KEY_NS_DRAG_COLOR;
5907 XSETINT (emacs_event->x, x);
5908 XSETINT (emacs_event->y, y);
5909 ns_input_color = ns_color_to_lisp (c);
5910 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5911 EV_TRAILER (theEvent);
5914 else if ([type isEqualToString: NSFontPboardType])
5916 /* impl based on GNUstep NSTextView.m */
5917 NSData *data = [pb dataForType: NSFontPboardType];
5918 NSDictionary *dict = [NSUnarchiver unarchiveObjectWithData: data];
5919 NSFont *font = [dict objectForKey: NSFontAttributeName];
5925 emacs_event->kind = NS_NONKEY_EVENT;
5926 emacs_event->code = KEY_NS_CHANGE_FONT;
5927 XSETINT (emacs_event->x, x);
5928 XSETINT (emacs_event->y, y);
5929 ns_input_font = build_string ([[font fontName] UTF8String]);
5930 snprintf (fontSize, 10, "%f", [font pointSize]);
5931 ns_input_fontsize = build_string (fontSize);
5932 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5933 EV_TRAILER (theEvent);
5938 error ("Invalid data type in dragging pasteboard.");
5944 - (id) validRequestorForSendType: (NSString *)typeSent
5945 returnType: (NSString *)typeReturned
5947 NSTRACE (validRequestorForSendType);
5948 if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
5949 && typeReturned == nil)
5951 if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
5955 return [super validRequestorForSendType: typeSent
5956 returnType: typeReturned];
5960 /* The next two methods are part of NSServicesRequests informal protocol,
5961 supposedly called when a services menu item is chosen from this app.
5962 But this should not happen because we override the services menu with our
5963 own entries which call ns-perform-service.
5964 Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
5965 So let's at least stub them out until further investigation can be done. */
5967 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
5969 /* we could call ns_string_from_pasteboard(pboard) here but then it should
5970 be written into the buffer in place of the existing selection..
5971 ordinary service calls go through functions defined in ns-win.el */
5975 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
5977 NSArray *typesDeclared;
5980 /* We only support NSStringPboardType */
5981 if ([types containsObject:NSStringPboardType] == NO) {
5985 val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
5986 if (CONSP (val) && SYMBOLP (XCAR (val)))
5989 if (CONSP (val) && NILP (XCDR (val)))
5992 if (! STRINGP (val))
5995 typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
5996 [pb declareTypes:typesDeclared owner:nil];
5997 ns_string_to_pasteboard (pb, val);
6002 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
6003 (gives a miniaturized version of the window); currently we use the latter for
6004 frames whose active buffer doesn't correspond to any file
6005 (e.g., '*scratch*') */
6006 - setMiniwindowImage: (BOOL) setMini
6008 id image = [[self window] miniwindowImage];
6009 NSTRACE (setMiniwindowImage);
6011 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
6012 about "AppleDockIconEnabled" notwithstanding, however the set message
6013 below has its effect nonetheless. */
6014 if (image != emacsframe->output_data.ns->miniimage)
6016 if (image && [image isKindOfClass: [EmacsImage class]])
6018 [[self window] setMiniwindowImage:
6019 setMini ? emacsframe->output_data.ns->miniimage : nil];
6026 - (void) setRows: (int) r andColumns: (int) c
6032 @end /* EmacsView */
6036 /* ==========================================================================
6038 EmacsWindow implementation
6040 ========================================================================== */
6042 @implementation EmacsWindow
6044 /* If we have multiple monitors, one above the other, we don't want to
6045 restrict the height to just one monitor. So we override this. */
6046 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
6048 /* When making the frame visible for the first time or if there is just
6049 one screen, we want to constrain. Other times not. */
6050 NSUInteger nr_screens = [[NSScreen screens] count];
6051 struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
6052 NSTRACE (constrainFrameRect);
6054 if (nr_screens == 1)
6055 return [super constrainFrameRect:frameRect toScreen:screen];
6057 if (f->output_data.ns->dont_constrain
6058 || ns_menu_bar_should_be_hidden ())
6061 f->output_data.ns->dont_constrain = 1;
6062 return [super constrainFrameRect:frameRect toScreen:screen];
6066 /* called only on resize clicks by special case in EmacsApp-sendEvent */
6067 - (void)mouseDown: (NSEvent *)theEvent
6071 NSSize size = [[theEvent window] frame].size;
6072 grabOffset = [theEvent locationInWindow];
6073 grabOffset.x = size.width - grabOffset.x;
6076 [super mouseDown: theEvent];
6081 - (void)mouseUp: (NSEvent *)theEvent
6085 struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
6087 ns_set_name_as_filename (f);
6089 ns_send_appdefined (-1);
6092 [super mouseUp: theEvent];
6096 /* send resize events */
6097 - (void)mouseDragged: (NSEvent *)theEvent
6101 NSPoint p = [theEvent locationInWindow];
6102 NSSize size, vettedSize, origSize = [self frame].size;
6104 size.width = p.x + grabOffset.x;
6105 size.height = origSize.height - p.y + grabOffset.y;
6107 if (size.width == origSize.width && size.height == origSize.height)
6110 vettedSize = [[self delegate] windowWillResize: self toSize: size];
6111 [[NSNotificationCenter defaultCenter]
6112 postNotificationName: NSWindowDidResizeNotification
6116 [super mouseDragged: theEvent];
6119 @end /* EmacsWindow */
6122 /* ==========================================================================
6124 EmacsScroller implementation
6126 ========================================================================== */
6129 @implementation EmacsScroller
6131 /* for repeat button push */
6132 #define SCROLL_BAR_FIRST_DELAY 0.5
6133 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
6135 + (CGFloat) scrollerWidth
6137 /* TODO: if we want to allow variable widths, this is the place to do it,
6138 however neither GNUstep nor Cocoa support it very well */
6139 return [NSScroller scrollerWidth];
6143 - initFrame: (NSRect )r window: (Lisp_Object)nwin
6145 NSTRACE (EmacsScroller_initFrame);
6147 r.size.width = [EmacsScroller scrollerWidth];
6148 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
6149 [self setContinuous: YES];
6150 [self setEnabled: YES];
6152 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
6153 locked against the top and bottom edges, and right edge on OS X, where
6154 scrollers are on right. */
6155 #ifdef NS_IMPL_GNUSTEP
6156 [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
6158 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
6163 pixel_height = NSHeight (r);
6164 if (pixel_height == 0) pixel_height = 1;
6165 min_portion = 20 / pixel_height;
6167 frame = XFRAME (XWINDOW (win)->frame);
6168 if (FRAME_LIVE_P (frame))
6171 EmacsView *view = FRAME_NS_VIEW (frame);
6172 NSView *sview = [[view window] contentView];
6173 NSArray *subs = [sview subviews];
6175 /* disable optimization stopping redraw of other scrollbars */
6176 view->scrollbarsNeedingUpdate = 0;
6177 for (i =[subs count]-1; i >= 0; i--)
6178 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
6179 view->scrollbarsNeedingUpdate++;
6180 [sview addSubview: self];
6183 /* [self setFrame: r]; */
6189 - (void)setFrame: (NSRect)newRect
6191 NSTRACE (EmacsScroller_setFrame);
6193 pixel_height = NSHeight (newRect);
6194 if (pixel_height == 0) pixel_height = 1;
6195 min_portion = 20 / pixel_height;
6196 [super setFrame: newRect];
6198 /* UNBLOCK_INPUT; */
6204 NSTRACE (EmacsScroller_dealloc);
6206 XWINDOW (win)->vertical_scroll_bar = Qnil;
6234 /* ensure other scrollbar updates after deletion */
6235 view = (EmacsView *)FRAME_NS_VIEW (frame);
6237 view->scrollbarsNeedingUpdate++;
6238 [self removeFromSuperview];
6246 - (void)resetCursorRects
6248 NSRect visible = [self visibleRect];
6249 NSTRACE (resetCursorRects);
6251 if (!NSIsEmptyRect (visible))
6252 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
6253 [[NSCursor arrowCursor] setOnMouseEntered: YES];
6257 - (int) checkSamePosition: (int) position portion: (int) portion
6260 return em_position ==position && em_portion ==portion && em_whole ==whole
6261 && portion != whole; /* needed for resize empty buf */
6265 - setPosition: (int)position portion: (int)portion whole: (int)whole
6267 NSTRACE (setPosition);
6269 em_position = position;
6270 em_portion = portion;
6273 if (portion >= whole)
6275 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
6276 [self setKnobProportion: 1.0];
6277 [self setDoubleValue: 1.0];
6279 [self setFloatValue: 0.0 knobProportion: 1.0];
6285 portion = max ((float)whole*min_portion/pixel_height, portion);
6286 pos = (float)position / (whole - portion);
6287 por = (float)portion/whole;
6288 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
6289 [self setKnobProportion: por];
6290 [self setDoubleValue: pos];
6292 [self setFloatValue: pos knobProportion: por];
6298 /* FIXME: unused at moment (see ns_mouse_position) at the moment because
6299 drag events will go directly to the EmacsScroller. Leaving in for now. */
6300 -(void)getMouseMotionPart: (int *)part window: (Lisp_Object *)window
6301 x: (Lisp_Object *)x y: ( Lisp_Object *)y
6303 *part = last_hit_part;
6305 XSETINT (*y, pixel_height);
6306 if ([self floatValue] > 0.999)
6307 XSETINT (*x, pixel_height);
6309 XSETINT (*x, pixel_height * [self floatValue]);
6313 /* set up emacs_event */
6314 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
6319 emacs_event->part = last_hit_part;
6320 emacs_event->code = 0;
6321 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
6322 emacs_event->frame_or_window = win;
6323 emacs_event->timestamp = EV_TIMESTAMP (e);
6324 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
6325 emacs_event->arg = Qnil;
6326 XSETINT (emacs_event->x, loc * pixel_height);
6327 XSETINT (emacs_event->y, pixel_height-20);
6329 n_emacs_events_pending++;
6330 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
6331 EVENT_INIT (*emacs_event);
6332 ns_send_appdefined (-1);
6336 /* called manually thru timer to implement repeated button action w/hold-down */
6337 - repeatScroll: (NSTimer *)scrollEntry
6339 NSEvent *e = [[self window] currentEvent];
6340 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
6341 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
6343 /* clear timer if need be */
6344 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
6346 [scroll_repeat_entry invalidate];
6347 [scroll_repeat_entry release];
6348 scroll_repeat_entry = nil;
6354 = [[NSTimer scheduledTimerWithTimeInterval:
6355 SCROLL_BAR_CONTINUOUS_DELAY
6357 selector: @selector (repeatScroll:)
6363 [self sendScrollEventAtLoc: 0 fromEvent: e];
6368 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
6369 mouseDragged events without going into a modal loop. */
6370 - (void)mouseDown: (NSEvent *)e
6373 /* hitPart is only updated AFTER event is passed on */
6374 NSScrollerPart part = [self testPart: [e locationInWindow]];
6375 double inc = 0.0, loc, kloc, pos;
6378 NSTRACE (EmacsScroller_mouseDown);
6382 case NSScrollerDecrementPage:
6383 last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
6384 case NSScrollerIncrementPage:
6385 last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
6386 case NSScrollerDecrementLine:
6387 last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
6388 case NSScrollerIncrementLine:
6389 last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
6390 case NSScrollerKnob:
6391 last_hit_part = scroll_bar_handle; break;
6392 case NSScrollerKnobSlot: /* GNUstep-only */
6393 last_hit_part = scroll_bar_move_ratio; break;
6394 default: /* NSScrollerNoPart? */
6395 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
6402 pos = 0; /* ignored */
6404 /* set a timer to repeat, as we can't let superclass do this modally */
6406 = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
6408 selector: @selector (repeatScroll:)
6415 /* handle, or on GNUstep possibly slot */
6416 NSEvent *fake_event;
6418 /* compute float loc in slot and mouse offset on knob */
6419 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6421 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6427 else if (loc >= NSHeight (sr))
6429 loc = NSHeight (sr);
6437 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
6439 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
6441 last_mouse_offset = kloc;
6443 /* if knob, tell emacs a location offset by knob pos
6444 (to indicate top of handle) */
6445 if (part == NSScrollerKnob)
6446 pos = (loc - last_mouse_offset) / NSHeight (sr);
6448 /* else this is a slot click on GNUstep: go straight there */
6449 pos = loc / NSHeight (sr);
6451 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
6452 fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
6453 location: [e locationInWindow]
6454 modifierFlags: [e modifierFlags]
6455 timestamp: [e timestamp]
6456 windowNumber: [e windowNumber]
6457 context: [e context]
6458 eventNumber: [e eventNumber]
6459 clickCount: [e clickCount]
6460 pressure: [e pressure]];
6461 [super mouseUp: fake_event];
6464 if (part != NSScrollerKnob)
6465 [self sendScrollEventAtLoc: pos fromEvent: e];
6469 /* Called as we manually track scroller drags, rather than superclass. */
6470 - (void)mouseDragged: (NSEvent *)e
6476 NSTRACE (EmacsScroller_mouseDragged);
6478 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6480 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6487 else if (loc >= NSHeight (sr) + last_mouse_offset)
6489 loc = NSHeight (sr) + last_mouse_offset;
6493 pos = /*(edge ? loc :*/ (loc - last_mouse_offset) / NSHeight (sr);
6494 [self sendScrollEventAtLoc: pos fromEvent: e];
6498 - (void)mouseUp: (NSEvent *)e
6500 if (scroll_repeat_entry)
6502 [scroll_repeat_entry invalidate];
6503 [scroll_repeat_entry release];
6504 scroll_repeat_entry = nil;
6510 /* treat scrollwheel events in the bar as though they were in the main window */
6511 - (void) scrollWheel: (NSEvent *)theEvent
6513 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
6514 [view mouseDown: theEvent];
6517 @end /* EmacsScroller */
6522 /* ==========================================================================
6524 Font-related functions; these used to be in nsfaces.m
6526 ========================================================================== */
6530 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
6532 struct font *font = XFONT_OBJECT (font_object);
6535 fontset = fontset_from_font (font_object);
6536 FRAME_FONTSET (f) = fontset;
6538 if (FRAME_FONT (f) == font)
6539 /* This font is already set in frame F. There's nothing more to
6543 FRAME_FONT (f) = font;
6545 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
6546 FRAME_COLUMN_WIDTH (f) = font->average_width;
6547 FRAME_SPACE_WIDTH (f) = font->space_width;
6548 FRAME_LINE_HEIGHT (f) = font->height;
6550 compute_fringe_widths (f, 1);
6552 /* Compute the scroll bar width in character columns. */
6553 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
6555 int wid = FRAME_COLUMN_WIDTH (f);
6556 FRAME_CONFIG_SCROLL_BAR_COLS (f)
6557 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
6561 int wid = FRAME_COLUMN_WIDTH (f);
6562 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
6565 /* Now make the frame display the given font. */
6566 if (FRAME_NS_WINDOW (f) != 0)
6567 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
6573 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
6574 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
6578 ns_xlfd_to_fontname (const char *xlfd)
6579 /* --------------------------------------------------------------------------
6580 Convert an X font name (XLFD) to an NS font name.
6581 Only family is used.
6582 The string returned is temporarily allocated.
6583 -------------------------------------------------------------------------- */
6585 char *name = xmalloc (180);
6589 if (!strncmp (xlfd, "--", 2))
6590 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
6592 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
6594 /* stopgap for malformed XLFD input */
6595 if (strlen (name) == 0)
6596 strcpy (name, "Monaco");
6598 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
6599 also uppercase after '-' or ' ' */
6600 name[0] = toupper (name[0]);
6601 for (len =strlen (name), i =0; i<len; i++)
6607 name[i+1] = toupper (name[i+1]);
6609 else if (name[i] == '_')
6613 name[i+1] = toupper (name[i+1]);
6616 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
6617 ret = [[NSString stringWithUTF8String: name] UTF8String];
6624 syms_of_nsterm (void)
6626 NSTRACE (syms_of_nsterm);
6628 ns_antialias_threshold = 10.0;
6630 /* from 23+ we need to tell emacs what modifiers there are.. */
6631 DEFSYM (Qmodifier_value, "modifier-value");
6632 DEFSYM (Qalt, "alt");
6633 DEFSYM (Qhyper, "hyper");
6634 DEFSYM (Qmeta, "meta");
6635 DEFSYM (Qsuper, "super");
6636 DEFSYM (Qcontrol, "control");
6637 DEFSYM (Qnone, "none");
6638 DEFSYM (QUTF8_STRING, "UTF8_STRING");
6640 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
6641 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
6642 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
6643 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
6644 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
6646 DEFVAR_LISP ("ns-input-file", ns_input_file,
6647 "The file specified in the last NS event.");
6648 ns_input_file =Qnil;
6650 DEFVAR_LISP ("ns-input-text", ns_input_text,
6651 "The data received in the last NS text drag event.");
6652 ns_input_text =Qnil;
6654 DEFVAR_LISP ("ns-working-text", ns_working_text,
6655 "String for visualizing working composition sequence.");
6656 ns_working_text =Qnil;
6658 DEFVAR_LISP ("ns-input-font", ns_input_font,
6659 "The font specified in the last NS event.");
6660 ns_input_font =Qnil;
6662 DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
6663 "The fontsize specified in the last NS event.");
6664 ns_input_fontsize =Qnil;
6666 DEFVAR_LISP ("ns-input-line", ns_input_line,
6667 "The line specified in the last NS event.");
6668 ns_input_line =Qnil;
6670 DEFVAR_LISP ("ns-input-color", ns_input_color,
6671 "The color specified in the last NS event.");
6672 ns_input_color =Qnil;
6674 DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
6675 "The service name specified in the last NS event.");
6676 ns_input_spi_name =Qnil;
6678 DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
6679 "The service argument specified in the last NS event.");
6680 ns_input_spi_arg =Qnil;
6682 DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
6683 "This variable describes the behavior of the alternate or option key.\n\
6684 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6685 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6686 at all, allowing it to be used at a lower level for accented character entry.");
6687 ns_alternate_modifier = Qmeta;
6689 DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
6690 "This variable describes the behavior of the right alternate or option key.\n\
6691 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6692 Set to left means be the same key as `ns-alternate-modifier'.\n\
6693 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6694 at all, allowing it to be used at a lower level for accented character entry.");
6695 ns_right_alternate_modifier = Qleft;
6697 DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
6698 "This variable describes the behavior of the command key.\n\
6699 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6700 ns_command_modifier = Qsuper;
6702 DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
6703 "This variable describes the behavior of the right command key.\n\
6704 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6705 Set to left means be the same key as `ns-command-modifier'.\n\
6706 Set to none means that the command / option key is not interpreted by Emacs\n\
6707 at all, allowing it to be used at a lower level for accented character entry.");
6708 ns_right_command_modifier = Qleft;
6710 DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
6711 "This variable describes the behavior of the control key.\n\
6712 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6713 ns_control_modifier = Qcontrol;
6715 DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
6716 "This variable describes the behavior of the right control key.\n\
6717 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6718 Set to left means be the same key as `ns-control-modifier'.\n\
6719 Set to none means that the control / option key is not interpreted by Emacs\n\
6720 at all, allowing it to be used at a lower level for accented character entry.");
6721 ns_right_control_modifier = Qleft;
6723 DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
6724 "This variable describes the behavior of the function key (on laptops).\n\
6725 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6726 Set to none means that the function key is not interpreted by Emacs at all,\n\
6727 allowing it to be used at a lower level for accented character entry.");
6728 ns_function_modifier = Qnone;
6730 DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
6731 "Non-nil (the default) means to render text antialiased. Only has an effect on OS X Panther and above.");
6732 ns_antialias_text = Qt;
6734 DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
6735 "Whether to confirm application quit using dialog.");
6736 ns_confirm_quit = Qnil;
6738 staticpro (&ns_display_name_list);
6739 ns_display_name_list = Qnil;
6741 staticpro (&last_mouse_motion_frame);
6742 last_mouse_motion_frame = Qnil;
6744 DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
6745 doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
6746 Only works on OSX 10.6 or later. */);
6747 ns_auto_hide_menu_bar = Qnil;
6749 /* TODO: move to common code */
6750 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
6751 doc: /* Which toolkit scroll bars Emacs uses, if any.
6752 A value of nil means Emacs doesn't use toolkit scroll bars.
6753 With the X Window system, the value is a symbol describing the
6754 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
6755 With MS Windows or Nextstep, the value is t. */);
6756 Vx_toolkit_scroll_bars = Qt;
6758 DEFVAR_BOOL ("x-use-underline-position-properties",
6759 x_use_underline_position_properties,
6760 doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
6761 A value of nil means ignore them. If you encounter fonts with bogus
6762 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
6763 to 4.1, set this to nil. */);
6764 x_use_underline_position_properties = 0;
6766 DEFVAR_BOOL ("x-underline-at-descent-line",
6767 x_underline_at_descent_line,
6768 doc: /* Non-nil means to draw the underline at the same place as the descent line.
6769 A value of nil means to draw the underline according to the value of the
6770 variable `x-use-underline-position-properties', which is usually at the
6771 baseline level. The default value is nil. */);
6772 x_underline_at_descent_line = 0;
6774 /* Tell emacs about this window system. */
6775 Fprovide (intern ("ns"), Qnil);