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>
39 #include <c-strcase.h>
43 #include "blockinput.h"
44 #include "sysselect.h"
47 #include "character.h"
49 #include "composite.h"
52 #include "termhooks.h"
63 int term_trace_num = 0;
64 #define NSTRACE(x) fprintf (stderr, "%s:%d: [%d] " #x "\n", \
65 __FILE__, __LINE__, ++term_trace_num)
70 extern NSString *NSMenuDidBeginTrackingNotification;
72 /* ==========================================================================
76 ========================================================================== */
78 /* Convert a symbol indexed with an NSxxx value to a value as defined
79 in keyboard.c (lispy_function_key). I hope this is a correct way
81 static unsigned convert_ns_to_X_keysym[] =
83 NSHomeFunctionKey, 0x50,
84 NSLeftArrowFunctionKey, 0x51,
85 NSUpArrowFunctionKey, 0x52,
86 NSRightArrowFunctionKey, 0x53,
87 NSDownArrowFunctionKey, 0x54,
88 NSPageUpFunctionKey, 0x55,
89 NSPageDownFunctionKey, 0x56,
90 NSEndFunctionKey, 0x57,
91 NSBeginFunctionKey, 0x58,
92 NSSelectFunctionKey, 0x60,
93 NSPrintFunctionKey, 0x61,
94 NSExecuteFunctionKey, 0x62,
95 NSInsertFunctionKey, 0x63,
96 NSUndoFunctionKey, 0x65,
97 NSRedoFunctionKey, 0x66,
98 NSMenuFunctionKey, 0x67,
99 NSFindFunctionKey, 0x68,
100 NSHelpFunctionKey, 0x6A,
101 NSBreakFunctionKey, 0x6B,
103 NSF1FunctionKey, 0xBE,
104 NSF2FunctionKey, 0xBF,
105 NSF3FunctionKey, 0xC0,
106 NSF4FunctionKey, 0xC1,
107 NSF5FunctionKey, 0xC2,
108 NSF6FunctionKey, 0xC3,
109 NSF7FunctionKey, 0xC4,
110 NSF8FunctionKey, 0xC5,
111 NSF9FunctionKey, 0xC6,
112 NSF10FunctionKey, 0xC7,
113 NSF11FunctionKey, 0xC8,
114 NSF12FunctionKey, 0xC9,
115 NSF13FunctionKey, 0xCA,
116 NSF14FunctionKey, 0xCB,
117 NSF15FunctionKey, 0xCC,
118 NSF16FunctionKey, 0xCD,
119 NSF17FunctionKey, 0xCE,
120 NSF18FunctionKey, 0xCF,
121 NSF19FunctionKey, 0xD0,
122 NSF20FunctionKey, 0xD1,
123 NSF21FunctionKey, 0xD2,
124 NSF22FunctionKey, 0xD3,
125 NSF23FunctionKey, 0xD4,
126 NSF24FunctionKey, 0xD5,
128 NSBackspaceCharacter, 0x08, /* 8: Not on some KBs. */
129 NSDeleteCharacter, 0xFF, /* 127: Big 'delete' key upper right. */
130 NSDeleteFunctionKey, 0x9F, /* 63272: Del forw key off main array. */
132 NSTabCharacter, 0x09,
133 0x19, 0x09, /* left tab->regular since pass shift */
134 NSCarriageReturnCharacter, 0x0D,
135 NSNewlineCharacter, 0x0D,
136 NSEnterCharacter, 0x8D,
138 0x1B, 0x1B /* escape */
141 static Lisp_Object Qmodifier_value;
142 Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper, Qnone;
143 extern Lisp_Object Qcursor_color, Qcursor_type, Qns, Qleft;
145 static Lisp_Object QUTF8_STRING;
147 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
148 the maximum font size to NOT antialias. On GNUstep there is currently
149 no way to control this behavior. */
150 float ns_antialias_threshold;
152 /* Used to pick up AppleHighlightColor on OS X */
153 NSString *ns_selection_color;
155 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
156 NSString *ns_app_name = @"Emacs"; /* default changed later */
158 /* Display variables */
159 struct ns_display_info *x_display_list; /* Chain of existing displays */
160 Lisp_Object ns_display_name_list;
161 long context_menu_value = 0;
164 NSPoint last_mouse_motion_position;
165 static NSRect last_mouse_glyph;
166 static Time last_mouse_movement_time = 0;
167 static Lisp_Object last_mouse_motion_frame;
168 static EmacsScroller *last_mouse_scroll_bar = nil;
169 static struct frame *ns_updating_frame;
170 static NSView *focus_view = NULL;
171 static int ns_window_num = 0;
172 #ifdef NS_IMPL_GNUSTEP
175 static BOOL gsaved = NO;
176 BOOL ns_in_resize = NO;
177 static BOOL ns_fake_keydown = NO;
178 int ns_tmp_flags; /* FIXME */
179 struct nsfont_info *ns_tmp_font; /* FIXME */
180 static BOOL ns_menu_bar_is_hidden = NO;
181 /*static int debug_lock = 0; */
184 static BOOL send_appdefined = YES;
185 static NSEvent *last_appdefined_event = 0;
186 static NSTimer *timed_entry = 0;
187 static NSTimer *fd_entry = nil;
188 static NSTimer *scroll_repeat_entry = nil;
189 static fd_set select_readfds, t_readfds;
190 static int select_nfds;
191 static NSAutoreleasePool *outerpool;
192 static struct input_event *emacs_event = NULL;
193 static struct input_event *q_event_ptr = NULL;
194 static int n_emacs_events_pending = 0;
195 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
196 *ns_pending_service_args;
197 static BOOL inNsSelect = 0;
199 /* Convert modifiers in a NeXTstep event to emacs style modifiers. */
200 #define NS_FUNCTION_KEY_MASK 0x800000
201 #define NSLeftControlKeyMask (0x000001 | NSControlKeyMask)
202 #define NSRightControlKeyMask (0x002000 | NSControlKeyMask)
203 #define NSLeftCommandKeyMask (0x000008 | NSCommandKeyMask)
204 #define NSRightCommandKeyMask (0x000010 | NSCommandKeyMask)
205 #define NSLeftAlternateKeyMask (0x000020 | NSAlternateKeyMask)
206 #define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
207 #define EV_MODIFIERS(e) \
208 ((([e modifierFlags] & NSHelpKeyMask) ? \
209 hyper_modifier : 0) \
210 | (!EQ (ns_right_alternate_modifier, Qleft) && \
211 (([e modifierFlags] & NSRightAlternateKeyMask) \
212 == NSRightAlternateKeyMask) ? \
213 parse_solitary_modifier (ns_right_alternate_modifier) : 0) \
214 | (([e modifierFlags] & NSAlternateKeyMask) ? \
215 parse_solitary_modifier (ns_alternate_modifier) : 0) \
216 | (([e modifierFlags] & NSShiftKeyMask) ? \
217 shift_modifier : 0) \
218 | (!EQ (ns_right_control_modifier, Qleft) && \
219 (([e modifierFlags] & NSRightControlKeyMask) \
220 == NSRightControlKeyMask) ? \
221 parse_solitary_modifier (ns_right_control_modifier) : 0) \
222 | (([e modifierFlags] & NSControlKeyMask) ? \
223 parse_solitary_modifier (ns_control_modifier) : 0) \
224 | (([e modifierFlags] & NS_FUNCTION_KEY_MASK) ? \
225 parse_solitary_modifier (ns_function_modifier) : 0) \
226 | (!EQ (ns_right_command_modifier, Qleft) && \
227 (([e modifierFlags] & NSRightCommandKeyMask) \
228 == NSRightCommandKeyMask) ? \
229 parse_solitary_modifier (ns_right_command_modifier) : 0) \
230 | (([e modifierFlags] & NSCommandKeyMask) ? \
231 parse_solitary_modifier (ns_command_modifier):0))
233 #define EV_UDMODIFIERS(e) \
234 ((([e type] == NSLeftMouseDown) ? down_modifier : 0) \
235 | (([e type] == NSRightMouseDown) ? down_modifier : 0) \
236 | (([e type] == NSOtherMouseDown) ? down_modifier : 0) \
237 | (([e type] == NSLeftMouseDragged) ? down_modifier : 0) \
238 | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
239 | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
240 | (([e type] == NSLeftMouseUp) ? up_modifier : 0) \
241 | (([e type] == NSRightMouseUp) ? up_modifier : 0) \
242 | (([e type] == NSOtherMouseUp) ? up_modifier : 0))
244 #define EV_BUTTON(e) \
245 ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 : \
246 (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
247 [e buttonNumber] - 1)
249 /* Convert the time field to a timestamp in milliseconds. */
250 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
252 /* This is a piece of code which is common to all the event handling
253 methods. Maybe it should even be a function. */
254 #define EV_TRAILER(e) \
256 XSETFRAME (emacs_event->frame_or_window, emacsframe); \
257 if (e) emacs_event->timestamp = EV_TIMESTAMP (e); \
258 n_emacs_events_pending++; \
259 kbd_buffer_store_event_hold (emacs_event, q_event_ptr); \
260 EVENT_INIT (*emacs_event); \
261 ns_send_appdefined (-1); \
264 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
266 /* TODO: get rid of need for these forward declarations */
267 static void ns_condemn_scroll_bars (struct frame *f);
268 static void ns_judge_scroll_bars (struct frame *f);
269 void x_set_frame_alpha (struct frame *f);
272 /* ==========================================================================
276 ========================================================================== */
280 append2 (Lisp_Object list, Lisp_Object item)
281 /* --------------------------------------------------------------------------
282 Utility to append to a list
283 -------------------------------------------------------------------------- */
285 Lisp_Object array[2];
287 array[1] = Fcons (item, Qnil);
288 return Fnconc (2, &array[0]);
293 ns_etc_directory (void)
294 /* If running as a self-contained app bundle, return as a string the
295 filename of the etc directory, if present; else nil. */
297 NSBundle *bundle = [NSBundle mainBundle];
298 NSString *resourceDir = [bundle resourcePath];
299 NSString *resourcePath;
300 NSFileManager *fileManager = [NSFileManager defaultManager];
303 resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
304 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
306 if (isDir) return [resourcePath UTF8String];
314 /* If running as a self-contained app bundle, return as a path string
315 the filenames of the libexec and bin directories, ie libexec:bin.
316 Otherwise, return nil.
317 Normally, Emacs does not add its own bin/ directory to the PATH.
318 However, a self-contained NS build has a different layout, with
319 bin/ and libexec/ subdirectories in the directory that contains
321 We put libexec first, because init_callproc_1 uses the first
322 element to initialize exec-directory. An alternative would be
323 for init_callproc to check for invocation-directory/libexec.
326 NSBundle *bundle = [NSBundle mainBundle];
327 NSString *resourceDir = [bundle resourcePath];
328 NSString *binDir = [bundle bundlePath];
329 NSString *resourcePath, *resourcePaths;
331 BOOL onWindows = NO; /* FIXME determine this somehow */
332 NSString *pathSeparator = onWindows ? @";" : @":";
333 NSFileManager *fileManager = [NSFileManager defaultManager];
335 NSEnumerator *pathEnum;
338 range = [resourceDir rangeOfString: @"Contents"];
339 if (range.location != NSNotFound)
341 binDir = [binDir stringByAppendingPathComponent: @"Contents"];
343 binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
347 paths = [binDir stringsByAppendingPaths:
348 [NSArray arrayWithObjects: @"libexec", @"bin", nil]];
349 pathEnum = [paths objectEnumerator];
352 while ((resourcePath = [pathEnum nextObject]))
354 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
357 if ([resourcePaths length] > 0)
359 = [resourcePaths stringByAppendingString: pathSeparator];
361 = [resourcePaths stringByAppendingString: resourcePath];
364 if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
372 /* If running as a self-contained app bundle, return as a path string
373 the filenames of the site-lisp, lisp and leim directories.
374 Ie, site-lisp:lisp:leim. Otherwise, return nil. */
376 NSBundle *bundle = [NSBundle mainBundle];
377 NSString *resourceDir = [bundle resourcePath];
378 NSString *resourcePath, *resourcePaths;
379 BOOL onWindows = NO; /* FIXME determine this somehow */
380 NSString *pathSeparator = onWindows ? @";" : @":";
381 NSFileManager *fileManager = [NSFileManager defaultManager];
383 NSArray *paths = [resourceDir stringsByAppendingPaths:
384 [NSArray arrayWithObjects:
385 @"site-lisp", @"lisp", @"leim", nil]];
386 NSEnumerator *pathEnum = [paths objectEnumerator];
389 /* Hack to skip site-lisp. */
390 if (no_site_lisp) resourcePath = [pathEnum nextObject];
392 while ((resourcePath = [pathEnum nextObject]))
394 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
397 if ([resourcePaths length] > 0)
399 = [resourcePaths stringByAppendingString: pathSeparator];
401 = [resourcePaths stringByAppendingString: resourcePath];
404 if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
410 ns_timeout (int usecs)
411 /* --------------------------------------------------------------------------
412 Blocking timer utility used by ns_ring_bell
413 -------------------------------------------------------------------------- */
415 EMACS_TIME wakeup = add_emacs_time (current_emacs_time (),
416 make_emacs_time (0, usecs * 1000));
418 /* Keep waiting until past the time wakeup. */
421 EMACS_TIME timeout, now = current_emacs_time ();
422 if (EMACS_TIME_LE (wakeup, now))
424 timeout = sub_emacs_time (wakeup, now);
426 /* Try to wait that long--but we might wake up sooner. */
427 pselect (0, NULL, NULL, NULL, &timeout, NULL);
433 ns_release_object (void *obj)
434 /* --------------------------------------------------------------------------
435 Release an object (callable from C)
436 -------------------------------------------------------------------------- */
443 ns_retain_object (void *obj)
444 /* --------------------------------------------------------------------------
445 Retain an object (callable from C)
446 -------------------------------------------------------------------------- */
453 ns_alloc_autorelease_pool (void)
454 /* --------------------------------------------------------------------------
455 Allocate a pool for temporary objects (callable from C)
456 -------------------------------------------------------------------------- */
458 return [[NSAutoreleasePool alloc] init];
463 ns_release_autorelease_pool (void *pool)
464 /* --------------------------------------------------------------------------
465 Free a pool and temporary objects it refers to (callable from C)
466 -------------------------------------------------------------------------- */
468 ns_release_object (pool);
473 /* ==========================================================================
475 Focus (clipping) and screen update
477 ========================================================================== */
480 ns_resize_handle_rect (NSWindow *window)
482 NSRect r = [window frame];
483 r.origin.x = r.size.width - RESIZE_HANDLE_SIZE;
485 r.size.width = r.size.height = RESIZE_HANDLE_SIZE;
491 // Window constraining
492 // -------------------
494 // To ensure that the windows are not placed under the menu bar, they
495 // are typically moved by the call-back constrainFrameRect. However,
496 // by overriding it, it's possible to inhibit this, leaving the window
497 // in it's original position.
499 // It's possible to hide the menu bar. However, technically, it's only
500 // possible to hide it when the application is active. To ensure that
501 // this work properly, the menu bar and window constraining are
502 // deferred until the application becomes active.
504 // Even though it's not possible to manually move a window above the
505 // top of the screen, it is allowed if it's done programmatically,
506 // when the menu is hidden. This allows the editable area to cover the
507 // full screen height.
512 // Use the following extra files:
515 // ;; Hide menu and place frame slightly above the top of the screen.
516 // (setq ns-auto-hide-menu-bar t)
517 // (set-frame-position (selected-frame) 0 -20)
521 // emacs -Q -l init.el
523 // Result: No menu bar, and the title bar should be above the screen.
529 // Result: Menu bar visible, frame placed immediately below the menu.
533 ns_constrain_all_frames (void)
535 Lisp_Object tail, frame;
537 FOR_EACH_FRAME (tail, frame)
539 struct frame *f = XFRAME (frame);
542 NSView *view = FRAME_NS_VIEW (f);
543 /* This no-op will trigger the default window placing
544 * constraint system. */
545 f->output_data.ns->dont_constrain = 0;
546 [[view window] setFrameOrigin:[[view window] frame].origin];
552 /* True, if the menu bar should be hidden. */
555 ns_menu_bar_should_be_hidden (void)
557 return !NILP (ns_auto_hide_menu_bar)
558 && [NSApp respondsToSelector:@selector(setPresentationOptions:)];
562 /* Show or hide the menu bar, based on user setting. */
565 ns_update_auto_hide_menu_bar (void)
567 #ifndef MAC_OS_X_VERSION_10_6
568 #define MAC_OS_X_VERSION_10_6 1060
571 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
574 NSTRACE (ns_update_auto_hide_menu_bar);
578 && [NSApp respondsToSelector:@selector(setPresentationOptions:)])
580 // Note, "setPresentationOptions" triggers an error unless the
581 // application is active.
582 BOOL menu_bar_should_be_hidden = ns_menu_bar_should_be_hidden ();
584 if (menu_bar_should_be_hidden != ns_menu_bar_is_hidden)
586 NSApplicationPresentationOptions options
587 = NSApplicationPresentationAutoHideDock;
589 if (menu_bar_should_be_hidden)
590 options |= NSApplicationPresentationAutoHideMenuBar;
592 [NSApp setPresentationOptions: options];
594 ns_menu_bar_is_hidden = menu_bar_should_be_hidden;
596 if (!ns_menu_bar_is_hidden)
598 ns_constrain_all_frames ();
610 ns_update_begin (struct frame *f)
611 /* --------------------------------------------------------------------------
612 Prepare for a grouped sequence of drawing calls
613 external (RIF) call; whole frame, called before update_window_begin
614 -------------------------------------------------------------------------- */
616 NSView *view = FRAME_NS_VIEW (f);
617 NSTRACE (ns_update_begin);
619 ns_update_auto_hide_menu_bar ();
621 ns_updating_frame = f;
624 #ifdef NS_IMPL_GNUSTEP
625 uRect = NSMakeRect (0, 0, 0, 0);
631 ns_update_window_begin (struct window *w)
632 /* --------------------------------------------------------------------------
633 Prepare for a grouped sequence of drawing calls
634 external (RIF) call; for one window, called after update_begin
635 -------------------------------------------------------------------------- */
637 struct frame *f = XFRAME (WINDOW_FRAME (w));
638 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
639 NSTRACE (ns_update_window_begin);
642 set_output_cursor (&w->cursor);
646 if (f == hlinfo->mouse_face_mouse_frame)
648 /* Don't do highlighting for mouse motion during the update. */
649 hlinfo->mouse_face_defer = 1;
651 /* If the frame needs to be redrawn,
652 simply forget about any prior mouse highlighting. */
653 if (FRAME_GARBAGED_P (f))
654 hlinfo->mouse_face_window = Qnil;
656 /* (further code for mouse faces ifdef'd out in other terms elided) */
664 ns_update_window_end (struct window *w, int cursor_on_p,
665 int mouse_face_overwritten_p)
666 /* --------------------------------------------------------------------------
667 Finished a grouped sequence of drawing calls
668 external (RIF) call; for one window called before update_end
669 -------------------------------------------------------------------------- */
671 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (XFRAME (w->frame));
673 /* note: this fn is nearly identical in all terms */
674 if (!w->pseudo_window_p)
679 display_and_set_cursor (w, 1,
680 output_cursor.hpos, output_cursor.vpos,
681 output_cursor.x, output_cursor.y);
683 if (draw_window_fringes (w, 1))
684 x_draw_vertical_border (w);
689 /* If a row with mouse-face was overwritten, arrange for
690 frame_up_to_date to redisplay the mouse highlight. */
691 if (mouse_face_overwritten_p)
693 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
694 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
695 hlinfo->mouse_face_window = Qnil;
698 updated_window = NULL;
699 NSTRACE (update_window_end);
704 ns_update_end (struct frame *f)
705 /* --------------------------------------------------------------------------
706 Finished a grouped sequence of drawing calls
707 external (RIF) call; for whole frame, called after update_window_end
708 -------------------------------------------------------------------------- */
710 NSView *view = FRAME_NS_VIEW (f);
712 /* if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
713 MOUSE_HL_INFO (f)->mouse_face_defer = 0;
717 #ifdef NS_IMPL_GNUSTEP
718 /* trigger flush only in the rectangle we tracked as being drawn */
719 [view unlockFocusNeedsFlush: NO];
720 /*fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", uRect.origin.x, uRect.origin.y, uRect.size.width, uRect.size.height); */
721 [view lockFocusInRect: uRect];
725 [[view window] flushWindow];
728 ns_updating_frame = NULL;
729 NSTRACE (ns_update_end);
734 ns_flush (struct frame *f)
735 /* --------------------------------------------------------------------------
737 NS impl is no-op since currently we flush in ns_update_end and elsewhere
738 -------------------------------------------------------------------------- */
745 ns_focus (struct frame *f, NSRect *r, int n)
746 /* --------------------------------------------------------------------------
747 Internal: Focus on given frame. During small local updates this is used to
748 draw, however during large updates, ns_update_begin and ns_update_end are
749 called to wrap the whole thing, in which case these calls are stubbed out.
750 Except, on GNUstep, we accumulate the rectangle being drawn into, because
751 the back end won't do this automatically, and will just end up flushing
753 -------------------------------------------------------------------------- */
755 // NSTRACE (ns_focus);
756 #ifdef NS_IMPL_GNUSTEP
759 u = NSUnionRect (r[0], r[1]);
764 fprintf (stderr, "focus: %d", c++);
765 if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
766 fprintf (stderr, "\n"); */
768 if (f != ns_updating_frame)
770 NSView *view = FRAME_NS_VIEW (f);
771 if (view != focus_view)
773 if (focus_view != NULL)
775 [focus_view unlockFocus];
776 [[focus_view window] flushWindow];
781 #ifdef NS_IMPL_GNUSTEP
782 r ? [view lockFocusInRect: u] : [view lockFocus];
787 /*if (view) debug_lock++; */
789 #ifdef NS_IMPL_GNUSTEP
792 /* more than one rect being drawn into */
795 [view unlockFocus]; /* add prev rect to redraw list */
796 [view lockFocusInRect: u]; /* focus for draw in new rect */
801 #ifdef NS_IMPL_GNUSTEP
804 /* in batch mode, but in GNUstep must still track rectangles explicitly */
805 uRect = (r ? NSUnionRect (uRect, u) : [FRAME_NS_VIEW (f) visibleRect]);
812 [[NSGraphicsContext currentContext] saveGraphicsState];
814 NSRectClipList (r, 2);
823 ns_unfocus (struct frame *f)
824 /* --------------------------------------------------------------------------
825 Internal: Remove focus on given frame
826 -------------------------------------------------------------------------- */
828 // NSTRACE (ns_unfocus);
832 [[NSGraphicsContext currentContext] restoreGraphicsState];
836 if (f != ns_updating_frame)
838 if (focus_view != NULL)
840 [focus_view unlockFocus];
841 [[focus_view window] flushWindow];
850 ns_clip_to_row (struct window *w, struct glyph_row *row, int area, BOOL gc)
851 /* --------------------------------------------------------------------------
852 Internal (but parallels other terms): Focus drawing on given row
853 -------------------------------------------------------------------------- */
855 struct frame *f = XFRAME (WINDOW_FRAME (w));
857 int window_x, window_y, window_width;
859 window_box (w, area, &window_x, &window_y, &window_width, 0);
861 clip_rect.origin.x = window_x - FRAME_INTERNAL_BORDER_WIDTH (f);
862 clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
863 clip_rect.origin.y = max (clip_rect.origin.y, window_y);
864 clip_rect.size.width = window_width + 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
865 clip_rect.size.height = row->visible_height;
867 /* allow a full-height row at the top when requested
868 (used to draw fringe all the way through internal border area) */
869 if (gc && clip_rect.origin.y < 5)
871 clip_rect.origin.y -= FRAME_INTERNAL_BORDER_WIDTH (f);
872 clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
875 /* likewise at bottom */
877 FRAME_PIXEL_HEIGHT (f) - (clip_rect.origin.y + clip_rect.size.height) < 5)
878 clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
880 ns_focus (f, &clip_rect, 1);
885 ns_ring_bell (struct frame *f)
886 /* --------------------------------------------------------------------------
888 -------------------------------------------------------------------------- */
890 NSTRACE (ns_ring_bell);
893 NSAutoreleasePool *pool;
894 struct frame *frame = SELECTED_FRAME ();
898 pool = [[NSAutoreleasePool alloc] init];
900 view = FRAME_NS_VIEW (frame);
904 NSPoint dim = NSMakePoint (128, 128);
907 r.origin.x += (r.size.width - dim.x) / 2;
908 r.origin.y += (r.size.height - dim.y) / 2;
909 r.size.width = dim.x;
910 r.size.height = dim.y;
911 surr = NSInsetRect (r, -2, -2);
912 ns_focus (frame, &surr, 1);
913 [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
914 [ns_lookup_indexed_color (NS_FACE_FOREGROUND
915 (FRAME_DEFAULT_FACE (frame)), frame) set];
917 [[view window] flushWindow];
919 [[view window] restoreCachedImage];
920 [[view window] flushWindow];
934 ns_reset_terminal_modes (struct terminal *terminal)
935 /* Externally called as hook */
937 NSTRACE (ns_reset_terminal_modes);
942 ns_set_terminal_modes (struct terminal *terminal)
943 /* Externally called as hook */
945 NSTRACE (ns_set_terminal_modes);
950 /* ==========================================================================
952 Frame / window manager related functions
954 ========================================================================== */
958 ns_raise_frame (struct frame *f)
959 /* --------------------------------------------------------------------------
960 Bring window to foreground and make it active
961 -------------------------------------------------------------------------- */
963 NSView *view = FRAME_NS_VIEW (f);
966 FRAME_SAMPLE_VISIBILITY (f);
967 if (FRAME_VISIBLE_P (f))
969 [[view window] makeKeyAndOrderFront: NSApp];
976 ns_lower_frame (struct frame *f)
977 /* --------------------------------------------------------------------------
979 -------------------------------------------------------------------------- */
981 NSView *view = FRAME_NS_VIEW (f);
984 [[view window] orderBack: NSApp];
990 ns_frame_raise_lower (struct frame *f, int raise)
991 /* --------------------------------------------------------------------------
993 -------------------------------------------------------------------------- */
995 NSTRACE (ns_frame_raise_lower);
1005 ns_frame_rehighlight (struct frame *frame)
1006 /* --------------------------------------------------------------------------
1007 External (hook): called on things like window switching within frame
1008 -------------------------------------------------------------------------- */
1010 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
1011 struct frame *old_highlight = dpyinfo->x_highlight_frame;
1013 NSTRACE (ns_frame_rehighlight);
1014 if (dpyinfo->x_focus_frame)
1016 dpyinfo->x_highlight_frame
1017 = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1018 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1019 : dpyinfo->x_focus_frame);
1020 if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
1022 FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
1023 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
1027 dpyinfo->x_highlight_frame = 0;
1029 if (dpyinfo->x_highlight_frame &&
1030 dpyinfo->x_highlight_frame != old_highlight)
1034 x_update_cursor (old_highlight, 1);
1035 x_set_frame_alpha (old_highlight);
1037 if (dpyinfo->x_highlight_frame)
1039 x_update_cursor (dpyinfo->x_highlight_frame, 1);
1040 x_set_frame_alpha (dpyinfo->x_highlight_frame);
1047 x_make_frame_visible (struct frame *f)
1048 /* --------------------------------------------------------------------------
1049 External: Show the window (X11 semantics)
1050 -------------------------------------------------------------------------- */
1052 NSTRACE (x_make_frame_visible);
1053 /* XXX: at some points in past this was not needed, as the only place that
1054 called this (frame.c:Fraise_frame ()) also called raise_lower;
1055 if this ends up the case again, comment this out again. */
1056 if (!FRAME_VISIBLE_P (f))
1058 f->async_visible = 1;
1065 x_make_frame_invisible (struct frame *f)
1066 /* --------------------------------------------------------------------------
1067 External: Hide the window (X11 semantics)
1068 -------------------------------------------------------------------------- */
1070 NSView * view = FRAME_NS_VIEW (f);
1071 NSTRACE (x_make_frame_invisible);
1073 [[view window] orderOut: NSApp];
1074 f->async_visible = 0;
1075 f->async_iconified = 0;
1080 x_iconify_frame (struct frame *f)
1081 /* --------------------------------------------------------------------------
1082 External: Iconify window
1083 -------------------------------------------------------------------------- */
1085 NSView * view = FRAME_NS_VIEW (f);
1086 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1087 NSTRACE (x_iconify_frame);
1090 if (dpyinfo->x_highlight_frame == f)
1091 dpyinfo->x_highlight_frame = 0;
1093 if ([[view window] windowNumber] <= 0)
1095 /* the window is still deferred. Make it very small, bring it
1096 on screen and order it out. */
1097 NSRect s = { { 100, 100}, {0, 0} };
1099 t = [[view window] frame];
1100 [[view window] setFrame: s display: NO];
1101 [[view window] orderBack: NSApp];
1102 [[view window] orderOut: NSApp];
1103 [[view window] setFrame: t display: NO];
1105 [[view window] miniaturize: NSApp];
1108 /* Free X resources of frame F. */
1111 x_free_frame_resources (struct frame *f)
1113 NSView *view = FRAME_NS_VIEW (f);
1114 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1115 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1116 NSTRACE (x_free_frame_resources);
1119 [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1123 free_frame_menubar (f);
1125 if (FRAME_FACE_CACHE (f))
1126 free_frame_faces (f);
1128 if (f == dpyinfo->x_focus_frame)
1129 dpyinfo->x_focus_frame = 0;
1130 if (f == dpyinfo->x_highlight_frame)
1131 dpyinfo->x_highlight_frame = 0;
1132 if (f == hlinfo->mouse_face_mouse_frame)
1134 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
1135 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
1136 hlinfo->mouse_face_window = Qnil;
1137 hlinfo->mouse_face_deferred_gc = 0;
1138 hlinfo->mouse_face_mouse_frame = 0;
1141 if (f->output_data.ns->miniimage != nil)
1142 [f->output_data.ns->miniimage release];
1144 [[view window] close];
1147 xfree (f->output_data.ns);
1153 x_destroy_window (struct frame *f)
1154 /* --------------------------------------------------------------------------
1155 External: Delete the window
1156 -------------------------------------------------------------------------- */
1158 NSTRACE (x_destroy_window);
1160 x_free_frame_resources (f);
1166 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1167 /* --------------------------------------------------------------------------
1168 External: Position the window
1169 -------------------------------------------------------------------------- */
1171 NSView *view = FRAME_NS_VIEW (f);
1172 NSArray *screens = [NSScreen screens];
1173 NSScreen *fscreen = [screens objectAtIndex: 0];
1174 NSScreen *screen = [[view window] screen];
1176 NSTRACE (x_set_offset);
1183 if (view != nil && screen && fscreen)
1185 f->left_pos = f->size_hint_flags & XNegative
1186 ? [screen visibleFrame].size.width + f->left_pos - FRAME_PIXEL_WIDTH (f)
1188 /* We use visibleFrame here to take menu bar into account.
1189 Ideally we should also adjust left/top with visibleFrame.origin. */
1191 f->top_pos = f->size_hint_flags & YNegative
1192 ? ([screen visibleFrame].size.height + f->top_pos
1193 - FRAME_PIXEL_HEIGHT (f) - FRAME_NS_TITLEBAR_HEIGHT (f)
1194 - FRAME_TOOLBAR_HEIGHT (f))
1196 #ifdef NS_IMPL_GNUSTEP
1197 if (f->left_pos < 100)
1198 f->left_pos = 100; /* don't overlap menu */
1200 /* Constrain the setFrameTopLeftPoint so we don't move behind the
1202 f->output_data.ns->dont_constrain = 0;
1203 [[view window] setFrameTopLeftPoint:
1204 NSMakePoint (SCREENMAXBOUND (f->left_pos),
1205 SCREENMAXBOUND ([fscreen frame].size.height
1206 - NS_TOP_POS (f)))];
1207 f->size_hint_flags &= ~(XNegative|YNegative);
1215 x_set_window_size (struct frame *f, int change_grav, int cols, int rows)
1216 /* --------------------------------------------------------------------------
1217 Adjust window pixel size based on given character grid size
1218 Impl is a bit more complex than other terms, need to do some
1220 -------------------------------------------------------------------------- */
1222 EmacsView *view = FRAME_NS_VIEW (f);
1223 NSWindow *window = [view window];
1224 NSRect wr = [window frame];
1225 int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1226 int pixelwidth, pixelheight;
1227 static int oldRows, oldCols, oldFontWidth, oldFontHeight;
1229 static struct frame *oldF;
1231 NSTRACE (x_set_window_size);
1235 && rows == oldRows && cols == oldCols
1236 && oldFontWidth == FRAME_COLUMN_WIDTH (f)
1237 && oldFontHeight == FRAME_LINE_HEIGHT (f)
1241 /*fprintf (stderr, "\tsetWindowSize: %d x %d, font size %d x %d\n", cols, rows, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f)); */
1245 check_frame_size (f, &rows, &cols);
1249 oldFontWidth = FRAME_COLUMN_WIDTH (f);
1250 oldFontHeight = FRAME_LINE_HEIGHT (f);
1253 f->scroll_bar_actual_width = NS_SCROLL_BAR_WIDTH (f);
1254 compute_fringe_widths (f, 0);
1256 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols);
1257 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
1259 /* If we have a toolbar, take its height into account. */
1261 /* NOTE: previously this would generate wrong result if toolbar not
1262 yet displayed and fixing toolbar_height=32 helped, but
1263 now (200903) seems no longer needed */
1264 FRAME_TOOLBAR_HEIGHT (f) =
1265 NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1266 - FRAME_NS_TITLEBAR_HEIGHT (f);
1268 FRAME_TOOLBAR_HEIGHT (f) = 0;
1270 wr.size.width = pixelwidth + f->border_width;
1271 wr.size.height = pixelheight + FRAME_NS_TITLEBAR_HEIGHT (f)
1272 + FRAME_TOOLBAR_HEIGHT (f);
1274 /* Do not try to constrain to this screen. We may have multiple
1275 screens, and want Emacs to span those. Constraining to screen
1276 prevents that, and that is not nice to the user. */
1277 if (f->output_data.ns->zooming)
1278 f->output_data.ns->zooming = 0;
1280 wr.origin.y += FRAME_PIXEL_HEIGHT (f) - pixelheight;
1282 [view setRows: rows andColumns: cols];
1283 [window setFrame: wr display: YES];
1285 /*fprintf (stderr, "\tx_set_window_size %d, %d\t%d, %d\n", cols, rows, pixelwidth, pixelheight); */
1287 /* This is a trick to compensate for Emacs' managing the scrollbar area
1288 as a fixed number of standard character columns. Instead of leaving
1289 blank space for the extra, we chopped it off above. Now for
1290 left-hand scrollbars, we shift all rendering to the left by the
1291 difference between the real width and Emacs' imagined one. For
1292 right-hand bars, don't worry about it since the extra is never used.
1293 (Obviously doesn't work for vertically split windows tho..) */
1295 NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1296 ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1297 - NS_SCROLL_BAR_WIDTH (f), 0)
1298 : NSMakePoint (0, 0);
1299 [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1300 [view setBoundsOrigin: origin];
1303 change_frame_size (f, rows, cols, 0, 1, 0); /* pretend, delay, safe */
1304 FRAME_PIXEL_WIDTH (f) = pixelwidth;
1305 FRAME_PIXEL_HEIGHT (f) = pixelheight;
1306 /* SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */
1308 mark_window_cursors_off (XWINDOW (f->root_window));
1309 cancel_mouse_face (f);
1316 /* ==========================================================================
1320 ========================================================================== */
1324 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1326 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1327 if (idx < 1 || idx >= color_table->avail)
1329 return color_table->colors[idx];
1334 ns_index_color (NSColor *color, struct frame *f)
1336 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1340 if (!color_table->colors)
1342 color_table->size = NS_COLOR_CAPACITY;
1343 color_table->avail = 1; /* skip idx=0 as marker */
1344 color_table->colors = xmalloc (color_table->size * sizeof (NSColor *));
1345 color_table->colors[0] = nil;
1346 color_table->empty_indices = [[NSMutableSet alloc] init];
1349 /* do we already have this color ? */
1350 for (i = 1; i < color_table->avail; i++)
1351 if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1354 if ([color_table->empty_indices count] > 0)
1356 NSNumber *index = [color_table->empty_indices anyObject];
1357 [color_table->empty_indices removeObject: index];
1358 idx = [index unsignedLongValue];
1362 if (color_table->avail == color_table->size)
1363 color_table->colors =
1364 xpalloc (color_table->colors, &color_table->size, 1,
1365 min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1366 idx = color_table->avail++;
1369 color_table->colors[idx] = color;
1371 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1377 ns_free_indexed_color (unsigned long idx, struct frame *f)
1379 struct ns_color_table *color_table;
1386 color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1388 if (idx <= 0 || idx >= color_table->size) {
1389 message1 ("ns_free_indexed_color: Color index out of range.\n");
1393 index = [NSNumber numberWithUnsignedInt: idx];
1394 if ([color_table->empty_indices containsObject: index]) {
1395 message1 ("ns_free_indexed_color: attempt to free already freed color.\n");
1399 color = color_table->colors[idx];
1401 color_table->colors[idx] = nil;
1402 [color_table->empty_indices addObject: index];
1403 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1408 ns_get_color (const char *name, NSColor **col)
1409 /* --------------------------------------------------------------------------
1411 -------------------------------------------------------------------------- */
1412 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1413 X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1414 See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1417 static char hex[20];
1419 float r = -1.0, g, b;
1420 NSString *nsname = [NSString stringWithUTF8String: name];
1422 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1425 if ([nsname isEqualToString: @"ns_selection_color"])
1427 nsname = ns_selection_color;
1428 name = [ns_selection_color UTF8String];
1431 /* First, check for some sort of numeric specification. */
1434 if (name[0] == '0' || name[0] == '1' || name[0] == '.') /* RGB decimal */
1436 NSScanner *scanner = [NSScanner scannerWithString: nsname];
1437 [scanner scanFloat: &r];
1438 [scanner scanFloat: &g];
1439 [scanner scanFloat: &b];
1441 else if (!strncmp(name, "rgb:", 4)) /* A newer X11 format -- rgb:r/g/b */
1442 scaling = (snprintf (hex, sizeof hex, "%s", name + 4) - 2) / 3;
1443 else if (name[0] == '#') /* An old X11 format; convert to newer */
1445 int len = (strlen(name) - 1);
1446 int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1448 scaling = strlen(name+start) / 3;
1449 for (i = 0; i < 3; i++)
1450 sprintf (hex + i * (scaling + 1), "%.*s/", scaling,
1451 name + start + i * scaling);
1452 hex[3 * (scaling + 1) - 1] = '\0';
1458 float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1459 if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1469 *col = [NSColor colorWithCalibratedRed: r green: g blue: b alpha: 1.0];
1474 /* Otherwise, color is expected to be from a list */
1476 NSEnumerator *lenum, *cenum;
1480 #ifdef NS_IMPL_GNUSTEP
1481 /* XXX: who is wrong, the requestor or the implementation? */
1482 if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1484 nsname = @"highlightColor";
1487 lenum = [[NSColorList availableColorLists] objectEnumerator];
1488 while ( (clist = [lenum nextObject]) && new == nil)
1490 cenum = [[clist allKeys] objectEnumerator];
1491 while ( (name = [cenum nextObject]) && new == nil )
1493 if ([name compare: nsname
1494 options: NSCaseInsensitiveSearch] == NSOrderedSame )
1495 new = [clist colorWithKey: name];
1501 *col = [new colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1508 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1509 /* --------------------------------------------------------------------------
1510 Convert a Lisp string object to a NS color
1511 -------------------------------------------------------------------------- */
1513 NSTRACE (ns_lisp_to_color);
1514 if (STRINGP (color))
1515 return ns_get_color (SSDATA (color), col);
1516 else if (SYMBOLP (color))
1517 return ns_get_color (SSDATA (SYMBOL_NAME (color)), col);
1523 ns_color_to_lisp (NSColor *col)
1524 /* --------------------------------------------------------------------------
1525 Convert a color to a lisp string with the RGB equivalent
1526 -------------------------------------------------------------------------- */
1528 CGFloat red, green, blue, alpha, gray;
1531 NSTRACE (ns_color_to_lisp);
1534 if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1536 if ((str =[[col colorNameComponent] UTF8String]))
1539 return build_string ((char *)str);
1542 [[col colorUsingColorSpaceName: NSCalibratedRGBColorSpace]
1543 getRed: &red green: &green blue: &blue alpha: &alpha];
1544 if (red ==green && red ==blue)
1546 [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1547 getWhite: &gray alpha: &alpha];
1548 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1549 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1551 return build_string (buf);
1554 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1555 lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1558 return build_string (buf);
1563 ns_query_color(void *col, XColor *color_def, int setPixel)
1564 /* --------------------------------------------------------------------------
1565 Get ARGB values out of NSColor col and put them into color_def.
1566 If setPixel, set the pixel to a concatenated version.
1567 and set color_def pixel to the resulting index.
1568 -------------------------------------------------------------------------- */
1572 [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1573 color_def->red = r * 65535;
1574 color_def->green = g * 65535;
1575 color_def->blue = b * 65535;
1577 if (setPixel == YES)
1579 = ARGB_TO_ULONG((int)(a*255),
1580 (int)(r*255), (int)(g*255), (int)(b*255));
1585 ns_defined_color (struct frame *f,
1590 /* --------------------------------------------------------------------------
1591 Return 1 if named color found, and set color_def rgb accordingly.
1592 If makeIndex and alloc are nonzero put the color in the color_table,
1593 and set color_def pixel to the resulting index.
1594 If makeIndex is zero, set color_def pixel to ARGB.
1595 Return 0 if not found
1596 -------------------------------------------------------------------------- */
1599 NSTRACE (ns_defined_color);
1602 if (ns_get_color (name, &col) != 0) /* Color not found */
1607 if (makeIndex && alloc)
1608 color_def->pixel = ns_index_color (col, f);
1609 ns_query_color (col, color_def, !makeIndex);
1616 ns_get_rgb_color (struct frame *f, float r, float g, float b, float a)
1617 /* --------------------------------------------------------------------------
1618 return an autoreleased RGB color
1619 -------------------------------------------------------------------------- */
1621 /*static int c = 1; fprintf (stderr, "color request %d\n", c++); */
1622 if (r < 0.0) r = 0.0;
1623 else if (r > 1.0) r = 1.0;
1624 if (g < 0.0) g = 0.0;
1625 else if (g > 1.0) g = 1.0;
1626 if (b < 0.0) b = 0.0;
1627 else if (b > 1.0) b = 1.0;
1628 if (a < 0.0) a = 0.0;
1629 else if (a > 1.0) a = 1.0;
1630 return (unsigned long) ns_index_color(
1631 [NSColor colorWithCalibratedRed: r green: g blue: b alpha: a], f);
1636 x_set_frame_alpha (struct frame *f)
1637 /* --------------------------------------------------------------------------
1638 change the entire-frame transparency
1639 -------------------------------------------------------------------------- */
1641 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1642 EmacsView *view = FRAME_NS_VIEW (f);
1644 double alpha_min = 1.0;
1646 if (dpyinfo->x_highlight_frame == f)
1647 alpha = f->alpha[0];
1649 alpha = f->alpha[1];
1651 if (FLOATP (Vframe_alpha_lower_limit))
1652 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1653 else if (INTEGERP (Vframe_alpha_lower_limit))
1654 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1658 else if (1.0 < alpha)
1660 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1663 #ifdef NS_IMPL_COCOA
1664 [[view window] setAlphaValue: alpha];
1669 /* ==========================================================================
1673 ========================================================================== */
1677 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1678 /* --------------------------------------------------------------------------
1679 Programmatically reposition mouse pointer in pixel coordinates
1680 -------------------------------------------------------------------------- */
1682 NSTRACE (x_set_mouse_pixel_position);
1685 /* FIXME: this does not work, and what about GNUstep? */
1686 #ifdef NS_IMPL_COCOA
1687 [FRAME_NS_VIEW (f) lockFocus];
1688 PSsetmouse ((float)pix_x, (float)pix_y);
1689 [FRAME_NS_VIEW (f) unlockFocus];
1696 x_set_mouse_position (struct frame *f, int h, int v)
1697 /* --------------------------------------------------------------------------
1698 Programmatically reposition mouse pointer in character coordinates
1699 -------------------------------------------------------------------------- */
1703 pix_x = FRAME_COL_TO_PIXEL_X (f, h) + FRAME_COLUMN_WIDTH (f) / 2;
1704 pix_y = FRAME_LINE_TO_PIXEL_Y (f, v) + FRAME_LINE_HEIGHT (f) / 2;
1706 if (pix_x < 0) pix_x = 0;
1707 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
1709 if (pix_y < 0) pix_y = 0;
1710 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
1712 x_set_mouse_pixel_position (f, pix_x, pix_y);
1717 note_mouse_movement (struct frame *frame, float x, float y)
1718 /* ------------------------------------------------------------------------
1719 Called by EmacsView on mouseMovement events. Passes on
1720 to emacs mainstream code if we moved off of a rect of interest
1721 known as last_mouse_glyph.
1722 ------------------------------------------------------------------------ */
1724 // NSTRACE (note_mouse_movement);
1726 XSETFRAME (last_mouse_motion_frame, frame);
1728 /* Note, this doesn't get called for enter/leave, since we don't have a
1729 position. Those are taken care of in the corresponding NSView methods. */
1731 /* has movement gone beyond last rect we were tracking? */
1732 if (x < last_mouse_glyph.origin.x ||
1733 x >= (last_mouse_glyph.origin.x + last_mouse_glyph.size.width) ||
1734 y < last_mouse_glyph.origin.y ||
1735 y >= (last_mouse_glyph.origin.y + last_mouse_glyph.size.height))
1737 ns_update_begin(frame);
1738 frame->mouse_moved = 1;
1739 note_mouse_highlight (frame, x, y);
1740 remember_mouse_glyph (frame, x, y, &last_mouse_glyph);
1741 ns_update_end(frame);
1750 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1751 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1753 /* --------------------------------------------------------------------------
1754 External (hook): inform emacs about mouse position and hit parts.
1755 If a scrollbar is being dragged, set bar_window, part, x, y, time.
1756 x & y should be position in the scrollbar (the whole bar, not the handle)
1757 and length of scrollbar respectively
1758 -------------------------------------------------------------------------- */
1762 Lisp_Object frame, tail;
1764 struct ns_display_info *dpyinfo;
1766 NSTRACE (ns_mouse_position);
1770 fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1774 dpyinfo = FRAME_NS_DISPLAY_INFO (*fp);
1778 if (last_mouse_scroll_bar != nil && insist == 0)
1780 /* TODO: we do not use this path at the moment because drag events will
1781 go directly to the EmacsScroller. Leaving code in for now. */
1782 [last_mouse_scroll_bar getMouseMotionPart: (int *)part window: bar_window
1784 if (time) *time = last_mouse_movement_time;
1785 last_mouse_scroll_bar = nil;
1789 /* Clear the mouse-moved flag for every frame on this display. */
1790 FOR_EACH_FRAME (tail, frame)
1791 if (FRAME_NS_P (XFRAME (frame))
1792 && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1793 XFRAME (frame)->mouse_moved = 0;
1795 last_mouse_scroll_bar = nil;
1796 if (last_mouse_frame && FRAME_LIVE_P (last_mouse_frame))
1797 f = last_mouse_frame;
1799 f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame
1800 : SELECTED_FRAME ();
1802 if (f && f->output_data.ns) /* TODO: 2nd check no longer needed? */
1804 view = FRAME_NS_VIEW (*fp);
1806 position = [[view window] mouseLocationOutsideOfEventStream];
1807 position = [view convertPoint: position fromView: nil];
1808 remember_mouse_glyph (f, position.x, position.y, &last_mouse_glyph);
1809 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1811 if (bar_window) *bar_window = Qnil;
1812 if (part) *part = 0; /*scroll_bar_handle; */
1814 if (x) XSETINT (*x, lrint (position.x));
1815 if (y) XSETINT (*y, lrint (position.y));
1816 if (time) *time = last_mouse_movement_time;
1826 ns_frame_up_to_date (struct frame *f)
1827 /* --------------------------------------------------------------------------
1828 External (hook): Fix up mouse highlighting right after a full update.
1829 Some highlighting was deferred if GC was happening during
1830 note_mouse_highlight (), while other highlighting was deferred for update.
1831 -------------------------------------------------------------------------- */
1833 NSTRACE (ns_frame_up_to_date);
1837 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1838 if ((hlinfo->mouse_face_deferred_gc || f ==hlinfo->mouse_face_mouse_frame)
1839 /*&& hlinfo->mouse_face_mouse_frame*/)
1843 if (hlinfo->mouse_face_mouse_frame)
1844 note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
1845 hlinfo->mouse_face_mouse_x,
1846 hlinfo->mouse_face_mouse_y);
1847 hlinfo->mouse_face_deferred_gc = 0;
1856 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1857 /* --------------------------------------------------------------------------
1858 External (RIF): set frame mouse pointer type.
1859 -------------------------------------------------------------------------- */
1861 NSTRACE (ns_define_frame_cursor);
1862 if (FRAME_POINTER_TYPE (f) != cursor)
1864 EmacsView *view = FRAME_NS_VIEW (f);
1865 FRAME_POINTER_TYPE (f) = cursor;
1866 [[view window] invalidateCursorRectsForView: view];
1867 /* Redisplay assumes this function also draws the changed frame
1868 cursor, but this function doesn't, so do it explicitly. */
1869 x_update_cursor (f, 1);
1875 /* ==========================================================================
1879 ========================================================================== */
1883 ns_convert_key (unsigned code)
1884 /* --------------------------------------------------------------------------
1885 Internal call used by NSView-keyDown.
1886 -------------------------------------------------------------------------- */
1888 const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym)
1889 / sizeof (convert_ns_to_X_keysym[0]));
1891 /* An array would be faster, but less easy to read. */
1892 for (keysym = 0; keysym < last_keysym; keysym += 2)
1893 if (code == convert_ns_to_X_keysym[keysym])
1894 return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
1896 /* if decide to use keyCode and Carbon table, use this line:
1897 return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
1902 x_get_keysym_name (int keysym)
1903 /* --------------------------------------------------------------------------
1904 Called by keyboard.c. Not sure if the return val is important, except
1906 -------------------------------------------------------------------------- */
1908 static char value[16];
1909 NSTRACE (x_get_keysym_name);
1910 sprintf (value, "%d", keysym);
1916 /* ==========================================================================
1918 Block drawing operations
1920 ========================================================================== */
1924 ns_redraw_scroll_bars (struct frame *f)
1928 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
1929 NSTRACE (ns_judge_scroll_bars);
1930 for (i =[subviews count]-1; i >= 0; i--)
1932 view = [subviews objectAtIndex: i];
1933 if (![view isKindOfClass: [EmacsScroller class]]) continue;
1940 ns_clear_frame (struct frame *f)
1941 /* --------------------------------------------------------------------------
1942 External (hook): Erase the entire frame
1943 -------------------------------------------------------------------------- */
1945 NSView *view = FRAME_NS_VIEW (f);
1948 NSTRACE (ns_clear_frame);
1952 /* comes on initial frame because we have
1953 after-make-frame-functions = select-frame */
1954 if (!FRAME_DEFAULT_FACE (f))
1957 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
1959 output_cursor.hpos = output_cursor.vpos = 0;
1960 output_cursor.x = -1;
1965 ns_focus (f, &r, 1);
1966 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
1970 #ifdef NS_IMPL_COCOA
1971 [[view window] display]; /* redraw resize handle */
1974 /* as of 2006/11 or so this is now needed */
1975 ns_redraw_scroll_bars (f);
1981 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
1982 /* --------------------------------------------------------------------------
1983 External (RIF): Clear section of frame
1984 -------------------------------------------------------------------------- */
1986 NSRect r = NSMakeRect (x, y, width, height);
1987 NSView *view = FRAME_NS_VIEW (f);
1988 struct face *face = FRAME_DEFAULT_FACE (f);
1993 NSTRACE (ns_clear_frame_area);
1995 r = NSIntersectionRect (r, [view frame]);
1996 ns_focus (f, &r, 1);
1997 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
1999 #ifdef NS_IMPL_COCOA
2001 /* clip out the resize handle */
2002 NSWindow *window = [FRAME_NS_VIEW (f) window];
2004 = [view convertRect: ns_resize_handle_rect (window) fromView: nil];
2006 ir = NSIntersectionRect (r, ir);
2007 if (NSIsEmptyRect (ir))
2013 #ifdef NS_IMPL_COCOA
2017 NSRect r1 = r, r2 = r; /* upper and lower non-intersecting */
2018 r1.size.height -= ir.size.height;
2019 r2.origin.y += r1.size.height;
2020 r2.size.width -= ir.size.width;
2021 r2.size.height = ir.size.height;
2034 ns_scroll_run (struct window *w, struct run *run)
2035 /* --------------------------------------------------------------------------
2036 External (RIF): Insert or delete n lines at line vpos
2037 -------------------------------------------------------------------------- */
2039 struct frame *f = XFRAME (w->frame);
2040 int x, y, width, height, from_y, to_y, bottom_y;
2042 NSTRACE (ns_scroll_run);
2044 /* begin copy from other terms */
2045 /* Get frame-relative bounding box of the text display area of W,
2046 without mode lines. Include in this box the left and right
2048 window_box (w, -1, &x, &y, &width, &height);
2050 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2051 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2052 bottom_y = y + height;
2056 /* Scrolling up. Make sure we don't copy part of the mode
2057 line at the bottom. */
2058 if (from_y + run->height > bottom_y)
2059 height = bottom_y - from_y;
2061 height = run->height;
2065 /* Scrolling down. Make sure we don't copy over the mode line.
2067 if (to_y + run->height > bottom_y)
2068 height = bottom_y - to_y;
2070 height = run->height;
2072 /* end copy from other terms */
2083 NSRect srcRect = NSMakeRect (x, from_y, width, height);
2084 NSRect dstRect = NSMakeRect (x, to_y, width, height);
2085 NSPoint dstOrigin = NSMakePoint (x, to_y);
2087 ns_focus (f, &dstRect, 1);
2088 NSCopyBits (0, srcRect , dstOrigin);
2097 ns_after_update_window_line (struct glyph_row *desired_row)
2098 /* --------------------------------------------------------------------------
2099 External (RIF): preparatory to fringe update after text was updated
2100 -------------------------------------------------------------------------- */
2102 struct window *w = updated_window;
2106 NSTRACE (ns_after_update_window_line);
2108 /* begin copy from other terms */
2111 if (!desired_row->mode_line_p && !w->pseudo_window_p)
2112 desired_row->redraw_fringe_bitmaps_p = 1;
2114 /* When a window has disappeared, make sure that no rest of
2115 full-width rows stays visible in the internal border.
2116 Under NS this is drawn inside the fringes. */
2117 if (windows_or_buffers_changed
2118 && (f = XFRAME (w->frame),
2119 width = FRAME_INTERNAL_BORDER_WIDTH (f),
2121 && (height = desired_row->visible_height,
2124 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2126 /* Internal border is drawn below the tool bar. */
2127 if (WINDOWP (f->tool_bar_window)
2128 && w == XWINDOW (f->tool_bar_window))
2130 /* end copy from other terms */
2133 if (!desired_row->full_width_p)
2135 int x1 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2136 + WINDOW_LEFT_FRINGE_WIDTH (w);
2137 int x2 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2138 + FRAME_PIXEL_WIDTH (f) - NS_SCROLL_BAR_WIDTH (f)
2139 - WINDOW_RIGHT_FRINGE_WIDTH (w)
2140 - FRAME_INTERNAL_BORDER_WIDTH (f);
2141 ns_clear_frame_area (f, x1, y, width, height);
2142 ns_clear_frame_area (f, x2, y, width, height);
2150 ns_shift_glyphs_for_insert (struct frame *f,
2151 int x, int y, int width, int height,
2153 /* --------------------------------------------------------------------------
2154 External (RIF): copy an area horizontally, don't worry about clearing src
2155 -------------------------------------------------------------------------- */
2157 NSRect srcRect = NSMakeRect (x, y, width, height);
2158 NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2159 NSPoint dstOrigin = dstRect.origin;
2161 NSTRACE (ns_shift_glyphs_for_insert);
2163 ns_focus (f, &dstRect, 1);
2164 NSCopyBits (0, srcRect, dstOrigin);
2170 /* ==========================================================================
2172 Character encoding and metrics
2174 ========================================================================== */
2178 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2179 /* --------------------------------------------------------------------------
2180 External (RIF); compute left/right overhang of whole string and set in s
2181 -------------------------------------------------------------------------- */
2183 struct font *font = s->font;
2187 struct font_metrics metrics;
2188 unsigned int codes[2];
2189 codes[0] = *(s->char2b);
2190 codes[1] = *(s->char2b + s->nchars - 1);
2192 font->driver->text_extents (font, codes, 2, &metrics);
2193 s->left_overhang = -metrics.lbearing;
2195 = metrics.rbearing > metrics.width
2196 ? metrics.rbearing - metrics.width : 0;
2200 s->left_overhang = 0;
2201 s->right_overhang = ((struct nsfont_info *)font)->ital ?
2202 FONT_HEIGHT (font) * 0.2 : 0;
2208 /* ==========================================================================
2210 Fringe and cursor drawing
2212 ========================================================================== */
2215 extern int max_used_fringe_bitmap;
2217 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2218 struct draw_fringe_bitmap_params *p)
2219 /* --------------------------------------------------------------------------
2220 External (RIF); fringe-related
2221 -------------------------------------------------------------------------- */
2223 struct frame *f = XFRAME (WINDOW_FRAME (w));
2224 struct face *face = p->face;
2226 static EmacsImage **bimgs = NULL;
2227 static int nBimgs = 0;
2228 /* NS-specific: move internal border inside fringe */
2229 int x = p->bx < 0 ? p->x : p->bx;
2230 int wd = p->bx < 0 ? p->wd : p->nx;
2231 BOOL fringeOnVeryLeft
2232 = x - WINDOW_LEFT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w)
2233 - FRAME_INTERNAL_BORDER_WIDTH (f) < 10;
2234 BOOL fringeOnVeryRight
2235 = FRAME_PIXEL_WIDTH (f) - x - wd - FRAME_INTERNAL_BORDER_WIDTH (f)
2236 - WINDOW_RIGHT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w) < 10;
2237 int xAdjust = FRAME_INTERNAL_BORDER_WIDTH (f) *
2238 (fringeOnVeryLeft ? -1 : (fringeOnVeryRight ? 1 : 0));
2240 /* grow bimgs if needed */
2241 if (nBimgs < max_used_fringe_bitmap)
2243 bimgs = xrealloc (bimgs, max_used_fringe_bitmap * sizeof *bimgs);
2244 memset (bimgs + nBimgs, 0,
2245 (max_used_fringe_bitmap - nBimgs) * sizeof *bimgs);
2246 nBimgs = max_used_fringe_bitmap;
2249 /* Must clip because of partially visible lines. */
2250 rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
2251 ns_clip_to_row (w, row, -1, YES);
2253 if (p->bx >= 0 && !p->overlay_p)
2255 int yAdjust = rowY - FRAME_INTERNAL_BORDER_WIDTH (f) < 5 ?
2256 -FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2257 int yIncr = FRAME_PIXEL_HEIGHT (f) - (p->by+yAdjust + p->ny) < 5 ?
2258 FRAME_INTERNAL_BORDER_WIDTH (f) : 0
2259 + (yAdjust ? FRAME_INTERNAL_BORDER_WIDTH (f) : 0);
2260 NSRect r = NSMakeRect (p->bx+xAdjust, p->by+yAdjust, p->nx, p->ny+yIncr);
2262 [ns_lookup_indexed_color(face->background, f) set];
2268 NSRect r = NSMakeRect (p->x+xAdjust, p->y, p->wd, p->h);
2269 NSPoint pt = r.origin;
2270 EmacsImage *img = bimgs[p->which - 1];
2274 unsigned short *bits = p->bits + p->dh;
2277 unsigned char *cbits = xmalloc (len);
2279 for (i =0; i<len; i++)
2280 cbits[i] = ~(bits[i] & 0xff);
2281 img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2283 bimgs[p->which - 1] = img;
2288 /* Since we composite the bitmap instead of just blitting it, we need
2289 to erase the whole background. */
2290 [ns_lookup_indexed_color(face->background, f) set];
2293 [img setXBMColor: ns_lookup_indexed_color(face->foreground, f)];
2294 [img compositeToPoint: pt operation: NSCompositeSourceOver];
2301 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2302 int x, int y, int cursor_type, int cursor_width,
2303 int on_p, int active_p)
2304 /* --------------------------------------------------------------------------
2305 External call (RIF): draw cursor.
2306 Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2307 -------------------------------------------------------------------------- */
2310 int fx, fy, h, cursor_height;
2311 struct frame *f = WINDOW_XFRAME (w);
2312 struct glyph *phys_cursor_glyph;
2314 struct glyph *cursor_glyph;
2316 NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2318 /* If cursor is out of bounds, don't draw garbage. This can happen
2319 in mini-buffer windows when switching between echo area glyphs
2322 NSTRACE (dumpcursor);
2327 w->phys_cursor_type = cursor_type;
2328 w->phys_cursor_on_p = on_p;
2330 if (cursor_type == NO_CURSOR)
2332 w->phys_cursor_width = 0;
2336 if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2338 if (glyph_row->exact_window_width_line_p
2339 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2341 glyph_row->cursor_in_fringe_p = 1;
2342 draw_fringe_bitmap (w, glyph_row, 0);
2347 /* We draw the cursor (with NSRectFill), then draw the glyph on top
2348 (other terminals do it the other way round). We must set
2349 w->phys_cursor_width to the cursor width. For bar cursors, that
2350 is CURSOR_WIDTH; for box cursors, it is the glyph width. */
2351 get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2353 /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2354 to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2355 if (cursor_type == BAR_CURSOR)
2357 if (cursor_width < 1)
2358 cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2359 w->phys_cursor_width = cursor_width;
2361 /* If we have an HBAR, "cursor_width" MAY specify height. */
2362 else if (cursor_type == HBAR_CURSOR)
2364 cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2365 fy += h - cursor_height;
2369 r.origin.x = fx, r.origin.y = fy;
2371 r.size.width = w->phys_cursor_width;
2373 /* FIXME: if we overwrite the internal border area, it does not get erased;
2374 fix by truncating cursor, but better would be to erase properly */
2375 overspill = r.origin.x + r.size.width -
2376 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, WINDOW_BOX_RIGHT_EDGE_X (w)
2377 - WINDOW_TOTAL_FRINGE_WIDTH (w) - FRAME_INTERNAL_BORDER_WIDTH (f));
2379 r.size.width -= overspill;
2381 /* TODO: only needed in rare cases with last-resort font in HELLO..
2382 should we do this more efficiently? */
2383 ns_clip_to_row (w, glyph_row, -1, NO); /* do ns_focus(f, &r, 1); if remove */
2386 face = FACE_FROM_ID (f, phys_cursor_glyph->face_id);
2387 if (face && NS_FACE_BACKGROUND (face)
2388 == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2390 [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2391 hollow_color = FRAME_CURSOR_COLOR (f);
2394 [FRAME_CURSOR_COLOR (f) set];
2396 #ifdef NS_IMPL_COCOA
2397 /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2398 atomic. Cleaner ways of doing this should be investigated.
2399 One way would be to set a global variable DRAWING_CURSOR
2400 when making the call to draw_phys..(), don't focus in that
2401 case, then move the ns_unfocus() here after that call. */
2402 NSDisableScreenUpdates ();
2405 switch (cursor_type)
2409 case FILLED_BOX_CURSOR:
2412 case HOLLOW_BOX_CURSOR:
2415 NSRectFill (NSInsetRect (r, 1, 1));
2416 [FRAME_CURSOR_COLOR (f) set];
2423 /* If the character under cursor is R2L, draw the bar cursor
2424 on the right of its glyph, rather than on the left. */
2425 cursor_glyph = get_phys_cursor_glyph (w);
2426 if ((cursor_glyph->resolved_level & 1) != 0)
2427 s.origin.x += cursor_glyph->pixel_width - s.size.width;
2434 /* draw the character under the cursor */
2435 if (cursor_type != NO_CURSOR)
2436 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2438 #ifdef NS_IMPL_COCOA
2439 NSEnableScreenUpdates ();
2446 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2447 /* --------------------------------------------------------------------------
2448 External (RIF): Draw a vertical line.
2449 -------------------------------------------------------------------------- */
2451 struct frame *f = XFRAME (WINDOW_FRAME (w));
2453 NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2455 NSTRACE (ns_draw_vertical_window_border);
2457 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2459 [ns_lookup_indexed_color(face->foreground, f) set];
2461 ns_focus (f, &r, 1);
2468 show_hourglass (struct atimer *timer)
2470 if (hourglass_shown_p)
2475 /* TODO: add NSProgressIndicator to selected frame (see macfns.c) */
2477 hourglass_shown_p = 1;
2483 hide_hourglass (void)
2485 if (!hourglass_shown_p)
2490 /* TODO: remove NSProgressIndicator from all frames */
2492 hourglass_shown_p = 0;
2498 /* ==========================================================================
2500 Glyph drawing operations
2502 ========================================================================== */
2505 static inline NSRect
2506 ns_fix_rect_ibw (NSRect r, int fibw, int frame_pixel_width)
2507 /* --------------------------------------------------------------------------
2508 Under NS we draw internal borders inside fringes, and want full-width
2509 rendering to go all the way to edge. This function makes that correction.
2510 -------------------------------------------------------------------------- */
2512 if (r.origin.y <= fibw+1)
2514 r.size.height += r.origin.y;
2517 if (r.origin.x <= fibw+1)
2519 r.size.width += r.origin.x;
2522 if (frame_pixel_width - (r.origin.x+r.size.width) <= fibw+1)
2523 r.size.width += fibw;
2530 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2531 /* --------------------------------------------------------------------------
2532 Wrapper utility to account for internal border width on full-width lines,
2533 and allow top full-width rows to hit the frame top. nr should be pointer
2534 to two successive NSRects. Number of rects actually used is returned.
2535 -------------------------------------------------------------------------- */
2537 int n = get_glyph_string_clip_rects (s, nr, 2);
2538 if (s->row->full_width_p)
2540 *nr = ns_fix_rect_ibw (*nr, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2541 FRAME_PIXEL_WIDTH (s->f));
2543 *nr = ns_fix_rect_ibw (*(nr+1), FRAME_INTERNAL_BORDER_WIDTH (s->f),
2544 FRAME_PIXEL_WIDTH (s->f));
2549 /* --------------------------------------------------------------------
2550 Draw a wavy line under glyph string s. The wave fills wave_height
2557 wave_height = 3 | * * * *
2558 --------------------------------------------------------------------- */
2561 ns_draw_underwave (struct glyph_string *s, CGFloat width, CGFloat x)
2563 int wave_height = 3, wave_length = 3;
2564 int y, dx, dy, odd, xmax;
2569 dy = wave_height - 1;
2573 /* Find and set clipping rectangle */
2574 waveClip = NSMakeRect (x, y, width, wave_height);
2575 [[NSGraphicsContext currentContext] saveGraphicsState];
2576 NSRectClip (waveClip);
2578 /* Draw the waves */
2579 a.x = x - ((int)(x) % dx);
2581 odd = (int)(a.x/dx) % 2;
2591 [NSBezierPath strokeLineFromPoint:a toPoint:b];
2592 a.x = b.x, a.y = b.y;
2593 b.x += dx, b.y = y + odd*dy;
2597 /* Restore previous clipping rectangle(s) */
2598 [[NSGraphicsContext currentContext] restoreGraphicsState];
2604 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
2605 NSColor *defaultCol, CGFloat width, CGFloat x)
2606 /* --------------------------------------------------------------------------
2607 Draw underline, overline, and strike-through on glyph string s.
2608 -------------------------------------------------------------------------- */
2610 if (s->for_overlaps)
2614 if (face->underline_p)
2616 if (s->face->underline_type == FACE_UNDER_WAVE)
2618 if (face->underline_defaulted_p)
2621 [ns_lookup_indexed_color (face->underline_color, s->f) set];
2623 ns_draw_underwave (s, width, x);
2625 else if (s->face->underline_type == FACE_UNDER_LINE)
2629 unsigned long thickness, position;
2631 /* If the prev was underlined, match its appearance. */
2632 if (s->prev && s->prev->face->underline_p
2633 && s->prev->underline_thickness > 0)
2635 thickness = s->prev->underline_thickness;
2636 position = s->prev->underline_position;
2641 unsigned long descent;
2644 descent = s->y + s->height - s->ybase;
2646 /* Use underline thickness of font, defaulting to 1. */
2647 thickness = (font && font->underline_thickness > 0)
2648 ? font->underline_thickness : 1;
2650 /* Determine the offset of underlining from the baseline. */
2651 if (x_underline_at_descent_line)
2652 position = descent - thickness;
2653 else if (x_use_underline_position_properties
2654 && font && font->underline_position >= 0)
2655 position = font->underline_position;
2657 position = lround (font->descent / 2);
2659 position = underline_minimum_offset;
2661 position = max (position, underline_minimum_offset);
2663 /* Ensure underlining is not cropped. */
2664 if (descent <= position)
2666 position = descent - 1;
2669 else if (descent < position + thickness)
2673 s->underline_thickness = thickness;
2674 s->underline_position = position;
2676 r = NSMakeRect (x, s->ybase + position, width, thickness);
2678 if (face->underline_defaulted_p)
2681 [ns_lookup_indexed_color (face->underline_color, s->f) set];
2685 /* Do overline. We follow other terms in using a thickness of 1
2686 and ignoring overline_margin. */
2687 if (face->overline_p)
2690 r = NSMakeRect (x, s->y, width, 1);
2692 if (face->overline_color_defaulted_p)
2695 [ns_lookup_indexed_color (face->overline_color, s->f) set];
2699 /* Do strike-through. We follow other terms for thickness and
2700 vertical position.*/
2701 if (face->strike_through_p)
2706 dy = lrint ((s->height - 1) / 2);
2707 r = NSMakeRect (x, s->y + dy, width, 1);
2709 if (face->strike_through_color_defaulted_p)
2712 [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
2718 ns_draw_box (NSRect r, float thickness, NSColor *col, char left_p, char right_p)
2719 /* --------------------------------------------------------------------------
2720 Draw an unfilled rect inside r, optionally leaving left and/or right open.
2721 Note we can't just use an NSDrawRect command, because of the possibility
2722 of some sides not being drawn, and because the rect will be filled.
2723 -------------------------------------------------------------------------- */
2729 s.size.height = thickness;
2731 s.origin.y += r.size.height - thickness;
2734 s.size.height = r.size.height;
2735 s.origin.y = r.origin.y;
2737 /* left, right (optional) */
2738 s.size.width = thickness;
2743 s.origin.x += r.size.width - thickness;
2750 ns_draw_relief (NSRect r, int thickness, char raised_p,
2751 char top_p, char bottom_p, char left_p, char right_p,
2752 struct glyph_string *s)
2753 /* --------------------------------------------------------------------------
2754 Draw a relief rect inside r, optionally leaving some sides open.
2755 Note we can't just use an NSDrawBezel command, because of the possibility
2756 of some sides not being drawn, and because the rect will be filled.
2757 -------------------------------------------------------------------------- */
2759 static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2760 NSColor *newBaseCol = nil;
2763 NSTRACE (ns_draw_relief);
2767 if (s->face->use_box_color_for_shadows_p)
2769 newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2771 /* else if (s->first_glyph->type == IMAGE_GLYPH
2773 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2775 newBaseCol = IMAGE_BACKGROUND (s->img, s->f, 0);
2779 newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2782 if (newBaseCol == nil)
2783 newBaseCol = [NSColor grayColor];
2785 if (newBaseCol != baseCol) /* TODO: better check */
2788 baseCol = [newBaseCol retain];
2790 lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2792 darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2795 [(raised_p ? lightCol : darkCol) set];
2797 /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2800 sr.size.height = thickness;
2801 if (top_p) NSRectFill (sr);
2804 sr.size.height = r.size.height;
2805 sr.size.width = thickness;
2806 if (left_p) NSRectFill (sr);
2808 [(raised_p ? darkCol : lightCol) set];
2811 sr.size.width = r.size.width;
2812 sr.size.height = thickness;
2813 sr.origin.y += r.size.height - thickness;
2814 if (bottom_p) NSRectFill (sr);
2817 sr.size.height = r.size.height;
2818 sr.origin.y = r.origin.y;
2819 sr.size.width = thickness;
2820 sr.origin.x += r.size.width - thickness;
2821 if (right_p) NSRectFill (sr);
2826 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2827 /* --------------------------------------------------------------------------
2828 Function modeled after x_draw_glyph_string_box ().
2829 Sets up parameters for drawing.
2830 -------------------------------------------------------------------------- */
2832 int right_x, last_x;
2833 char left_p, right_p;
2834 struct glyph *last_glyph;
2839 if (s->hl == DRAW_MOUSE_FACE)
2841 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2843 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2848 thickness = face->box_line_width;
2850 NSTRACE (ns_dumpglyphs_box_or_relief);
2852 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2853 ? WINDOW_RIGHT_EDGE_X (s->w)
2854 : window_box_right (s->w, s->area));
2855 last_glyph = (s->cmp || s->img
2856 ? s->first_glyph : s->first_glyph + s->nchars-1);
2858 right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2859 ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2861 left_p = (s->first_glyph->left_box_line_p
2862 || (s->hl == DRAW_MOUSE_FACE
2863 && (s->prev == NULL || s->prev->hl != s->hl)));
2864 right_p = (last_glyph->right_box_line_p
2865 || (s->hl == DRAW_MOUSE_FACE
2866 && (s->next == NULL || s->next->hl != s->hl)));
2868 r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2870 /* expand full-width row over internal borders */
2871 if (s->row->full_width_p)
2872 r = ns_fix_rect_ibw (r, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2873 FRAME_PIXEL_WIDTH (s->f));
2875 /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
2876 if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
2878 ns_draw_box (r, abs (thickness),
2879 ns_lookup_indexed_color (face->box_color, s->f),
2884 ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2885 1, 1, left_p, right_p, s);
2891 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2892 /* --------------------------------------------------------------------------
2893 Modeled after x_draw_glyph_string_background, which draws BG in
2894 certain cases. Others are left to the text rendering routine.
2895 -------------------------------------------------------------------------- */
2897 NSTRACE (ns_maybe_dumpglyphs_background);
2899 if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2901 int box_line_width = max (s->face->box_line_width, 0);
2902 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2903 || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2906 if (s->hl == DRAW_MOUSE_FACE)
2908 face = FACE_FROM_ID (s->f,
2909 MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2911 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2914 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2916 [(NS_FACE_BACKGROUND (face) != 0
2917 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2918 : FRAME_BACKGROUND_COLOR (s->f)) set];
2921 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (s->f);
2922 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2925 if (s->hl != DRAW_CURSOR)
2927 NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2928 s->background_width,
2929 s->height-2*box_line_width);
2931 /* expand full-width row over internal borders */
2932 if (s->row->full_width_p)
2934 int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2935 if (r.origin.y <= fibw+1 + box_line_width)
2937 r.size.height += r.origin.y;
2940 if (r.origin.x <= fibw+1)
2942 r.size.width += 2*r.origin.x;
2945 if (FRAME_PIXEL_WIDTH (s->f) - (r.origin.x + r.size.width)
2947 r.size.width += fibw;
2953 s->background_filled_p = 1;
2960 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2961 /* --------------------------------------------------------------------------
2962 Renders an image and associated borders.
2963 -------------------------------------------------------------------------- */
2965 EmacsImage *img = s->img->pixmap;
2966 int box_line_vwidth = max (s->face->box_line_width, 0);
2967 int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2968 int bg_x, bg_y, bg_height;
2975 NSTRACE (ns_dumpglyphs_image);
2977 if (s->face->box != FACE_NO_BOX
2978 && s->first_glyph->left_box_line_p && s->slice.x == 0)
2979 x += abs (s->face->box_line_width);
2982 bg_y = s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2983 bg_height = s->height;
2984 /* other terms have this, but was causing problems w/tabbar mode */
2985 /* - 2 * box_line_vwidth; */
2987 if (s->slice.x == 0) x += s->img->hmargin;
2988 if (s->slice.y == 0) y += s->img->vmargin;
2990 /* Draw BG: if we need larger area than image itself cleared, do that,
2991 otherwise, since we composite the image under NS (instead of mucking
2992 with its background color), we must clear just the image area. */
2993 if (s->hl == DRAW_MOUSE_FACE)
2995 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2997 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3000 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3002 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
3004 if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
3005 || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
3007 br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
3008 s->background_filled_p = 1;
3012 br = NSMakeRect (x, y, s->slice.width, s->slice.height);
3015 /* expand full-width row over internal borders */
3016 if (s->row->full_width_p)
3018 int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
3019 if (br.origin.y <= fibw+1 + box_line_vwidth)
3021 br.size.height += br.origin.y;
3024 if (br.origin.x <= fibw+1 + box_line_vwidth)
3026 br.size.width += br.origin.x;
3029 if (FRAME_PIXEL_WIDTH (s->f) - (br.origin.x + br.size.width) <= fibw+1)
3030 br.size.width += fibw;
3035 /* Draw the image.. do we need to draw placeholder if img ==nil? */
3037 [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3038 operation: NSCompositeSourceOver];
3040 if (s->hl == DRAW_CURSOR)
3042 [FRAME_CURSOR_COLOR (s->f) set];
3043 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3044 tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3046 /* Currently on NS img->mask is always 0. Since
3047 get_window_cursor_type specifies a hollow box cursor when on
3048 a non-masked image we never reach this clause. But we put it
3049 in in anticipation of better support for image masks on
3051 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3055 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3058 /* Draw underline, overline, strike-through. */
3059 ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3061 /* Draw relief, if requested */
3062 if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3064 if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3066 th = tool_bar_button_relief >= 0 ?
3067 tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3068 raised_p = (s->hl == DRAW_IMAGE_RAISED);
3072 th = abs (s->img->relief);
3073 raised_p = (s->img->relief > 0);
3076 r.origin.x = x - th;
3077 r.origin.y = y - th;
3078 r.size.width = s->slice.width + 2*th-1;
3079 r.size.height = s->slice.height + 2*th-1;
3080 ns_draw_relief (r, th, raised_p,
3082 s->slice.y + s->slice.height == s->img->height,
3084 s->slice.x + s->slice.width == s->img->width, s);
3087 /* If there is no mask, the background won't be seen,
3088 so draw a rectangle on the image for the cursor.
3089 Do this for all images, getting transparency right is not reliable. */
3090 if (s->hl == DRAW_CURSOR)
3092 int thickness = abs (s->img->relief);
3093 if (thickness == 0) thickness = 1;
3094 ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3100 ns_dumpglyphs_stretch (struct glyph_string *s)
3105 NSColor *fgCol, *bgCol;
3107 if (!s->background_filled_p)
3109 n = ns_get_glyph_string_clip_rect (s, r);
3110 *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3112 ns_focus (s->f, r, n);
3114 if (s->hl == DRAW_MOUSE_FACE)
3116 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3118 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3121 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3123 bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3124 fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3128 if (!s->row->full_width_p)
3130 int overrun, leftoverrun;
3132 /* truncate to avoid overwriting fringe and/or scrollbar */
3133 overrun = max (0, (s->x + s->background_width)
3134 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3135 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3136 r[i].size.width -= overrun;
3138 /* truncate to avoid overwriting to left of the window box */
3139 leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3140 + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3142 if (leftoverrun > 0)
3144 r[i].origin.x += leftoverrun;
3145 r[i].size.width -= leftoverrun;
3148 /* XXX: Try to work between problem where a stretch glyph on
3149 a partially-visible bottom row will clear part of the
3150 modeline, and another where list-buffers headers and similar
3151 rows erroneously have visible_height set to 0. Not sure
3152 where this is coming from as other terms seem not to show. */
3153 r[i].size.height = min (s->height, s->row->visible_height);
3156 /* expand full-width rows over internal borders */
3159 r[i] = ns_fix_rect_ibw (r[i], FRAME_INTERNAL_BORDER_WIDTH (s->f),
3160 FRAME_PIXEL_WIDTH (s->f));
3165 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3166 overwriting cursor (usually when cursor on a tab) */
3167 if (s->hl == DRAW_CURSOR)
3172 width = s->w->phys_cursor_width;
3173 r[i].size.width -= width;
3174 r[i].origin.x += width;
3178 /* Draw overlining, etc. on the cursor. */
3179 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3180 ns_draw_text_decoration (s, face, bgCol, width, x);
3182 ns_draw_text_decoration (s, face, fgCol, width, x);
3189 /* Draw overlining, etc. on the stretch glyph (or the part
3190 of the stretch glyph after the cursor). */
3191 ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3195 s->background_filled_p = 1;
3201 ns_draw_glyph_string (struct glyph_string *s)
3202 /* --------------------------------------------------------------------------
3203 External (RIF): Main draw-text call.
3204 -------------------------------------------------------------------------- */
3206 /* TODO (optimize): focus for box and contents draw */
3209 char box_drawn_p = 0;
3211 NSTRACE (ns_draw_glyph_string);
3213 if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3216 struct glyph_string *next;
3218 for (width = 0, next = s->next;
3219 next && width < s->right_overhang;
3220 width += next->width, next = next->next)
3221 if (next->first_glyph->type != IMAGE_GLYPH)
3223 if (next->first_glyph->type != STRETCH_GLYPH)
3225 n = ns_get_glyph_string_clip_rect (s->next, r);
3226 ns_focus (s->f, r, n);
3227 ns_maybe_dumpglyphs_background (s->next, 1);
3232 ns_dumpglyphs_stretch (s->next);
3234 next->num_clips = 0;
3238 if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3239 && (s->first_glyph->type == CHAR_GLYPH
3240 || s->first_glyph->type == COMPOSITE_GLYPH))
3242 n = ns_get_glyph_string_clip_rect (s, r);
3243 ns_focus (s->f, r, n);
3244 ns_maybe_dumpglyphs_background (s, 1);
3245 ns_dumpglyphs_box_or_relief (s);
3250 switch (s->first_glyph->type)
3254 n = ns_get_glyph_string_clip_rect (s, r);
3255 ns_focus (s->f, r, n);
3256 ns_dumpglyphs_image (s, r[0]);
3261 ns_dumpglyphs_stretch (s);
3265 case COMPOSITE_GLYPH:
3266 n = ns_get_glyph_string_clip_rect (s, r);
3267 ns_focus (s->f, r, n);
3269 if (s->for_overlaps || (s->cmp_from > 0
3270 && ! s->first_glyph->u.cmp.automatic))
3271 s->background_filled_p = 1;
3273 ns_maybe_dumpglyphs_background
3274 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3276 ns_tmp_flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3277 (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3278 (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3279 NS_DUMPGLYPH_NORMAL));
3280 ns_tmp_font = (struct nsfont_info *)s->face->font;
3281 if (ns_tmp_font == NULL)
3282 ns_tmp_font = (struct nsfont_info *)FRAME_FONT (s->f);
3284 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3286 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3287 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3288 NS_FACE_FOREGROUND (s->face) = tmp;
3291 ns_tmp_font->font.driver->draw
3292 (s, 0, s->nchars, s->x, s->y,
3293 (ns_tmp_flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3294 || ns_tmp_flags == NS_DUMPGLYPH_MOUSEFACE);
3296 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3298 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3299 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3300 NS_FACE_FOREGROUND (s->face) = tmp;
3306 case GLYPHLESS_GLYPH:
3307 n = ns_get_glyph_string_clip_rect (s, r);
3308 ns_focus (s->f, r, n);
3310 if (s->for_overlaps || (s->cmp_from > 0
3311 && ! s->first_glyph->u.cmp.automatic))
3312 s->background_filled_p = 1;
3314 ns_maybe_dumpglyphs_background
3315 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3317 /* Not yet implemented. */
3326 /* Draw box if not done already. */
3327 if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3329 n = ns_get_glyph_string_clip_rect (s, r);
3330 ns_focus (s->f, r, n);
3331 ns_dumpglyphs_box_or_relief (s);
3340 /* ==========================================================================
3344 ========================================================================== */
3348 ns_send_appdefined (int value)
3349 /* --------------------------------------------------------------------------
3350 Internal: post an appdefined event which EmacsApp-sendEvent will
3351 recognize and take as a command to halt the event loop.
3352 -------------------------------------------------------------------------- */
3354 /*NSTRACE (ns_send_appdefined); */
3356 /* Only post this event if we haven't already posted one. This will end
3357 the [NXApp run] main loop after having processed all events queued at
3359 if (send_appdefined)
3363 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
3364 send_appdefined = NO;
3366 /* Don't need wakeup timer any more */
3369 [timed_entry invalidate];
3370 [timed_entry release];
3374 /* Ditto for file descriptor poller */
3377 [fd_entry invalidate];
3382 nxev = [NSEvent otherEventWithType: NSApplicationDefined
3383 location: NSMakePoint (0, 0)
3386 windowNumber: [[NSApp mainWindow] windowNumber]
3387 context: [NSApp context]
3392 /* Post an application defined event on the event queue. When this is
3393 received the [NXApp run] will return, thus having processed all
3394 events which are currently queued. */
3395 [NSApp postEvent: nxev atStart: NO];
3401 ns_read_socket (struct terminal *terminal, int expected,
3402 struct input_event *hold_quit)
3403 /* --------------------------------------------------------------------------
3404 External (hook): Post an event to ourself and keep reading events until
3405 we read it back again. In effect process all events which were waiting.
3406 From 21+ we have to manage the event buffer ourselves.
3407 -------------------------------------------------------------------------- */
3409 struct input_event ev;
3412 /* NSTRACE (ns_read_socket); */
3414 if (interrupt_input_blocked)
3416 interrupt_input_pending = 1;
3418 pending_signals = 1;
3423 interrupt_input_pending = 0;
3425 pending_signals = pending_atimers;
3429 n_emacs_events_pending = 0;
3432 q_event_ptr = hold_quit;
3434 /* we manage autorelease pools by allocate/reallocate each time around
3435 the loop; strict nesting is occasionally violated but seems not to
3436 matter.. earlier methods using full nesting caused major memory leaks */
3437 [outerpool release];
3438 outerpool = [[NSAutoreleasePool alloc] init];
3440 /* If have pending open-file requests, attend to the next one of those. */
3441 if (ns_pending_files && [ns_pending_files count] != 0
3442 && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3444 [ns_pending_files removeObjectAtIndex: 0];
3446 /* Deal with pending service requests. */
3447 else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3449 NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3450 withArg: [ns_pending_service_args objectAtIndex: 0]])
3452 [ns_pending_service_names removeObjectAtIndex: 0];
3453 [ns_pending_service_args removeObjectAtIndex: 0];
3457 /* Run and wait for events. We must always send one NX_APPDEFINED event
3458 to ourself, otherwise [NXApp run] will never exit. */
3459 send_appdefined = YES;
3461 /* If called via ns_select, this is called once with expected=1,
3462 because we expect either the timeout or file descriptor activity.
3463 In this case the first event through will either be real input or
3464 one of these. read_avail_input() then calls once more with expected=0
3465 and in that case we need to return quickly if there is nothing.
3466 If we're being called outside of that, it's also OK to return quickly
3467 after one iteration through the event loop, since other terms do
3468 this and emacs expects it. */
3469 if (!(inNsSelect && expected))
3471 /* Post an application defined event on the event queue. When this is
3472 received the [NXApp run] will return, thus having processed all
3473 events which are currently queued, if any. */
3474 ns_send_appdefined (-1);
3480 nevents = n_emacs_events_pending;
3481 n_emacs_events_pending = 0;
3482 emacs_event = q_event_ptr = NULL;
3490 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3491 fd_set *exceptfds, EMACS_TIME *timeout, sigset_t *sigmask)
3492 /* --------------------------------------------------------------------------
3493 Replacement for select, checking for events
3494 -------------------------------------------------------------------------- */
3499 struct timespec select_timeout;
3501 /* NSTRACE (ns_select); */
3503 if (NSApp == nil || inNsSelect == 1 /* || ([NSApp isActive] == NO &&
3504 [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
3505 inMode:NSDefaultRunLoopMode dequeue:NO] == nil) */)
3506 return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
3508 /* Save file descriptor set, which gets overwritten in calls to select ()
3509 Note, this is called from process.c, and only readfds is ever set */
3512 memcpy (&select_readfds, readfds, sizeof (fd_set));
3518 /* Try an initial select for pending data on input files */
3519 select_timeout.tv_sec = select_timeout.tv_nsec = 0;
3520 result = pselect (nfds, readfds, writefds, exceptfds,
3521 &select_timeout, sigmask);
3525 /* if (!timeout || timed_entry || fd_entry)
3526 fprintf (stderr, "assertion failed: timeout null or timed_entry/fd_entry non-null in ns_select\n"); */
3528 /* set a timeout and run the main AppKit event loop while continuing
3529 to monitor the files */
3530 time = EMACS_TIME_TO_DOUBLE (*timeout);
3531 timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3533 selector: @selector (timeout_handler:)
3535 repeats: YES] /* for safe removal */
3538 /* set a periodic task to try the pselect () again */
3539 fd_entry = [[NSTimer scheduledTimerWithTimeInterval: 0.1
3541 selector: @selector (fd_handler:)
3546 /* Let Application dispatch events until it receives an event of the type
3547 NX_APPDEFINED, which should only be sent by timeout_handler.
3548 We tell read_avail_input() that input is "expected" because we do expect
3549 either the timeout or fd handler to fire, and if they don't, the original
3550 call from process.c that got us here expects us to wait until some input
3554 ev = last_appdefined_event;
3560 if ([ev type] != NSApplicationDefined)
3564 last_appdefined_event = 0;
3568 /* The NX_APPDEFINED event we received was a timeout. */
3573 /* The NX_APPDEFINED event we received was the result of
3574 at least one real input event arriving. */
3580 /* Received back from pselect () in fd_handler; copy the results */
3582 memcpy (readfds, &select_readfds, sizeof (fd_set));
3586 /* never reached, shut compiler up */
3592 /* ==========================================================================
3596 ========================================================================== */
3600 ns_set_vertical_scroll_bar (struct window *window,
3601 int portion, int whole, int position)
3602 /* --------------------------------------------------------------------------
3603 External (hook): Update or add scrollbar
3604 -------------------------------------------------------------------------- */
3608 struct frame *f = XFRAME (WINDOW_FRAME (window));
3609 EmacsView *view = FRAME_NS_VIEW (f);
3610 int window_y, window_height;
3611 BOOL barOnVeryLeft, barOnVeryRight;
3612 int top, left, height, width, sb_width, sb_left;
3615 /* optimization; display engine sends WAY too many of these.. */
3616 if (!NILP (window->vertical_scroll_bar))
3618 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3619 if ([bar checkSamePosition: position portion: portion whole: whole])
3621 if (view->scrollbarsNeedingUpdate == 0)
3623 if (!windows_or_buffers_changed)
3627 view->scrollbarsNeedingUpdate--;
3631 NSTRACE (ns_set_vertical_scroll_bar);
3633 /* Get dimensions. */
3634 window_box (window, -1, 0, &window_y, 0, &window_height);
3636 height = window_height;
3637 width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3638 left = WINDOW_SCROLL_BAR_AREA_X (window);
3640 if (top < 5) /* top scrollbar adjustment */
3642 top -= FRAME_INTERNAL_BORDER_WIDTH (f);
3643 height += FRAME_INTERNAL_BORDER_WIDTH (f);
3646 /* allow for displaying a skinnier scrollbar than char area allotted */
3647 sb_width = (WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) > 0) ?
3648 WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) : width;
3650 barOnVeryLeft = left < 5;
3651 barOnVeryRight = FRAME_PIXEL_WIDTH (f) - left - width < 5;
3652 sb_left = left + FRAME_INTERNAL_BORDER_WIDTH (f)
3653 * (barOnVeryLeft ? -1 : (barOnVeryRight ? 1 : 0));
3655 r = NSMakeRect (sb_left, top, sb_width, height);
3656 /* the parent view is flipped, so we need to flip y value */
3658 r.origin.y = (v.size.height - r.size.height - r.origin.y);
3660 XSETWINDOW (win, window);
3663 /* we want at least 5 lines to display a scrollbar */
3664 if (WINDOW_TOTAL_LINES (window) < 5)
3666 if (!NILP (window->vertical_scroll_bar))
3668 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3669 [bar removeFromSuperview];
3670 window->vertical_scroll_bar = Qnil;
3672 ns_clear_frame_area (f, sb_left, top, width, height);
3677 if (NILP (window->vertical_scroll_bar))
3679 ns_clear_frame_area (f, sb_left, top, width, height);
3680 bar = [[EmacsScroller alloc] initFrame: r window: win];
3681 window->vertical_scroll_bar = make_save_value (bar, 0);
3686 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3687 oldRect = [bar frame];
3688 r.size.width = oldRect.size.width;
3689 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3691 if (oldRect.origin.x != r.origin.x)
3692 ns_clear_frame_area (f, sb_left, top, width, height);
3697 [bar setPosition: position portion: portion whole: whole];
3703 ns_condemn_scroll_bars (struct frame *f)
3704 /* --------------------------------------------------------------------------
3705 External (hook): arrange for all frame's scrollbars to be removed
3706 at next call to judge_scroll_bars, except for those redeemed.
3707 -------------------------------------------------------------------------- */
3711 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3713 NSTRACE (ns_condemn_scroll_bars);
3715 for (i =[subviews count]-1; i >= 0; i--)
3717 view = [subviews objectAtIndex: i];
3718 if ([view isKindOfClass: [EmacsScroller class]])
3725 ns_redeem_scroll_bar (struct window *window)
3726 /* --------------------------------------------------------------------------
3727 External (hook): arrange to spare this window's scrollbar
3728 at next call to judge_scroll_bars.
3729 -------------------------------------------------------------------------- */
3732 NSTRACE (ns_redeem_scroll_bar);
3733 if (!NILP (window->vertical_scroll_bar))
3735 bar =XNS_SCROLL_BAR (window->vertical_scroll_bar);
3742 ns_judge_scroll_bars (struct frame *f)
3743 /* --------------------------------------------------------------------------
3744 External (hook): destroy all scrollbars on frame that weren't
3745 redeemed after call to condemn_scroll_bars.
3746 -------------------------------------------------------------------------- */
3750 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3751 NSTRACE (ns_judge_scroll_bars);
3752 for (i =[subviews count]-1; i >= 0; i--)
3754 view = [subviews objectAtIndex: i];
3755 if (![view isKindOfClass: [EmacsScroller class]]) continue;
3762 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
3764 /* XXX irrelevant under NS */
3769 /* ==========================================================================
3773 ========================================================================== */
3776 x_display_pixel_height (struct ns_display_info *dpyinfo)
3778 NSScreen *screen = [NSScreen mainScreen];
3779 return [screen frame].size.height;
3783 x_display_pixel_width (struct ns_display_info *dpyinfo)
3785 NSScreen *screen = [NSScreen mainScreen];
3786 return [screen frame].size.width;
3790 static Lisp_Object ns_string_to_lispmod (const char *s)
3791 /* --------------------------------------------------------------------------
3792 Convert modifier name to lisp symbol
3793 -------------------------------------------------------------------------- */
3795 if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
3797 else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
3799 else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
3801 else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
3803 else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
3805 else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
3813 ns_default (const char *parameter, Lisp_Object *result,
3814 Lisp_Object yesval, Lisp_Object noval,
3815 BOOL is_float, BOOL is_modstring)
3816 /* --------------------------------------------------------------------------
3817 Check a parameter value in user's preferences
3818 -------------------------------------------------------------------------- */
3820 const char *value = ns_get_defaults_value (parameter);
3826 if (c_strcasecmp (value, "YES") == 0)
3828 else if (c_strcasecmp (value, "NO") == 0)
3830 else if (is_float && (f = strtod (value, &pos), pos != value))
3831 *result = make_float (f);
3832 else if (is_modstring && value)
3833 *result = ns_string_to_lispmod (value);
3834 else fprintf (stderr,
3835 "Bad value for default \"%s\": \"%s\"\n", parameter, value);
3841 ns_initialize_display_info (struct ns_display_info *dpyinfo)
3842 /* --------------------------------------------------------------------------
3843 Initialize global info and storage for display.
3844 -------------------------------------------------------------------------- */
3846 NSScreen *screen = [NSScreen mainScreen];
3847 NSWindowDepth depth = [screen depth];
3848 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
3850 dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
3851 dpyinfo->resy = 72.27;
3852 dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
3853 NSColorSpaceFromDepth (depth)]
3854 && ![NSCalibratedWhiteColorSpace isEqualToString:
3855 NSColorSpaceFromDepth (depth)];
3856 dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
3857 dpyinfo->image_cache = make_image_cache ();
3858 dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
3859 dpyinfo->color_table->colors = NULL;
3860 dpyinfo->root_window = 42; /* a placeholder.. */
3862 hlinfo->mouse_face_mouse_frame = NULL;
3863 hlinfo->mouse_face_deferred_gc = 0;
3864 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
3865 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
3866 hlinfo->mouse_face_face_id = DEFAULT_FACE_ID;
3867 hlinfo->mouse_face_window = hlinfo->mouse_face_overlay = Qnil;
3868 hlinfo->mouse_face_hidden = 0;
3870 hlinfo->mouse_face_mouse_x = hlinfo->mouse_face_mouse_y = 0;
3871 hlinfo->mouse_face_defer = 0;
3873 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
3875 dpyinfo->n_fonts = 0;
3876 dpyinfo->smallest_font_height = 1;
3877 dpyinfo->smallest_char_width = 1;
3881 /* This and next define (many of the) public functions in this file. */
3882 /* x_... are generic versions in xdisp.c that we, and other terms, get away
3883 with using despite presence in the "system dependent" redisplay
3884 interface. In addition, many of the ns_ methods have code that is
3885 shared with all terms, indicating need for further refactoring. */
3886 extern frame_parm_handler ns_frame_parm_handlers[];
3887 static struct redisplay_interface ns_redisplay_interface =
3889 ns_frame_parm_handlers,
3893 x_clear_end_of_line,
3895 ns_after_update_window_line,
3896 ns_update_window_begin,
3897 ns_update_window_end,
3900 0, /* flush_display_optional */
3901 x_clear_window_mouse_face,
3902 x_get_glyph_overhangs,
3903 x_fix_overlapping_area,
3904 ns_draw_fringe_bitmap,
3905 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
3906 0, /* destroy_fringe_bitmap */
3907 ns_compute_glyph_string_overhangs,
3908 ns_draw_glyph_string, /* interface to nsfont.m */
3909 ns_define_frame_cursor,
3910 ns_clear_frame_area,
3911 ns_draw_window_cursor,
3912 ns_draw_vertical_window_border,
3913 ns_shift_glyphs_for_insert
3918 ns_delete_display (struct ns_display_info *dpyinfo)
3924 /* This function is called when the last frame on a display is deleted. */
3926 ns_delete_terminal (struct terminal *terminal)
3928 struct ns_display_info *dpyinfo = terminal->display_info.ns;
3930 /* Protect against recursive calls. delete_frame in
3931 delete_terminal calls us back when it deletes our last frame. */
3932 if (!terminal->name)
3937 x_destroy_all_bitmaps (dpyinfo);
3938 ns_delete_display (dpyinfo);
3943 static struct terminal *
3944 ns_create_terminal (struct ns_display_info *dpyinfo)
3945 /* --------------------------------------------------------------------------
3946 Set up use of NS before we make the first connection.
3947 -------------------------------------------------------------------------- */
3949 struct terminal *terminal;
3951 NSTRACE (ns_create_terminal);
3953 terminal = create_terminal ();
3955 terminal->type = output_ns;
3956 terminal->display_info.ns = dpyinfo;
3957 dpyinfo->terminal = terminal;
3959 terminal->rif = &ns_redisplay_interface;
3961 terminal->clear_frame_hook = ns_clear_frame;
3962 terminal->ins_del_lines_hook = 0; /* XXX vestigial? */
3963 terminal->delete_glyphs_hook = 0; /* XXX vestigial? */
3964 terminal->ring_bell_hook = ns_ring_bell;
3965 terminal->reset_terminal_modes_hook = ns_reset_terminal_modes;
3966 terminal->set_terminal_modes_hook = ns_set_terminal_modes;
3967 terminal->update_begin_hook = ns_update_begin;
3968 terminal->update_end_hook = ns_update_end;
3969 terminal->set_terminal_window_hook = NULL; /* XXX vestigial? */
3970 terminal->read_socket_hook = ns_read_socket;
3971 terminal->frame_up_to_date_hook = ns_frame_up_to_date;
3972 terminal->mouse_position_hook = ns_mouse_position;
3973 terminal->frame_rehighlight_hook = ns_frame_rehighlight;
3974 terminal->frame_raise_lower_hook = ns_frame_raise_lower;
3976 terminal->fullscreen_hook = 0; /* see XTfullscreen_hook */
3978 terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
3979 terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
3980 terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
3981 terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
3983 terminal->delete_frame_hook = x_destroy_window;
3984 terminal->delete_terminal_hook = ns_delete_terminal;
3986 terminal->scroll_region_ok = 1;
3987 terminal->char_ins_del_ok = 1;
3988 terminal->line_ins_del_ok = 1;
3989 terminal->fast_clear_end_of_line = 1;
3990 terminal->memory_below_frame = 0;
3996 struct ns_display_info *
3997 ns_term_init (Lisp_Object display_name)
3998 /* --------------------------------------------------------------------------
3999 Start the Application and get things rolling.
4000 -------------------------------------------------------------------------- */
4002 struct terminal *terminal;
4003 struct ns_display_info *dpyinfo;
4004 static int ns_initialized = 0;
4007 NSTRACE (ns_term_init);
4009 /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4010 /*GSDebugAllocationActive (YES); */
4012 handling_signal = 0;
4014 if (!ns_initialized)
4017 Fset_input_interrupt_mode (Qnil);
4021 ns_pending_files = [[NSMutableArray alloc] init];
4022 ns_pending_service_names = [[NSMutableArray alloc] init];
4023 ns_pending_service_args = [[NSMutableArray alloc] init];
4025 /* Start app and create the main menu, window, view.
4026 Needs to be here because ns_initialize_display_info () uses AppKit classes.
4027 The view will then ask the NSApp to stop and return to Emacs. */
4028 [EmacsApp sharedApplication];
4031 [NSApp setDelegate: NSApp];
4033 /* debugging: log all notifications */
4034 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
4035 selector: @selector (logNotification:)
4036 name: nil object: nil]; */
4038 dpyinfo = xzalloc (sizeof *dpyinfo);
4040 ns_initialize_display_info (dpyinfo);
4041 terminal = ns_create_terminal (dpyinfo);
4043 terminal->kboard = xmalloc (sizeof *terminal->kboard);
4044 init_kboard (terminal->kboard);
4045 KVAR (terminal->kboard, Vwindow_system) = Qns;
4046 terminal->kboard->next_kboard = all_kboards;
4047 all_kboards = terminal->kboard;
4048 /* Don't let the initial kboard remain current longer than necessary.
4049 That would cause problems if a file loaded on startup tries to
4050 prompt in the mini-buffer. */
4051 if (current_kboard == initial_kboard)
4052 current_kboard = terminal->kboard;
4053 terminal->kboard->reference_count++;
4055 dpyinfo->next = x_display_list;
4056 x_display_list = dpyinfo;
4058 /* Put it on ns_display_name_list */
4059 ns_display_name_list = Fcons (Fcons (display_name, Qnil),
4060 ns_display_name_list);
4061 dpyinfo->name_list_element = XCAR (ns_display_name_list);
4063 terminal->name = xstrdup (SSDATA (display_name));
4067 if (!inhibit_x_resources)
4069 ns_default ("GSFontAntiAlias", &ns_antialias_text,
4072 /* this is a standard variable */
4073 ns_default ("AppleAntiAliasingThreshold", &tmp,
4074 make_float (10.0), make_float (6.0), YES, NO);
4075 ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4078 ns_selection_color = [[NSUserDefaults standardUserDefaults]
4079 stringForKey: @"AppleHighlightColor"];
4080 if (ns_selection_color == nil)
4081 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
4084 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4088 Lisp_Object color_file, color_map, color;
4092 color_file = Fexpand_file_name (build_string ("rgb.txt"),
4093 Fsymbol_value (intern ("data-directory")));
4094 if (NILP (Ffile_readable_p (color_file)))
4095 fatal ("Could not find %s.\n", SDATA (color_file));
4097 color_map = Fx_load_color_file (color_file);
4098 if (NILP (color_map))
4099 fatal ("Could not read %s.\n", SDATA (color_file));
4101 cl = [[NSColorList alloc] initWithName: @"Emacs"];
4102 for ( ; CONSP (color_map); color_map = XCDR (color_map))
4104 color = XCAR (color_map);
4105 name = SSDATA (XCAR (color));
4106 c = XINT (XCDR (color));
4108 [NSColor colorWithCalibratedRed: RED_FROM_ULONG (c) / 255.0
4109 green: GREEN_FROM_ULONG (c) / 255.0
4110 blue: BLUE_FROM_ULONG (c) / 255.0
4112 forKey: [NSString stringWithUTF8String: name]];
4114 [cl writeToFile: nil];
4119 #ifdef NS_IMPL_GNUSTEP
4120 Vwindow_system_version = build_string (gnustep_base_version);
4122 /*PSnextrelease (128, c); */
4123 char c[DBL_BUFSIZE_BOUND];
4124 int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4125 Vwindow_system_version = make_unibyte_string (c, len);
4129 delete_keyboard_wait_descriptor (0);
4131 ns_app_name = [[NSProcessInfo processInfo] processName];
4133 /* Set up OS X app menu */
4134 #ifdef NS_IMPL_COCOA
4138 /* set up the application menu */
4139 svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4140 [svcsMenu setAutoenablesItems: NO];
4141 appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4142 [appMenu setAutoenablesItems: NO];
4143 mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4144 dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4146 [appMenu insertItemWithTitle: @"About Emacs"
4147 action: @selector (orderFrontStandardAboutPanel:)
4150 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4151 [appMenu insertItemWithTitle: @"Preferences..."
4152 action: @selector (showPreferencesWindow:)
4155 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4156 item = [appMenu insertItemWithTitle: @"Services"
4157 action: @selector (menuDown:)
4160 [appMenu setSubmenu: svcsMenu forItem: item];
4161 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4162 [appMenu insertItemWithTitle: @"Hide Emacs"
4163 action: @selector (hide:)
4166 item = [appMenu insertItemWithTitle: @"Hide Others"
4167 action: @selector (hideOtherApplications:)
4170 [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4171 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4172 [appMenu insertItemWithTitle: @"Quit Emacs"
4173 action: @selector (terminate:)
4177 item = [mainMenu insertItemWithTitle: ns_app_name
4178 action: @selector (menuDown:)
4181 [mainMenu setSubmenu: appMenu forItem: item];
4182 [dockMenu insertItemWithTitle: @"New Frame"
4183 action: @selector (newFrame:)
4187 [NSApp setMainMenu: mainMenu];
4188 [NSApp setAppleMenu: appMenu];
4189 [NSApp setServicesMenu: svcsMenu];
4190 /* Needed at least on Cocoa, to get dock menu to show windows */
4191 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4193 [[NSNotificationCenter defaultCenter]
4194 addObserver: mainMenu
4195 selector: @selector (trackingNotification:)
4196 name: NSMenuDidBeginTrackingNotification object: mainMenu];
4197 [[NSNotificationCenter defaultCenter]
4198 addObserver: mainMenu
4199 selector: @selector (trackingNotification:)
4200 name: NSMenuDidEndTrackingNotification object: mainMenu];
4202 #endif /* MAC OS X menu setup */
4211 ns_term_shutdown (int sig)
4213 [[NSUserDefaults standardUserDefaults] synchronize];
4215 /* code not reached in emacs.c after this is called by shut_down_emacs: */
4216 if (STRINGP (Vauto_save_list_file_name))
4217 unlink (SSDATA (Vauto_save_list_file_name));
4219 if (sig == 0 || sig == SIGTERM)
4221 [NSApp terminate: NSApp];
4223 else // force a stack trace to happen
4230 /* ==========================================================================
4232 EmacsApp implementation
4234 ========================================================================== */
4237 @implementation EmacsApp
4239 - (void)logNotification: (NSNotification *)notification
4241 const char *name = [[notification name] UTF8String];
4242 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4243 && !strstr (name, "WindowNumber"))
4244 NSLog (@"notification: '%@'", [notification name]);
4248 - (void)sendEvent: (NSEvent *)theEvent
4249 /* --------------------------------------------------------------------------
4250 Called when NSApp is running for each event received. Used to stop
4251 the loop when we choose, since there's no way to just run one iteration.
4252 -------------------------------------------------------------------------- */
4254 int type = [theEvent type];
4255 NSWindow *window = [theEvent window];
4256 /* NSTRACE (sendEvent); */
4257 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4259 #ifdef NS_IMPL_COCOA
4260 if (type == NSApplicationDefined
4261 && [theEvent data2] == NSAPP_DATA2_RUNASSCRIPT)
4269 if (type == NSCursorUpdate && window == nil)
4271 fprintf (stderr, "Dropping external cursor update event.\n");
4275 #ifdef NS_IMPL_COCOA
4276 /* pass mouse down in resize handle and subsequent drags directly to
4277 EmacsWindow so we can generate continuous redisplays */
4280 if (type == NSLeftMouseDragged)
4282 [window mouseDragged: theEvent];
4285 else if (type == NSLeftMouseUp)
4287 [window mouseUp: theEvent];
4291 else if (type == NSLeftMouseDown)
4293 NSRect r = ns_resize_handle_rect (window);
4294 if (NSPointInRect ([theEvent locationInWindow], r))
4297 [window mouseDown: theEvent];
4303 if (type == NSApplicationDefined)
4305 /* Events posted by ns_send_appdefined interrupt the run loop here.
4306 But, if a modal window is up, an appdefined can still come through,
4307 (e.g., from a makeKeyWindow event) but stopping self also stops the
4308 modal loop. Just defer it until later. */
4309 if ([NSApp modalWindow] == nil)
4311 last_appdefined_event = theEvent;
4316 send_appdefined = YES;
4320 [super sendEvent: theEvent];
4324 - (void)showPreferencesWindow: (id)sender
4326 struct frame *emacsframe = SELECTED_FRAME ();
4327 NSEvent *theEvent = [NSApp currentEvent];
4331 emacs_event->kind = NS_NONKEY_EVENT;
4332 emacs_event->code = KEY_NS_SHOW_PREFS;
4333 emacs_event->modifiers = 0;
4334 EV_TRAILER (theEvent);
4338 - (void)newFrame: (id)sender
4340 struct frame *emacsframe = SELECTED_FRAME ();
4341 NSEvent *theEvent = [NSApp currentEvent];
4345 emacs_event->kind = NS_NONKEY_EVENT;
4346 emacs_event->code = KEY_NS_NEW_FRAME;
4347 emacs_event->modifiers = 0;
4348 EV_TRAILER (theEvent);
4352 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4353 - (BOOL) openFile: (NSString *)fileName
4355 struct frame *emacsframe = SELECTED_FRAME ();
4356 NSEvent *theEvent = [NSApp currentEvent];
4361 emacs_event->kind = NS_NONKEY_EVENT;
4362 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4363 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4364 ns_input_line = Qnil; /* can be start or cons start,end */
4365 emacs_event->modifiers =0;
4366 EV_TRAILER (theEvent);
4372 /* **************************************************************************
4374 EmacsApp delegate implementation
4376 ************************************************************************** */
4378 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4379 /* --------------------------------------------------------------------------
4380 When application is loaded, terminate event loop in ns_term_init
4381 -------------------------------------------------------------------------- */
4383 NSTRACE (applicationDidFinishLaunching);
4384 [NSApp setServicesProvider: NSApp];
4385 ns_send_appdefined (-2);
4389 /* Termination sequences:
4392 MenuBar | File | Exit:
4393 Select Quit from App menubar:
4395 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4398 Select Quit from Dock menu:
4401 Cancel -> Nothing else
4405 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4410 - (void) terminate: (id)sender
4412 struct frame *emacsframe = SELECTED_FRAME ();
4417 emacs_event->kind = NS_NONKEY_EVENT;
4418 emacs_event->code = KEY_NS_POWER_OFF;
4419 emacs_event->arg = Qt; /* mark as non-key event */
4420 EV_TRAILER ((id)nil);
4424 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4428 if (NILP (ns_confirm_quit)) // || ns_shutdown_properly --> TO DO
4429 return NSTerminateNow;
4431 ret = NSRunAlertPanel(ns_app_name,
4432 [NSString stringWithUTF8String:"Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?"],
4433 @"Save Buffers and Exit", @"Cancel", nil);
4435 if (ret == NSAlertDefaultReturn)
4436 return NSTerminateNow;
4437 else if (ret == NSAlertAlternateReturn)
4438 return NSTerminateCancel;
4439 return NSTerminateNow; /* just in case */
4443 /* Notification from the Workspace to open a file */
4444 - (BOOL)application: sender openFile: (NSString *)file
4446 [ns_pending_files addObject: file];
4451 /* Open a file as a temporary file */
4452 - (BOOL)application: sender openTempFile: (NSString *)file
4454 [ns_pending_files addObject: file];
4459 /* Notification from the Workspace to open a file noninteractively (?) */
4460 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4462 [ns_pending_files addObject: file];
4467 /* Notification from the Workspace to open multiple files */
4468 - (void)application: sender openFiles: (NSArray *)fileList
4470 NSEnumerator *files = [fileList objectEnumerator];
4472 while ((file = [files nextObject]) != nil)
4473 [ns_pending_files addObject: file];
4475 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4480 /* Handle dock menu requests. */
4481 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4487 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4488 - (void)applicationWillBecomeActive: (NSNotification *)notification
4490 //ns_app_active=YES;
4492 - (void)applicationDidBecomeActive: (NSNotification *)notification
4494 NSTRACE (applicationDidBecomeActive);
4496 //ns_app_active=YES;
4498 ns_update_auto_hide_menu_bar ();
4499 // No constraining takes place when the application is not active.
4500 ns_constrain_all_frames ();
4502 - (void)applicationDidResignActive: (NSNotification *)notification
4505 ns_send_appdefined (-1);
4510 /* ==========================================================================
4512 EmacsApp aux handlers for managing event loop
4514 ========================================================================== */
4517 - (void)timeout_handler: (NSTimer *)timedEntry
4518 /* --------------------------------------------------------------------------
4519 The timeout specified to ns_select has passed.
4520 -------------------------------------------------------------------------- */
4522 /*NSTRACE (timeout_handler); */
4523 ns_send_appdefined (-2);
4526 - (void)fd_handler: (NSTimer *) fdEntry
4527 /* --------------------------------------------------------------------------
4528 Check data waiting on file descriptors and terminate if so
4529 -------------------------------------------------------------------------- */
4532 struct timespec select_timeout;
4533 /* NSTRACE (fd_handler); */
4535 if (select_nfds == 0)
4538 memcpy (&t_readfds, &select_readfds, sizeof (fd_set));
4540 select_timeout.tv_sec = select_timeout.tv_nsec = 0;
4541 result = pselect (select_nfds, &t_readfds, NULL, NULL, &select_timeout, NULL);
4544 memcpy (&select_readfds, &t_readfds, sizeof (fd_set));
4545 ns_send_appdefined (result);
4551 /* ==========================================================================
4555 ========================================================================== */
4557 /* called from system: queue for next pass through event loop */
4558 - (void)requestService: (NSPasteboard *)pboard
4559 userData: (NSString *)userData
4560 error: (NSString **)error
4562 [ns_pending_service_names addObject: userData];
4563 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
4564 SSDATA (ns_string_from_pasteboard (pboard))]];
4568 /* called from ns_read_socket to clear queue */
4569 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
4571 struct frame *emacsframe = SELECTED_FRAME ();
4572 NSEvent *theEvent = [NSApp currentEvent];
4577 emacs_event->kind = NS_NONKEY_EVENT;
4578 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
4579 ns_input_spi_name = build_string ([name UTF8String]);
4580 ns_input_spi_arg = build_string ([arg UTF8String]);
4581 emacs_event->modifiers = EV_MODIFIERS (theEvent);
4582 EV_TRAILER (theEvent);
4592 /* ==========================================================================
4594 EmacsView implementation
4596 ========================================================================== */
4599 @implementation EmacsView
4601 /* needed to inform when window closed from LISP */
4602 - (void) setWindowClosing: (BOOL)closing
4604 windowClosing = closing;
4610 NSTRACE (EmacsView_dealloc);
4616 /* called on font panel selection */
4617 - (void)changeFont: (id)sender
4619 NSEvent *e =[[self window] currentEvent];
4620 struct face *face =FRAME_DEFAULT_FACE (emacsframe);
4624 NSTRACE (changeFont);
4628 if ((newFont = [sender convertFont:
4629 ((struct nsfont_info *)face->font)->nsfont]))
4631 SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
4633 emacs_event->kind = NS_NONKEY_EVENT;
4634 emacs_event->modifiers = 0;
4635 emacs_event->code = KEY_NS_CHANGE_FONT;
4637 size = [newFont pointSize];
4638 ns_input_fontsize = make_number (lrint (size));
4639 ns_input_font = build_string ([[newFont familyName] UTF8String]);
4645 - (BOOL)acceptsFirstResponder
4647 NSTRACE (acceptsFirstResponder);
4652 - (void)resetCursorRects
4654 NSRect visible = [self visibleRect];
4655 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
4656 NSTRACE (resetCursorRects);
4658 if (currentCursor == nil)
4659 currentCursor = [NSCursor arrowCursor];
4661 if (!NSIsEmptyRect (visible))
4662 [self addCursorRect: visible cursor: currentCursor];
4663 [currentCursor setOnMouseEntered: YES];
4668 /*****************************************************************************/
4669 /* Keyboard handling. */
4672 - (void)keyDown: (NSEvent *)theEvent
4674 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
4676 unsigned fnKeysym = 0;
4678 static NSMutableArray *nsEvArray;
4679 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
4680 static BOOL firstTime = YES;
4686 /* Rhapsody and OS X give up and down events for the arrow keys */
4687 if (ns_fake_keydown == YES)
4688 ns_fake_keydown = NO;
4689 else if ([theEvent type] != NSKeyDown)
4695 if (![[self window] isKeyWindow]
4696 && [[theEvent window] isKindOfClass: [EmacsWindow class]]
4697 /* we must avoid an infinite loop here. */
4698 && (EmacsView *)[[theEvent window] delegate] != self)
4700 /* XXX: There is an occasional condition in which, when Emacs display
4701 updates a different frame from the current one, and temporarily
4702 selects it, then processes some interrupt-driven input
4703 (dispnew.c:3878), OS will send the event to the correct NSWindow, but
4704 for some reason that window has its first responder set to the NSView
4705 most recently updated (I guess), which is not the correct one. */
4706 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
4710 if (nsEvArray == nil)
4711 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
4713 [NSCursor setHiddenUntilMouseMoves: YES];
4715 if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
4717 clear_mouse_face (hlinfo);
4718 hlinfo->mouse_face_hidden = 1;
4721 if (!processingCompose)
4723 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
4724 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
4725 /* (Carbon way: [theEvent keyCode]) */
4727 /* is it a "function key"? */
4728 fnKeysym = ns_convert_key (code);
4731 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
4732 because Emacs treats Delete and KP-Delete same (in simple.el). */
4733 if (fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
4734 code = 0xFF08; /* backspace */
4739 /* are there modifiers? */
4740 emacs_event->modifiers = 0;
4741 flags = [theEvent modifierFlags];
4743 if (flags & NSHelpKeyMask)
4744 emacs_event->modifiers |= hyper_modifier;
4746 if (flags & NSShiftKeyMask)
4747 emacs_event->modifiers |= shift_modifier;
4749 if ((flags & NSRightCommandKeyMask) == NSRightCommandKeyMask)
4750 emacs_event->modifiers |= parse_solitary_modifier
4751 (EQ (ns_right_command_modifier, Qleft)
4752 ? ns_command_modifier
4753 : ns_right_command_modifier);
4755 if ((flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask)
4757 emacs_event->modifiers |= parse_solitary_modifier
4758 (ns_command_modifier);
4760 /* if super (default), take input manager's word so things like
4761 dvorak / qwerty layout work */
4762 if (EQ (ns_command_modifier, Qsuper)
4764 && [[theEvent characters] length] != 0)
4766 /* XXX: the code we get will be unshifted, so if we have
4767 a shift modifier, must convert ourselves */
4768 if (!(flags & NSShiftKeyMask))
4769 code = [[theEvent characters] characterAtIndex: 0];
4771 /* this is ugly and also requires linking w/Carbon framework
4772 (for LMGetKbdType) so for now leave this rare (?) case
4773 undealt with.. in future look into CGEvent methods */
4776 long smv = GetScriptManagerVariable (smKeyScript);
4777 Handle uchrHandle = GetResource
4778 ('uchr', GetScriptVariable (smv, smScriptKeys));
4780 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
4781 [[theEvent characters] characterAtIndex: 0],
4782 kUCKeyActionDisplay,
4783 (flags & ~NSCommandKeyMask) >> 8,
4784 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
4785 &dummy, 1, &dummy, &code);
4792 if ((flags & NSRightControlKeyMask) == NSRightControlKeyMask)
4793 emacs_event->modifiers |= parse_solitary_modifier
4794 (EQ (ns_right_control_modifier, Qleft)
4795 ? ns_control_modifier
4796 : ns_right_control_modifier);
4798 if ((flags & NSLeftControlKeyMask) == NSLeftControlKeyMask)
4799 emacs_event->modifiers |= parse_solitary_modifier
4800 (ns_control_modifier);
4802 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
4803 emacs_event->modifiers |=
4804 parse_solitary_modifier (ns_function_modifier);
4806 left_is_none = NILP (ns_alternate_modifier)
4807 || EQ (ns_alternate_modifier, Qnone);
4809 if ((flags & NSRightAlternateKeyMask) == NSRightAlternateKeyMask)
4811 if ((NILP (ns_right_alternate_modifier)
4812 || EQ (ns_right_alternate_modifier, Qnone)
4813 || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
4815 { /* accept pre-interp alt comb */
4816 if ([[theEvent characters] length] > 0)
4817 code = [[theEvent characters] characterAtIndex: 0];
4818 /*HACK: clear lone shift modifier to stop next if from firing */
4819 if (emacs_event->modifiers == shift_modifier)
4820 emacs_event->modifiers = 0;
4823 emacs_event->modifiers |= parse_solitary_modifier
4824 (EQ (ns_right_alternate_modifier, Qleft)
4825 ? ns_alternate_modifier
4826 : ns_right_alternate_modifier);
4829 if ((flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask) /* default = meta */
4831 if (left_is_none && !fnKeysym)
4832 { /* accept pre-interp alt comb */
4833 if ([[theEvent characters] length] > 0)
4834 code = [[theEvent characters] characterAtIndex: 0];
4835 /*HACK: clear lone shift modifier to stop next if from firing */
4836 if (emacs_event->modifiers == shift_modifier)
4837 emacs_event->modifiers = 0;
4840 emacs_event->modifiers |=
4841 parse_solitary_modifier (ns_alternate_modifier);
4845 fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
4846 code, fnKeysym, flags, emacs_event->modifiers);
4848 /* if it was a function key or had modifiers, pass it directly to emacs */
4849 if (fnKeysym || (emacs_event->modifiers
4850 && (emacs_event->modifiers != shift_modifier)
4851 && [[theEvent charactersIgnoringModifiers] length] > 0))
4852 /*[[theEvent characters] length] */
4854 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4856 code |= (1<<28)|(3<<16);
4857 else if (code == 0x7f)
4858 code |= (1<<28)|(3<<16);
4860 emacs_event->kind = code > 0xFF
4861 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4863 emacs_event->code = code;
4864 EV_TRAILER (theEvent);
4870 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
4871 /* if we get here we should send the key for input manager processing */
4872 if (firstTime && [[NSInputManager currentInputManager]
4873 wantsToDelayTextChangeNotifications] == NO)
4875 "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
4878 if (NS_KEYLOG && !processingCompose)
4879 fprintf (stderr, "keyDown: Begin compose sequence.\n");
4881 processingCompose = YES;
4882 [nsEvArray addObject: theEvent];
4883 [self interpretKeyEvents: nsEvArray];
4884 [nsEvArray removeObject: theEvent];
4888 #ifdef NS_IMPL_COCOA
4889 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
4890 decided not to send key-down for.
4891 See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
4892 This only applies on Tiger and earlier.
4893 If it matches one of these, send it on to keyDown. */
4894 -(void)keyUp: (NSEvent *)theEvent
4896 int flags = [theEvent modifierFlags];
4897 int code = [theEvent keyCode];
4898 if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
4899 code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
4902 fprintf (stderr, "keyUp: passed test");
4903 ns_fake_keydown = YES;
4904 [self keyDown: theEvent];
4910 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
4913 /* <NSTextInput>: called when done composing;
4914 NOTE: also called when we delete over working text, followed immed.
4915 by doCommandBySelector: deleteBackward: */
4916 - (void)insertText: (id)aString
4919 int len = [(NSString *)aString length];
4923 NSLog (@"insertText '%@'\tlen = %d", aString, len);
4924 processingCompose = NO;
4929 /* first, clear any working text */
4930 if (workingText != nil)
4931 [self deleteWorkingText];
4933 /* now insert the string as keystrokes */
4934 for (i =0; i<len; i++)
4936 code = [aString characterAtIndex: i];
4937 /* TODO: still need this? */
4939 code = '~'; /* 0x7E */
4940 emacs_event->modifiers = 0;
4942 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4943 emacs_event->code = code;
4944 EV_TRAILER ((id)nil);
4949 /* <NSTextInput>: inserts display of composing characters */
4950 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
4952 NSString *str = [aString respondsToSelector: @selector (string)] ?
4953 [aString string] : aString;
4955 NSLog (@"setMarkedText '%@' len =%d range %d from %d", str, [str length],
4956 selRange.length, selRange.location);
4958 if (workingText != nil)
4959 [self deleteWorkingText];
4960 if ([str length] == 0)
4966 processingCompose = YES;
4967 workingText = [str copy];
4968 ns_working_text = build_string ([workingText UTF8String]);
4970 emacs_event->kind = NS_TEXT_EVENT;
4971 emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
4972 EV_TRAILER ((id)nil);
4976 /* delete display of composing characters [not in <NSTextInput>] */
4977 - (void)deleteWorkingText
4979 if (workingText == nil)
4982 NSLog(@"deleteWorkingText len =%d\n", [workingText length]);
4983 [workingText release];
4985 processingCompose = NO;
4990 emacs_event->kind = NS_TEXT_EVENT;
4991 emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
4992 EV_TRAILER ((id)nil);
4996 - (BOOL)hasMarkedText
4998 return workingText != nil;
5002 - (NSRange)markedRange
5004 NSRange rng = workingText != nil
5005 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
5007 NSLog (@"markedRange request");
5015 NSLog (@"unmark (accept) text");
5016 [self deleteWorkingText];
5017 processingCompose = NO;
5021 /* used to position char selection windows, etc. */
5022 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
5026 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
5028 NSLog (@"firstRectForCharRange request");
5030 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
5031 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
5032 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
5033 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
5034 +FRAME_LINE_HEIGHT (emacsframe));
5036 pt = [self convertPoint: pt toView: nil];
5037 pt = [[self window] convertBaseToScreen: pt];
5043 - (long)conversationIdentifier
5049 - (void)doCommandBySelector: (SEL)aSelector
5052 NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
5054 if (aSelector == @selector (deleteBackward:))
5056 /* happens when user backspaces over an ongoing composition:
5057 throw a 'delete' into the event queue */
5060 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5061 emacs_event->code = 0xFF08;
5062 EV_TRAILER ((id)nil);
5066 - (NSArray *)validAttributesForMarkedText
5068 static NSArray *arr = nil;
5069 if (arr == nil) arr = [NSArray new];
5070 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
5074 - (NSRange)selectedRange
5077 NSLog (@"selectedRange request");
5078 return NSMakeRange (NSNotFound, 0);
5081 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
5084 NSLog (@"characterIndexForPoint request");
5088 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
5090 static NSAttributedString *str = nil;
5091 if (str == nil) str = [NSAttributedString new];
5093 NSLog (@"attributedSubstringFromRange request");
5097 /* End <NSTextInput> impl. */
5098 /*****************************************************************************/
5101 /* This is what happens when the user presses a mouse button. */
5102 - (void)mouseDown: (NSEvent *)theEvent
5104 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5106 NSTRACE (mouseDown);
5108 [self deleteWorkingText];
5113 last_mouse_frame = emacsframe;
5114 /* appears to be needed to prevent spurious movement events generated on
5116 last_mouse_frame->mouse_moved = 0;
5118 if ([theEvent type] == NSScrollWheel)
5120 float delta = [theEvent deltaY];
5121 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
5124 emacs_event->kind = WHEEL_EVENT;
5125 emacs_event->code = 0;
5126 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
5127 ((delta > 0) ? up_modifier : down_modifier);
5131 emacs_event->kind = MOUSE_CLICK_EVENT;
5132 emacs_event->code = EV_BUTTON (theEvent);
5133 emacs_event->modifiers = EV_MODIFIERS (theEvent)
5134 | EV_UDMODIFIERS (theEvent);
5136 XSETINT (emacs_event->x, lrint (p.x));
5137 XSETINT (emacs_event->y, lrint (p.y));
5138 EV_TRAILER (theEvent);
5142 - (void)rightMouseDown: (NSEvent *)theEvent
5144 NSTRACE (rightMouseDown);
5145 [self mouseDown: theEvent];
5149 - (void)otherMouseDown: (NSEvent *)theEvent
5151 NSTRACE (otherMouseDown);
5152 [self mouseDown: theEvent];
5156 - (void)mouseUp: (NSEvent *)theEvent
5159 [self mouseDown: theEvent];
5163 - (void)rightMouseUp: (NSEvent *)theEvent
5165 NSTRACE (rightMouseUp);
5166 [self mouseDown: theEvent];
5170 - (void)otherMouseUp: (NSEvent *)theEvent
5172 NSTRACE (otherMouseUp);
5173 [self mouseDown: theEvent];
5177 - (void) scrollWheel: (NSEvent *)theEvent
5179 NSTRACE (scrollWheel);
5180 [self mouseDown: theEvent];
5184 /* Tell emacs the mouse has moved. */
5185 - (void)mouseMoved: (NSEvent *)e
5187 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5190 // NSTRACE (mouseMoved);
5192 last_mouse_movement_time = EV_TIMESTAMP (e);
5193 last_mouse_motion_position
5194 = [self convertPoint: [e locationInWindow] fromView: nil];
5196 /* update any mouse face */
5197 if (hlinfo->mouse_face_hidden)
5199 hlinfo->mouse_face_hidden = 0;
5200 clear_mouse_face (hlinfo);
5203 /* tooltip handling */
5204 previous_help_echo_string = help_echo_string;
5205 help_echo_string = Qnil;
5207 if (!note_mouse_movement (emacsframe, last_mouse_motion_position.x,
5208 last_mouse_motion_position.y))
5209 help_echo_string = previous_help_echo_string;
5211 XSETFRAME (frame, emacsframe);
5212 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
5214 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
5215 (note_mouse_highlight), which is called through the
5216 note_mouse_movement () call above */
5217 gen_help_event (help_echo_string, frame, help_echo_window,
5218 help_echo_object, help_echo_pos);
5222 help_echo_string = Qnil;
5223 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
5226 if (emacsframe->mouse_moved && send_appdefined)
5227 ns_send_appdefined (-1);
5231 - (void)mouseDragged: (NSEvent *)e
5233 NSTRACE (mouseDragged);
5234 [self mouseMoved: e];
5238 - (void)rightMouseDragged: (NSEvent *)e
5240 NSTRACE (rightMouseDragged);
5241 [self mouseMoved: e];
5245 - (void)otherMouseDragged: (NSEvent *)e
5247 NSTRACE (otherMouseDragged);
5248 [self mouseMoved: e];
5252 - (BOOL)windowShouldClose: (id)sender
5254 NSEvent *e =[[self window] currentEvent];
5256 NSTRACE (windowShouldClose);
5257 windowClosing = YES;
5260 emacs_event->kind = DELETE_WINDOW_EVENT;
5261 emacs_event->modifiers = 0;
5262 emacs_event->code = 0;
5264 /* Don't close this window, let this be done from lisp code. */
5269 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
5270 /* normalize frame to gridded text size */
5272 NSTRACE (windowWillResize);
5273 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
5275 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe,
5276 #ifdef NS_IMPL_GNUSTEP
5277 frameSize.width + 3);
5281 if (cols < MINWIDTH)
5284 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, frameSize.height
5285 #ifdef NS_IMPL_GNUSTEP
5286 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe) + 3
5287 - FRAME_TOOLBAR_HEIGHT (emacsframe));
5289 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5290 - FRAME_TOOLBAR_HEIGHT (emacsframe));
5292 if (rows < MINHEIGHT)
5294 #ifdef NS_IMPL_COCOA
5296 /* this sets window title to have size in it; the wm does this under GS */
5297 NSRect r = [[self window] frame];
5298 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
5309 NSWindow *window = [self window];
5312 const char *t = [[[self window] title] UTF8String];
5313 char *pos = strstr (t, " — ");
5316 old_title = xstrdup (t);
5318 size_title = xmalloc (strlen (old_title) + 40);
5319 esprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
5320 [window setTitle: [NSString stringWithUTF8String: size_title]];
5325 #endif /* NS_IMPL_COCOA */
5326 /*fprintf (stderr," ...size became %.0f x %.0f (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
5332 - (void)windowDidResize: (NSNotification *)notification
5334 #ifdef NS_IMPL_GNUSTEP
5335 NSWindow *theWindow = [notification object];
5337 /* in GNUstep, at least currently, it's possible to get a didResize
5338 without getting a willResize.. therefore we need to act as if we got
5339 the willResize now */
5340 NSSize sz = [theWindow frame].size;
5341 sz = [self windowWillResize: theWindow toSize: sz];
5342 #endif /* NS_IMPL_GNUSTEP */
5344 NSTRACE (windowDidResize);
5345 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
5347 #ifdef NS_IMPL_COCOA
5353 #endif /* NS_IMPL_COCOA */
5355 /* Avoid loop under GNUstep due to call at beginning of this function.
5356 (x_set_window_size causes a resize which causes
5357 a "windowDidResize" which calls x_set_window_size). */
5358 #ifndef NS_IMPL_GNUSTEP
5359 if (cols > 0 && rows > 0)
5362 x_set_window_size (emacsframe, 0, cols, rows);
5365 NSWindow *window = [self window];
5366 NSRect wr = [window frame];
5367 FRAME_PIXEL_WIDTH (emacsframe) = (int)wr.size.width
5368 - emacsframe->border_width;
5369 FRAME_PIXEL_HEIGHT (emacsframe) = (int)wr.size.height
5370 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5371 - FRAME_TOOLBAR_HEIGHT (emacsframe);
5372 change_frame_size (emacsframe, rows, cols, 0, 0, 1);
5373 SET_FRAME_GARBAGED (emacsframe);
5374 cancel_mouse_face (emacsframe);
5379 ns_send_appdefined (-1);
5383 - (void)windowDidBecomeKey: (NSNotification *)notification
5384 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5386 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5387 struct frame *old_focus = dpyinfo->x_focus_frame;
5389 NSTRACE (windowDidBecomeKey);
5391 if (emacsframe != old_focus)
5392 dpyinfo->x_focus_frame = emacsframe;
5394 ns_frame_rehighlight (emacsframe);
5398 emacs_event->kind = FOCUS_IN_EVENT;
5399 EV_TRAILER ((id)nil);
5404 - (void)windowDidResignKey: (NSNotification *)notification
5405 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5407 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5408 NSTRACE (windowDidResignKey);
5410 if (dpyinfo->x_focus_frame == emacsframe)
5411 dpyinfo->x_focus_frame = 0;
5413 ns_frame_rehighlight (emacsframe);
5415 /* FIXME: for some reason needed on second and subsequent clicks away
5416 from sole-frame Emacs to get hollow box to show */
5417 if (!windowClosing && [[self window] isVisible] == YES)
5419 x_update_cursor (emacsframe, 1);
5420 x_set_frame_alpha (emacsframe);
5425 [self deleteWorkingText];
5426 emacs_event->kind = FOCUS_IN_EVENT;
5427 EV_TRAILER ((id)nil);
5432 - (void)windowWillMiniaturize: sender
5434 NSTRACE (windowWillMiniaturize);
5450 - initFrameFromEmacs: (struct frame *)f
5455 NSButton *toggleButton;
5460 NSTRACE (initFrameFromEmacs);
5463 processingCompose = NO;
5464 scrollbarsNeedingUpdate = 0;
5466 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
5468 ns_userRect = NSMakeRect (0, 0, 0, 0);
5469 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
5470 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
5471 [self initWithFrame: r];
5472 [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
5474 FRAME_NS_VIEW (f) = self;
5478 win = [[EmacsWindow alloc]
5479 initWithContentRect: r
5480 styleMask: (NSResizableWindowMask |
5481 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
5482 NSTitledWindowMask |
5484 NSMiniaturizableWindowMask |
5485 NSClosableWindowMask)
5486 backing: NSBackingStoreBuffered
5490 f->border_width = wr.size.width - r.size.width;
5491 FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
5493 [win setAcceptsMouseMovedEvents: YES];
5494 [win setDelegate: self];
5495 [win useOptimizedDrawing: YES];
5497 sz.width = FRAME_COLUMN_WIDTH (f);
5498 sz.height = FRAME_LINE_HEIGHT (f);
5499 [win setResizeIncrements: sz];
5501 [[win contentView] addSubview: self];
5504 [self registerForDraggedTypes: ns_drag_types];
5507 name = [NSString stringWithUTF8String:
5508 NILP (tem) ? "Emacs" : SSDATA (tem)];
5509 [win setTitle: name];
5511 /* toolbar support */
5512 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
5513 [NSString stringWithFormat: @"Emacs Frame %d",
5515 [win setToolbar: toolbar];
5516 [toolbar setVisible: NO];
5517 #ifdef NS_IMPL_COCOA
5518 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
5519 [toggleButton setTarget: self];
5520 [toggleButton setAction: @selector (toggleToolbar: )];
5522 FRAME_TOOLBAR_HEIGHT (f) = 0;
5526 [win setMiniwindowTitle:
5527 [NSString stringWithUTF8String: SSDATA (tem)]];
5530 NSScreen *screen = [win screen];
5533 [win setFrameTopLeftPoint: NSMakePoint
5534 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
5535 IN_BOUND (-SCREENMAX,
5536 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
5539 [win makeFirstResponder: self];
5541 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5542 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
5543 [win setBackgroundColor: col];
5544 if ([col alphaComponent] != 1.0)
5545 [win setOpaque: NO];
5547 [self allocateGState];
5549 [NSApp registerServicesMenuSendTypes: ns_send_types
5557 - (void)windowDidMove: sender
5559 NSWindow *win = [self window];
5560 NSRect r = [win frame];
5561 NSArray *screens = [NSScreen screens];
5562 NSScreen *screen = [screens objectAtIndex: 0];
5564 NSTRACE (windowDidMove);
5566 if (!emacsframe->output_data.ns)
5570 emacsframe->left_pos = r.origin.x;
5571 emacsframe->top_pos =
5572 [screen frame].size.height - (r.origin.y + r.size.height);
5577 /* Called AFTER method below, but before our windowWillResize call there leads
5578 to windowDidResize -> x_set_window_size. Update emacs' notion of frame
5579 location so set_window_size moves the frame. */
5580 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
5582 emacsframe->output_data.ns->zooming = 1;
5587 /* Override to do something slightly nonstandard, but nice. First click on
5588 zoom button will zoom vertically. Second will zoom completely. Third
5589 returns to original. */
5590 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
5591 defaultFrame:(NSRect)defaultFrame
5593 NSRect result = [sender frame];
5595 NSTRACE (windowWillUseStandardFrame);
5597 if (abs (defaultFrame.size.height - result.size.height)
5598 > FRAME_LINE_HEIGHT (emacsframe))
5601 ns_userRect = result;
5602 result.size.height = defaultFrame.size.height;
5603 result.origin.y = defaultFrame.origin.y;
5607 if (abs (defaultFrame.size.width - result.size.width)
5608 > FRAME_COLUMN_WIDTH (emacsframe))
5609 result = defaultFrame; /* second click */
5613 result = ns_userRect.size.height ? ns_userRect : result;
5614 ns_userRect = NSMakeRect (0, 0, 0, 0);
5618 [self windowWillResize: sender toSize: result.size];
5623 - (void)windowDidDeminiaturize: sender
5625 NSTRACE (windowDidDeminiaturize);
5626 if (!emacsframe->output_data.ns)
5628 emacsframe->async_iconified = 0;
5629 emacsframe->async_visible = 1;
5630 windows_or_buffers_changed++;
5634 emacs_event->kind = ICONIFY_EVENT;
5635 EV_TRAILER ((id)nil);
5640 - (void)windowDidExpose: sender
5642 NSTRACE (windowDidExpose);
5643 if (!emacsframe->output_data.ns)
5645 emacsframe->async_visible = 1;
5646 SET_FRAME_GARBAGED (emacsframe);
5648 if (send_appdefined)
5649 ns_send_appdefined (-1);
5653 - (void)windowDidMiniaturize: sender
5655 NSTRACE (windowDidMiniaturize);
5656 if (!emacsframe->output_data.ns)
5659 emacsframe->async_iconified = 1;
5660 emacsframe->async_visible = 0;
5664 emacs_event->kind = ICONIFY_EVENT;
5665 EV_TRAILER ((id)nil);
5670 - (void)mouseEntered: (NSEvent *)theEvent
5672 NSTRACE (mouseEntered);
5673 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5677 - (void)mouseExited: (NSEvent *)theEvent
5679 Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
5681 NSTRACE (mouseExited);
5686 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5688 if (emacsframe == hlinfo->mouse_face_mouse_frame)
5690 clear_mouse_face (hlinfo);
5691 hlinfo->mouse_face_mouse_frame = 0;
5699 if (context_menu_value == -1)
5700 context_menu_value = [sender tag];
5703 NSInteger tag = [sender tag];
5704 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
5705 emacsframe->menu_bar_vector,
5709 ns_send_appdefined (-1);
5714 - (EmacsToolbar *)toolbar
5720 /* this gets called on toolbar button click */
5721 - toolbarClicked: (id)item
5724 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
5726 NSTRACE (toolbarClicked);
5731 /* send first event (for some reason two needed) */
5732 theEvent = [[self window] currentEvent];
5733 emacs_event->kind = TOOL_BAR_EVENT;
5734 XSETFRAME (emacs_event->arg, emacsframe);
5735 EV_TRAILER (theEvent);
5737 emacs_event->kind = TOOL_BAR_EVENT;
5738 /* XSETINT (emacs_event->code, 0); */
5739 emacs_event->arg = AREF (emacsframe->tool_bar_items,
5740 idx + TOOL_BAR_ITEM_KEY);
5741 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5742 EV_TRAILER (theEvent);
5747 - toggleToolbar: (id)sender
5752 emacs_event->kind = NS_NONKEY_EVENT;
5753 emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
5754 EV_TRAILER ((id)nil);
5759 - (void)drawRect: (NSRect)rect
5761 int x = NSMinX (rect), y = NSMinY (rect);
5762 int width = NSWidth (rect), height = NSHeight (rect);
5766 if (!emacsframe || !emacsframe->output_data.ns || ns_in_resize)
5769 ns_clear_frame_area (emacsframe, x, y, width, height);
5770 expose_frame (emacsframe, x, y, width, height);
5773 drawRect: may be called (at least in OS X 10.5) for invisible
5774 views as well for some reason. Thus, do not infer visibility
5777 emacsframe->async_visible = 1;
5778 emacsframe->async_iconified = 0;
5783 /* NSDraggingDestination protocol methods. Actually this is not really a
5784 protocol, but a category of Object. O well... */
5786 -(NSUInteger) draggingEntered: (id <NSDraggingInfo>) sender
5788 NSTRACE (draggingEntered);
5789 return NSDragOperationGeneric;
5793 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
5799 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
5804 NSEvent *theEvent = [[self window] currentEvent];
5807 NSTRACE (performDragOperation);
5812 position = [self convertPoint: [sender draggingLocation] fromView: nil];
5813 x = lrint (position.x); y = lrint (position.y);
5815 pb = [sender draggingPasteboard];
5816 type = [pb availableTypeFromArray: ns_drag_types];
5821 else if ([type isEqualToString: NSFilenamesPboardType])
5824 NSEnumerator *fenum;
5827 if (!(files = [pb propertyListForType: type]))
5830 fenum = [files objectEnumerator];
5831 while ( (file = [fenum nextObject]) )
5833 emacs_event->kind = NS_NONKEY_EVENT;
5834 emacs_event->code = KEY_NS_DRAG_FILE;
5835 XSETINT (emacs_event->x, x);
5836 XSETINT (emacs_event->y, y);
5837 ns_input_file = append2 (ns_input_file,
5838 build_string ([file UTF8String]));
5839 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5840 EV_TRAILER (theEvent);
5844 else if ([type isEqualToString: NSURLPboardType])
5849 if (!(fileURL = [NSURL URLFromPasteboard: pb]) ||
5850 [fileURL isFileURL] == NO)
5853 file = [fileURL path];
5854 emacs_event->kind = NS_NONKEY_EVENT;
5855 emacs_event->code = KEY_NS_DRAG_FILE;
5856 XSETINT (emacs_event->x, x);
5857 XSETINT (emacs_event->y, y);
5858 ns_input_file = append2 (ns_input_file, build_string ([file UTF8String]));
5859 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5860 EV_TRAILER (theEvent);
5863 else if ([type isEqualToString: NSStringPboardType]
5864 || [type isEqualToString: NSTabularTextPboardType])
5868 if (! (data = [pb stringForType: type]))
5871 emacs_event->kind = NS_NONKEY_EVENT;
5872 emacs_event->code = KEY_NS_DRAG_TEXT;
5873 XSETINT (emacs_event->x, x);
5874 XSETINT (emacs_event->y, y);
5875 ns_input_text = build_string ([data UTF8String]);
5876 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5877 EV_TRAILER (theEvent);
5880 else if ([type isEqualToString: NSColorPboardType])
5882 NSColor *c = [NSColor colorFromPasteboard: pb];
5883 emacs_event->kind = NS_NONKEY_EVENT;
5884 emacs_event->code = KEY_NS_DRAG_COLOR;
5885 XSETINT (emacs_event->x, x);
5886 XSETINT (emacs_event->y, y);
5887 ns_input_color = ns_color_to_lisp (c);
5888 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5889 EV_TRAILER (theEvent);
5892 else if ([type isEqualToString: NSFontPboardType])
5894 /* impl based on GNUstep NSTextView.m */
5895 NSData *data = [pb dataForType: NSFontPboardType];
5896 NSDictionary *dict = [NSUnarchiver unarchiveObjectWithData: data];
5897 NSFont *font = [dict objectForKey: NSFontAttributeName];
5903 emacs_event->kind = NS_NONKEY_EVENT;
5904 emacs_event->code = KEY_NS_CHANGE_FONT;
5905 XSETINT (emacs_event->x, x);
5906 XSETINT (emacs_event->y, y);
5907 ns_input_font = build_string ([[font fontName] UTF8String]);
5908 snprintf (fontSize, 10, "%f", [font pointSize]);
5909 ns_input_fontsize = build_string (fontSize);
5910 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5911 EV_TRAILER (theEvent);
5916 error ("Invalid data type in dragging pasteboard.");
5922 - (id) validRequestorForSendType: (NSString *)typeSent
5923 returnType: (NSString *)typeReturned
5925 NSTRACE (validRequestorForSendType);
5926 if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
5927 && typeReturned == nil)
5929 if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
5933 return [super validRequestorForSendType: typeSent
5934 returnType: typeReturned];
5938 /* The next two methods are part of NSServicesRequests informal protocol,
5939 supposedly called when a services menu item is chosen from this app.
5940 But this should not happen because we override the services menu with our
5941 own entries which call ns-perform-service.
5942 Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
5943 So let's at least stub them out until further investigation can be done. */
5945 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
5947 /* we could call ns_string_from_pasteboard(pboard) here but then it should
5948 be written into the buffer in place of the existing selection..
5949 ordinary service calls go through functions defined in ns-win.el */
5953 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
5955 NSArray *typesDeclared;
5958 /* We only support NSStringPboardType */
5959 if ([types containsObject:NSStringPboardType] == NO) {
5963 val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
5964 if (CONSP (val) && SYMBOLP (XCAR (val)))
5967 if (CONSP (val) && NILP (XCDR (val)))
5970 if (! STRINGP (val))
5973 typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
5974 [pb declareTypes:typesDeclared owner:nil];
5975 ns_string_to_pasteboard (pb, val);
5980 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
5981 (gives a miniaturized version of the window); currently we use the latter for
5982 frames whose active buffer doesn't correspond to any file
5983 (e.g., '*scratch*') */
5984 - setMiniwindowImage: (BOOL) setMini
5986 id image = [[self window] miniwindowImage];
5987 NSTRACE (setMiniwindowImage);
5989 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
5990 about "AppleDockIconEnabled" notwithstanding, however the set message
5991 below has its effect nonetheless. */
5992 if (image != emacsframe->output_data.ns->miniimage)
5994 if (image && [image isKindOfClass: [EmacsImage class]])
5996 [[self window] setMiniwindowImage:
5997 setMini ? emacsframe->output_data.ns->miniimage : nil];
6004 - (void) setRows: (int) r andColumns: (int) c
6010 @end /* EmacsView */
6014 /* ==========================================================================
6016 EmacsWindow implementation
6018 ========================================================================== */
6020 @implementation EmacsWindow
6022 /* If we have multiple monitors, one above the other, we don't want to
6023 restrict the height to just one monitor. So we override this. */
6024 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
6026 /* When making the frame visible for the first time or if there is just
6027 one screen, we want to constrain. Other times not. */
6028 NSUInteger nr_screens = [[NSScreen screens] count];
6029 struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
6030 NSTRACE (constrainFrameRect);
6032 if (nr_screens == 1)
6033 return [super constrainFrameRect:frameRect toScreen:screen];
6035 if (f->output_data.ns->dont_constrain
6036 || ns_menu_bar_should_be_hidden ())
6039 f->output_data.ns->dont_constrain = 1;
6040 return [super constrainFrameRect:frameRect toScreen:screen];
6044 /* called only on resize clicks by special case in EmacsApp-sendEvent */
6045 - (void)mouseDown: (NSEvent *)theEvent
6049 NSSize size = [[theEvent window] frame].size;
6050 grabOffset = [theEvent locationInWindow];
6051 grabOffset.x = size.width - grabOffset.x;
6054 [super mouseDown: theEvent];
6059 - (void)mouseUp: (NSEvent *)theEvent
6063 struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
6065 ns_set_name_as_filename (f);
6067 ns_send_appdefined (-1);
6070 [super mouseUp: theEvent];
6074 /* send resize events */
6075 - (void)mouseDragged: (NSEvent *)theEvent
6079 NSPoint p = [theEvent locationInWindow];
6080 NSSize size, vettedSize, origSize = [self frame].size;
6082 size.width = p.x + grabOffset.x;
6083 size.height = origSize.height - p.y + grabOffset.y;
6085 if (size.width == origSize.width && size.height == origSize.height)
6088 vettedSize = [[self delegate] windowWillResize: self toSize: size];
6089 [[NSNotificationCenter defaultCenter]
6090 postNotificationName: NSWindowDidResizeNotification
6094 [super mouseDragged: theEvent];
6097 @end /* EmacsWindow */
6100 /* ==========================================================================
6102 EmacsScroller implementation
6104 ========================================================================== */
6107 @implementation EmacsScroller
6109 /* for repeat button push */
6110 #define SCROLL_BAR_FIRST_DELAY 0.5
6111 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
6113 + (CGFloat) scrollerWidth
6115 /* TODO: if we want to allow variable widths, this is the place to do it,
6116 however neither GNUstep nor Cocoa support it very well */
6117 return [NSScroller scrollerWidth];
6121 - initFrame: (NSRect )r window: (Lisp_Object)nwin
6123 NSTRACE (EmacsScroller_initFrame);
6125 r.size.width = [EmacsScroller scrollerWidth];
6126 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
6127 [self setContinuous: YES];
6128 [self setEnabled: YES];
6130 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
6131 locked against the top and bottom edges, and right edge on OS X, where
6132 scrollers are on right. */
6133 #ifdef NS_IMPL_GNUSTEP
6134 [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
6136 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
6141 pixel_height = NSHeight (r);
6142 if (pixel_height == 0) pixel_height = 1;
6143 min_portion = 20 / pixel_height;
6145 frame = XFRAME (XWINDOW (win)->frame);
6146 if (FRAME_LIVE_P (frame))
6149 EmacsView *view = FRAME_NS_VIEW (frame);
6150 NSView *sview = [[view window] contentView];
6151 NSArray *subs = [sview subviews];
6153 /* disable optimization stopping redraw of other scrollbars */
6154 view->scrollbarsNeedingUpdate = 0;
6155 for (i =[subs count]-1; i >= 0; i--)
6156 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
6157 view->scrollbarsNeedingUpdate++;
6158 [sview addSubview: self];
6161 /* [self setFrame: r]; */
6167 - (void)setFrame: (NSRect)newRect
6169 NSTRACE (EmacsScroller_setFrame);
6171 pixel_height = NSHeight (newRect);
6172 if (pixel_height == 0) pixel_height = 1;
6173 min_portion = 20 / pixel_height;
6174 [super setFrame: newRect];
6176 /* UNBLOCK_INPUT; */
6182 NSTRACE (EmacsScroller_dealloc);
6184 XWINDOW (win)->vertical_scroll_bar = Qnil;
6212 /* ensure other scrollbar updates after deletion */
6213 view = (EmacsView *)FRAME_NS_VIEW (frame);
6215 view->scrollbarsNeedingUpdate++;
6216 [self removeFromSuperview];
6224 - (void)resetCursorRects
6226 NSRect visible = [self visibleRect];
6227 NSTRACE (resetCursorRects);
6229 if (!NSIsEmptyRect (visible))
6230 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
6231 [[NSCursor arrowCursor] setOnMouseEntered: YES];
6235 - (int) checkSamePosition: (int) position portion: (int) portion
6238 return em_position ==position && em_portion ==portion && em_whole ==whole
6239 && portion != whole; /* needed for resize empty buf */
6243 - setPosition: (int)position portion: (int)portion whole: (int)whole
6245 NSTRACE (setPosition);
6247 em_position = position;
6248 em_portion = portion;
6251 if (portion >= whole)
6253 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
6254 [self setKnobProportion: 1.0];
6255 [self setDoubleValue: 1.0];
6257 [self setFloatValue: 0.0 knobProportion: 1.0];
6263 portion = max ((float)whole*min_portion/pixel_height, portion);
6264 pos = (float)position / (whole - portion);
6265 por = (float)portion/whole;
6266 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
6267 [self setKnobProportion: por];
6268 [self setDoubleValue: pos];
6270 [self setFloatValue: pos knobProportion: por];
6276 /* FIXME: unused at moment (see ns_mouse_position) at the moment because
6277 drag events will go directly to the EmacsScroller. Leaving in for now. */
6278 -(void)getMouseMotionPart: (int *)part window: (Lisp_Object *)window
6279 x: (Lisp_Object *)x y: ( Lisp_Object *)y
6281 *part = last_hit_part;
6283 XSETINT (*y, pixel_height);
6284 if ([self floatValue] > 0.999)
6285 XSETINT (*x, pixel_height);
6287 XSETINT (*x, pixel_height * [self floatValue]);
6291 /* set up emacs_event */
6292 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
6297 emacs_event->part = last_hit_part;
6298 emacs_event->code = 0;
6299 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
6300 emacs_event->frame_or_window = win;
6301 emacs_event->timestamp = EV_TIMESTAMP (e);
6302 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
6303 emacs_event->arg = Qnil;
6304 XSETINT (emacs_event->x, loc * pixel_height);
6305 XSETINT (emacs_event->y, pixel_height-20);
6307 n_emacs_events_pending++;
6308 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
6309 EVENT_INIT (*emacs_event);
6310 ns_send_appdefined (-1);
6314 /* called manually thru timer to implement repeated button action w/hold-down */
6315 - repeatScroll: (NSTimer *)scrollEntry
6317 NSEvent *e = [[self window] currentEvent];
6318 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
6319 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
6321 /* clear timer if need be */
6322 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
6324 [scroll_repeat_entry invalidate];
6325 [scroll_repeat_entry release];
6326 scroll_repeat_entry = nil;
6332 = [[NSTimer scheduledTimerWithTimeInterval:
6333 SCROLL_BAR_CONTINUOUS_DELAY
6335 selector: @selector (repeatScroll:)
6341 [self sendScrollEventAtLoc: 0 fromEvent: e];
6346 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
6347 mouseDragged events without going into a modal loop. */
6348 - (void)mouseDown: (NSEvent *)e
6351 /* hitPart is only updated AFTER event is passed on */
6352 NSScrollerPart part = [self testPart: [e locationInWindow]];
6353 double inc = 0.0, loc, kloc, pos;
6356 NSTRACE (EmacsScroller_mouseDown);
6360 case NSScrollerDecrementPage:
6361 last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
6362 case NSScrollerIncrementPage:
6363 last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
6364 case NSScrollerDecrementLine:
6365 last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
6366 case NSScrollerIncrementLine:
6367 last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
6368 case NSScrollerKnob:
6369 last_hit_part = scroll_bar_handle; break;
6370 case NSScrollerKnobSlot: /* GNUstep-only */
6371 last_hit_part = scroll_bar_move_ratio; break;
6372 default: /* NSScrollerNoPart? */
6373 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
6380 pos = 0; /* ignored */
6382 /* set a timer to repeat, as we can't let superclass do this modally */
6384 = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
6386 selector: @selector (repeatScroll:)
6393 /* handle, or on GNUstep possibly slot */
6394 NSEvent *fake_event;
6396 /* compute float loc in slot and mouse offset on knob */
6397 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6399 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6405 else if (loc >= NSHeight (sr))
6407 loc = NSHeight (sr);
6415 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
6417 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
6419 last_mouse_offset = kloc;
6421 /* if knob, tell emacs a location offset by knob pos
6422 (to indicate top of handle) */
6423 if (part == NSScrollerKnob)
6424 pos = (loc - last_mouse_offset) / NSHeight (sr);
6426 /* else this is a slot click on GNUstep: go straight there */
6427 pos = loc / NSHeight (sr);
6429 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
6430 fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
6431 location: [e locationInWindow]
6432 modifierFlags: [e modifierFlags]
6433 timestamp: [e timestamp]
6434 windowNumber: [e windowNumber]
6435 context: [e context]
6436 eventNumber: [e eventNumber]
6437 clickCount: [e clickCount]
6438 pressure: [e pressure]];
6439 [super mouseUp: fake_event];
6442 if (part != NSScrollerKnob)
6443 [self sendScrollEventAtLoc: pos fromEvent: e];
6447 /* Called as we manually track scroller drags, rather than superclass. */
6448 - (void)mouseDragged: (NSEvent *)e
6454 NSTRACE (EmacsScroller_mouseDragged);
6456 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6458 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6465 else if (loc >= NSHeight (sr) + last_mouse_offset)
6467 loc = NSHeight (sr) + last_mouse_offset;
6471 pos = /*(edge ? loc :*/ (loc - last_mouse_offset) / NSHeight (sr);
6472 [self sendScrollEventAtLoc: pos fromEvent: e];
6476 - (void)mouseUp: (NSEvent *)e
6478 if (scroll_repeat_entry)
6480 [scroll_repeat_entry invalidate];
6481 [scroll_repeat_entry release];
6482 scroll_repeat_entry = nil;
6488 /* treat scrollwheel events in the bar as though they were in the main window */
6489 - (void) scrollWheel: (NSEvent *)theEvent
6491 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
6492 [view mouseDown: theEvent];
6495 @end /* EmacsScroller */
6500 /* ==========================================================================
6502 Font-related functions; these used to be in nsfaces.m
6504 ========================================================================== */
6508 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
6510 struct font *font = XFONT_OBJECT (font_object);
6513 fontset = fontset_from_font (font_object);
6514 FRAME_FONTSET (f) = fontset;
6516 if (FRAME_FONT (f) == font)
6517 /* This font is already set in frame F. There's nothing more to
6521 FRAME_FONT (f) = font;
6523 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
6524 FRAME_COLUMN_WIDTH (f) = font->average_width;
6525 FRAME_SPACE_WIDTH (f) = font->space_width;
6526 FRAME_LINE_HEIGHT (f) = font->height;
6528 compute_fringe_widths (f, 1);
6530 /* Compute the scroll bar width in character columns. */
6531 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
6533 int wid = FRAME_COLUMN_WIDTH (f);
6534 FRAME_CONFIG_SCROLL_BAR_COLS (f)
6535 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
6539 int wid = FRAME_COLUMN_WIDTH (f);
6540 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
6543 /* Now make the frame display the given font. */
6544 if (FRAME_NS_WINDOW (f) != 0)
6545 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
6551 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
6552 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
6556 ns_xlfd_to_fontname (const char *xlfd)
6557 /* --------------------------------------------------------------------------
6558 Convert an X font name (XLFD) to an NS font name.
6559 Only family is used.
6560 The string returned is temporarily allocated.
6561 -------------------------------------------------------------------------- */
6563 char *name = xmalloc (180);
6567 if (!strncmp (xlfd, "--", 2))
6568 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
6570 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
6572 /* stopgap for malformed XLFD input */
6573 if (strlen (name) == 0)
6574 strcpy (name, "Monaco");
6576 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
6577 also uppercase after '-' or ' ' */
6578 name[0] = toupper (name[0]);
6579 for (len =strlen (name), i =0; i<len; i++)
6585 name[i+1] = toupper (name[i+1]);
6587 else if (name[i] == '_')
6591 name[i+1] = toupper (name[i+1]);
6594 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
6595 ret = [[NSString stringWithUTF8String: name] UTF8String];
6602 syms_of_nsterm (void)
6604 NSTRACE (syms_of_nsterm);
6606 ns_antialias_threshold = 10.0;
6608 /* from 23+ we need to tell emacs what modifiers there are.. */
6609 DEFSYM (Qmodifier_value, "modifier-value");
6610 DEFSYM (Qalt, "alt");
6611 DEFSYM (Qhyper, "hyper");
6612 DEFSYM (Qmeta, "meta");
6613 DEFSYM (Qsuper, "super");
6614 DEFSYM (Qcontrol, "control");
6615 DEFSYM (Qnone, "none");
6616 DEFSYM (QUTF8_STRING, "UTF8_STRING");
6618 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
6619 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
6620 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
6621 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
6622 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
6624 DEFVAR_LISP ("ns-input-file", ns_input_file,
6625 "The file specified in the last NS event.");
6626 ns_input_file =Qnil;
6628 DEFVAR_LISP ("ns-input-text", ns_input_text,
6629 "The data received in the last NS text drag event.");
6630 ns_input_text =Qnil;
6632 DEFVAR_LISP ("ns-working-text", ns_working_text,
6633 "String for visualizing working composition sequence.");
6634 ns_working_text =Qnil;
6636 DEFVAR_LISP ("ns-input-font", ns_input_font,
6637 "The font specified in the last NS event.");
6638 ns_input_font =Qnil;
6640 DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
6641 "The fontsize specified in the last NS event.");
6642 ns_input_fontsize =Qnil;
6644 DEFVAR_LISP ("ns-input-line", ns_input_line,
6645 "The line specified in the last NS event.");
6646 ns_input_line =Qnil;
6648 DEFVAR_LISP ("ns-input-color", ns_input_color,
6649 "The color specified in the last NS event.");
6650 ns_input_color =Qnil;
6652 DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
6653 "The service name specified in the last NS event.");
6654 ns_input_spi_name =Qnil;
6656 DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
6657 "The service argument specified in the last NS event.");
6658 ns_input_spi_arg =Qnil;
6660 DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
6661 "This variable describes the behavior of the alternate or option key.\n\
6662 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6663 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6664 at all, allowing it to be used at a lower level for accented character entry.");
6665 ns_alternate_modifier = Qmeta;
6667 DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
6668 "This variable describes the behavior of the right alternate or option key.\n\
6669 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6670 Set to left means be the same key as `ns-alternate-modifier'.\n\
6671 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6672 at all, allowing it to be used at a lower level for accented character entry.");
6673 ns_right_alternate_modifier = Qleft;
6675 DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
6676 "This variable describes the behavior of the command key.\n\
6677 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6678 ns_command_modifier = Qsuper;
6680 DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
6681 "This variable describes the behavior of the right command key.\n\
6682 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6683 Set to left means be the same key as `ns-command-modifier'.\n\
6684 Set to none means that the command / option key is not interpreted by Emacs\n\
6685 at all, allowing it to be used at a lower level for accented character entry.");
6686 ns_right_command_modifier = Qleft;
6688 DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
6689 "This variable describes the behavior of the control key.\n\
6690 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6691 ns_control_modifier = Qcontrol;
6693 DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
6694 "This variable describes the behavior of the right control key.\n\
6695 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6696 Set to left means be the same key as `ns-control-modifier'.\n\
6697 Set to none means that the control / option key is not interpreted by Emacs\n\
6698 at all, allowing it to be used at a lower level for accented character entry.");
6699 ns_right_control_modifier = Qleft;
6701 DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
6702 "This variable describes the behavior of the function key (on laptops).\n\
6703 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6704 Set to none means that the function key is not interpreted by Emacs at all,\n\
6705 allowing it to be used at a lower level for accented character entry.");
6706 ns_function_modifier = Qnone;
6708 DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
6709 "Non-nil (the default) means to render text antialiased. Only has an effect on OS X Panther and above.");
6710 ns_antialias_text = Qt;
6712 DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
6713 "Whether to confirm application quit using dialog.");
6714 ns_confirm_quit = Qnil;
6716 staticpro (&ns_display_name_list);
6717 ns_display_name_list = Qnil;
6719 staticpro (&last_mouse_motion_frame);
6720 last_mouse_motion_frame = Qnil;
6722 DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
6723 doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
6724 Only works on OSX 10.6 or later. */);
6725 ns_auto_hide_menu_bar = Qnil;
6727 /* TODO: move to common code */
6728 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
6729 doc: /* Which toolkit scroll bars Emacs uses, if any.
6730 A value of nil means Emacs doesn't use toolkit scroll bars.
6731 With the X Window system, the value is a symbol describing the
6732 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
6733 With MS Windows or Nextstep, the value is t. */);
6734 Vx_toolkit_scroll_bars = Qt;
6736 DEFVAR_BOOL ("x-use-underline-position-properties",
6737 x_use_underline_position_properties,
6738 doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
6739 A value of nil means ignore them. If you encounter fonts with bogus
6740 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
6741 to 4.1, set this to nil. */);
6742 x_use_underline_position_properties = 0;
6744 DEFVAR_BOOL ("x-underline-at-descent-line",
6745 x_underline_at_descent_line,
6746 doc: /* Non-nil means to draw the underline at the same place as the descent line.
6747 A value of nil means to draw the underline according to the value of the
6748 variable `x-use-underline-position-properties', which is usually at the
6749 baseline level. The default value is nil. */);
6750 x_underline_at_descent_line = 0;
6752 /* Tell emacs about this window system. */
6753 Fprovide (intern ("ns"), Qnil);