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>
40 #include <c-strcase.h>
48 #include "blockinput.h"
49 #include "sysselect.h"
52 #include "character.h"
54 #include "composite.h"
57 #include "termhooks.h"
67 int term_trace_num = 0;
68 #define NSTRACE(x) fprintf (stderr, "%s:%d: [%d] " #x "\n", \
69 __FILE__, __LINE__, ++term_trace_num)
74 #if defined (NS_IMPL_COCOA) && \
75 MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
79 extern NSString *NSMenuDidBeginTrackingNotification;
81 /* ==========================================================================
85 ========================================================================== */
87 /* Convert a symbol indexed with an NSxxx value to a value as defined
88 in keyboard.c (lispy_function_key). I hope this is a correct way
90 static unsigned convert_ns_to_X_keysym[] =
92 NSHomeFunctionKey, 0x50,
93 NSLeftArrowFunctionKey, 0x51,
94 NSUpArrowFunctionKey, 0x52,
95 NSRightArrowFunctionKey, 0x53,
96 NSDownArrowFunctionKey, 0x54,
97 NSPageUpFunctionKey, 0x55,
98 NSPageDownFunctionKey, 0x56,
99 NSEndFunctionKey, 0x57,
100 NSBeginFunctionKey, 0x58,
101 NSSelectFunctionKey, 0x60,
102 NSPrintFunctionKey, 0x61,
103 NSExecuteFunctionKey, 0x62,
104 NSInsertFunctionKey, 0x63,
105 NSUndoFunctionKey, 0x65,
106 NSRedoFunctionKey, 0x66,
107 NSMenuFunctionKey, 0x67,
108 NSFindFunctionKey, 0x68,
109 NSHelpFunctionKey, 0x6A,
110 NSBreakFunctionKey, 0x6B,
112 NSF1FunctionKey, 0xBE,
113 NSF2FunctionKey, 0xBF,
114 NSF3FunctionKey, 0xC0,
115 NSF4FunctionKey, 0xC1,
116 NSF5FunctionKey, 0xC2,
117 NSF6FunctionKey, 0xC3,
118 NSF7FunctionKey, 0xC4,
119 NSF8FunctionKey, 0xC5,
120 NSF9FunctionKey, 0xC6,
121 NSF10FunctionKey, 0xC7,
122 NSF11FunctionKey, 0xC8,
123 NSF12FunctionKey, 0xC9,
124 NSF13FunctionKey, 0xCA,
125 NSF14FunctionKey, 0xCB,
126 NSF15FunctionKey, 0xCC,
127 NSF16FunctionKey, 0xCD,
128 NSF17FunctionKey, 0xCE,
129 NSF18FunctionKey, 0xCF,
130 NSF19FunctionKey, 0xD0,
131 NSF20FunctionKey, 0xD1,
132 NSF21FunctionKey, 0xD2,
133 NSF22FunctionKey, 0xD3,
134 NSF23FunctionKey, 0xD4,
135 NSF24FunctionKey, 0xD5,
137 NSBackspaceCharacter, 0x08, /* 8: Not on some KBs. */
138 NSDeleteCharacter, 0xFF, /* 127: Big 'delete' key upper right. */
139 NSDeleteFunctionKey, 0x9F, /* 63272: Del forw key off main array. */
141 NSTabCharacter, 0x09,
142 0x19, 0x09, /* left tab->regular since pass shift */
143 NSCarriageReturnCharacter, 0x0D,
144 NSNewlineCharacter, 0x0D,
145 NSEnterCharacter, 0x8D,
147 0x1B, 0x1B /* escape */
150 static Lisp_Object Qmodifier_value;
151 Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper;
152 extern Lisp_Object Qcursor_color, Qcursor_type, Qns, Qleft;
154 static Lisp_Object QUTF8_STRING;
156 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
157 the maximum font size to NOT antialias. On GNUstep there is currently
158 no way to control this behavior. */
159 float ns_antialias_threshold;
161 /* Used to pick up AppleHighlightColor on OS X */
162 NSString *ns_selection_color;
164 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
165 NSString *ns_app_name = @"Emacs"; /* default changed later */
167 /* Display variables */
168 struct ns_display_info *x_display_list; /* Chain of existing displays */
169 Lisp_Object ns_display_name_list;
170 long context_menu_value = 0;
173 NSPoint last_mouse_motion_position;
174 static NSRect last_mouse_glyph;
175 static Time last_mouse_movement_time = 0;
176 static Lisp_Object last_mouse_motion_frame;
177 static EmacsScroller *last_mouse_scroll_bar = nil;
178 static struct frame *ns_updating_frame;
179 static NSView *focus_view = NULL;
180 static int ns_window_num = 0;
181 #ifdef NS_IMPL_GNUSTEP
184 static BOOL gsaved = NO;
185 static BOOL ns_fake_keydown = NO;
186 int ns_tmp_flags; /* FIXME */
187 struct nsfont_info *ns_tmp_font; /* FIXME */
188 static BOOL ns_menu_bar_is_hidden = NO;
189 /*static int debug_lock = 0; */
192 static BOOL send_appdefined = YES;
193 static NSEvent *last_appdefined_event = 0;
194 static NSTimer *timed_entry = 0;
195 static NSTimer *scroll_repeat_entry = nil;
196 static fd_set select_readfds, select_writefds;
197 enum { SELECT_HAVE_READ = 1, SELECT_HAVE_WRITE = 2, SELECT_HAVE_TMO = 4 };
198 static int select_nfds = 0, select_valid = 0;
199 static EMACS_TIME select_timeout = { 0, 0 };
200 static int selfds[2] = { -1, -1 };
201 static pthread_mutex_t select_mutex;
202 static int apploopnr = 0;
203 static NSAutoreleasePool *outerpool;
204 static struct input_event *emacs_event = NULL;
205 static struct input_event *q_event_ptr = NULL;
206 static int n_emacs_events_pending = 0;
207 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
208 *ns_pending_service_args;
209 static BOOL ns_do_open_file = NO;
212 struct input_event *q;
218 /* Convert modifiers in a NeXTstep event to emacs style modifiers. */
219 #define NS_FUNCTION_KEY_MASK 0x800000
220 #define NSLeftControlKeyMask (0x000001 | NSControlKeyMask)
221 #define NSRightControlKeyMask (0x002000 | NSControlKeyMask)
222 #define NSLeftCommandKeyMask (0x000008 | NSCommandKeyMask)
223 #define NSRightCommandKeyMask (0x000010 | NSCommandKeyMask)
224 #define NSLeftAlternateKeyMask (0x000020 | NSAlternateKeyMask)
225 #define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
226 #define EV_MODIFIERS(e) \
227 ((([e modifierFlags] & NSHelpKeyMask) ? \
228 hyper_modifier : 0) \
229 | (!EQ (ns_right_alternate_modifier, Qleft) && \
230 (([e modifierFlags] & NSRightAlternateKeyMask) \
231 == NSRightAlternateKeyMask) ? \
232 parse_solitary_modifier (ns_right_alternate_modifier) : 0) \
233 | (([e modifierFlags] & NSAlternateKeyMask) ? \
234 parse_solitary_modifier (ns_alternate_modifier) : 0) \
235 | (([e modifierFlags] & NSShiftKeyMask) ? \
236 shift_modifier : 0) \
237 | (!EQ (ns_right_control_modifier, Qleft) && \
238 (([e modifierFlags] & NSRightControlKeyMask) \
239 == NSRightControlKeyMask) ? \
240 parse_solitary_modifier (ns_right_control_modifier) : 0) \
241 | (([e modifierFlags] & NSControlKeyMask) ? \
242 parse_solitary_modifier (ns_control_modifier) : 0) \
243 | (([e modifierFlags] & NS_FUNCTION_KEY_MASK) ? \
244 parse_solitary_modifier (ns_function_modifier) : 0) \
245 | (!EQ (ns_right_command_modifier, Qleft) && \
246 (([e modifierFlags] & NSRightCommandKeyMask) \
247 == NSRightCommandKeyMask) ? \
248 parse_solitary_modifier (ns_right_command_modifier) : 0) \
249 | (([e modifierFlags] & NSCommandKeyMask) ? \
250 parse_solitary_modifier (ns_command_modifier):0))
252 #define EV_UDMODIFIERS(e) \
253 ((([e type] == NSLeftMouseDown) ? down_modifier : 0) \
254 | (([e type] == NSRightMouseDown) ? down_modifier : 0) \
255 | (([e type] == NSOtherMouseDown) ? down_modifier : 0) \
256 | (([e type] == NSLeftMouseDragged) ? down_modifier : 0) \
257 | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
258 | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
259 | (([e type] == NSLeftMouseUp) ? up_modifier : 0) \
260 | (([e type] == NSRightMouseUp) ? up_modifier : 0) \
261 | (([e type] == NSOtherMouseUp) ? up_modifier : 0))
263 #define EV_BUTTON(e) \
264 ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 : \
265 (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
266 [e buttonNumber] - 1)
268 /* Convert the time field to a timestamp in milliseconds. */
269 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
271 /* This is a piece of code which is common to all the event handling
272 methods. Maybe it should even be a function. */
273 #define EV_TRAILER(e) \
275 XSETFRAME (emacs_event->frame_or_window, emacsframe); \
276 if (e) emacs_event->timestamp = EV_TIMESTAMP (e); \
279 n_emacs_events_pending++; \
280 kbd_buffer_store_event_hold (emacs_event, q_event_ptr); \
283 hold_event (emacs_event); \
284 EVENT_INIT (*emacs_event); \
285 ns_send_appdefined (-1); \
288 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
290 /* TODO: get rid of need for these forward declarations */
291 static void ns_condemn_scroll_bars (struct frame *f);
292 static void ns_judge_scroll_bars (struct frame *f);
293 void x_set_frame_alpha (struct frame *f);
296 /* ==========================================================================
300 ========================================================================== */
303 hold_event (struct input_event *event)
305 if (hold_event_q.nr == hold_event_q.cap)
307 if (hold_event_q.cap == 0) hold_event_q.cap = 10;
308 else hold_event_q.cap *= 2;
309 hold_event_q.q = (struct input_event *)
310 xrealloc (hold_event_q.q, hold_event_q.cap * sizeof (*hold_event_q.q));
313 hold_event_q.q[hold_event_q.nr++] = *event;
317 append2 (Lisp_Object list, Lisp_Object item)
318 /* --------------------------------------------------------------------------
319 Utility to append to a list
320 -------------------------------------------------------------------------- */
322 Lisp_Object array[2];
324 array[1] = Fcons (item, Qnil);
325 return Fnconc (2, &array[0]);
330 ns_etc_directory (void)
331 /* If running as a self-contained app bundle, return as a string the
332 filename of the etc directory, if present; else nil. */
334 NSBundle *bundle = [NSBundle mainBundle];
335 NSString *resourceDir = [bundle resourcePath];
336 NSString *resourcePath;
337 NSFileManager *fileManager = [NSFileManager defaultManager];
340 resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
341 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
343 if (isDir) return [resourcePath UTF8String];
351 /* If running as a self-contained app bundle, return as a path string
352 the filenames of the libexec and bin directories, ie libexec:bin.
353 Otherwise, return nil.
354 Normally, Emacs does not add its own bin/ directory to the PATH.
355 However, a self-contained NS build has a different layout, with
356 bin/ and libexec/ subdirectories in the directory that contains
358 We put libexec first, because init_callproc_1 uses the first
359 element to initialize exec-directory. An alternative would be
360 for init_callproc to check for invocation-directory/libexec.
363 NSBundle *bundle = [NSBundle mainBundle];
364 NSString *resourceDir = [bundle resourcePath];
365 NSString *binDir = [bundle bundlePath];
366 NSString *resourcePath, *resourcePaths;
368 NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
369 NSFileManager *fileManager = [NSFileManager defaultManager];
371 NSEnumerator *pathEnum;
374 range = [resourceDir rangeOfString: @"Contents"];
375 if (range.location != NSNotFound)
377 binDir = [binDir stringByAppendingPathComponent: @"Contents"];
379 binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
383 paths = [binDir stringsByAppendingPaths:
384 [NSArray arrayWithObjects: @"libexec", @"bin", nil]];
385 pathEnum = [paths objectEnumerator];
388 while ((resourcePath = [pathEnum nextObject]))
390 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
393 if ([resourcePaths length] > 0)
395 = [resourcePaths stringByAppendingString: pathSeparator];
397 = [resourcePaths stringByAppendingString: resourcePath];
400 if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
408 /* If running as a self-contained app bundle, return as a path string
409 the filenames of the site-lisp, lisp and leim directories.
410 Ie, site-lisp:lisp:leim. Otherwise, return nil. */
412 NSBundle *bundle = [NSBundle mainBundle];
413 NSString *resourceDir = [bundle resourcePath];
414 NSString *resourcePath, *resourcePaths;
415 NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
416 NSFileManager *fileManager = [NSFileManager defaultManager];
418 NSArray *paths = [resourceDir stringsByAppendingPaths:
419 [NSArray arrayWithObjects:
420 @"site-lisp", @"lisp", @"leim", nil]];
421 NSEnumerator *pathEnum = [paths objectEnumerator];
424 /* Hack to skip site-lisp. */
425 if (no_site_lisp) resourcePath = [pathEnum nextObject];
427 while ((resourcePath = [pathEnum nextObject]))
429 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
432 if ([resourcePaths length] > 0)
434 = [resourcePaths stringByAppendingString: pathSeparator];
436 = [resourcePaths stringByAppendingString: resourcePath];
439 if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
445 ns_timeout (int usecs)
446 /* --------------------------------------------------------------------------
447 Blocking timer utility used by ns_ring_bell
448 -------------------------------------------------------------------------- */
450 EMACS_TIME wakeup = add_emacs_time (current_emacs_time (),
451 make_emacs_time (0, usecs * 1000));
453 /* Keep waiting until past the time wakeup. */
456 EMACS_TIME timeout, now = current_emacs_time ();
457 if (EMACS_TIME_LE (wakeup, now))
459 timeout = sub_emacs_time (wakeup, now);
461 /* Try to wait that long--but we might wake up sooner. */
462 pselect (0, NULL, NULL, NULL, &timeout, NULL);
468 ns_release_object (void *obj)
469 /* --------------------------------------------------------------------------
470 Release an object (callable from C)
471 -------------------------------------------------------------------------- */
478 ns_retain_object (void *obj)
479 /* --------------------------------------------------------------------------
480 Retain an object (callable from C)
481 -------------------------------------------------------------------------- */
488 ns_alloc_autorelease_pool (void)
489 /* --------------------------------------------------------------------------
490 Allocate a pool for temporary objects (callable from C)
491 -------------------------------------------------------------------------- */
493 return [[NSAutoreleasePool alloc] init];
498 ns_release_autorelease_pool (void *pool)
499 /* --------------------------------------------------------------------------
500 Free a pool and temporary objects it refers to (callable from C)
501 -------------------------------------------------------------------------- */
503 ns_release_object (pool);
508 /* ==========================================================================
510 Focus (clipping) and screen update
512 ========================================================================== */
515 // Window constraining
516 // -------------------
518 // To ensure that the windows are not placed under the menu bar, they
519 // are typically moved by the call-back constrainFrameRect. However,
520 // by overriding it, it's possible to inhibit this, leaving the window
521 // in it's original position.
523 // It's possible to hide the menu bar. However, technically, it's only
524 // possible to hide it when the application is active. To ensure that
525 // this work properly, the menu bar and window constraining are
526 // deferred until the application becomes active.
528 // Even though it's not possible to manually move a window above the
529 // top of the screen, it is allowed if it's done programmatically,
530 // when the menu is hidden. This allows the editable area to cover the
531 // full screen height.
536 // Use the following extra files:
539 // ;; Hide menu and place frame slightly above the top of the screen.
540 // (setq ns-auto-hide-menu-bar t)
541 // (set-frame-position (selected-frame) 0 -20)
545 // emacs -Q -l init.el
547 // Result: No menu bar, and the title bar should be above the screen.
553 // Result: Menu bar visible, frame placed immediately below the menu.
557 ns_constrain_all_frames (void)
559 Lisp_Object tail, frame;
561 FOR_EACH_FRAME (tail, frame)
563 struct frame *f = XFRAME (frame);
566 NSView *view = FRAME_NS_VIEW (f);
567 /* This no-op will trigger the default window placing
568 * constraint system. */
569 f->output_data.ns->dont_constrain = 0;
570 [[view window] setFrameOrigin:[[view window] frame].origin];
576 /* True, if the menu bar should be hidden. */
579 ns_menu_bar_should_be_hidden (void)
581 return !NILP (ns_auto_hide_menu_bar)
582 && [NSApp respondsToSelector:@selector(setPresentationOptions:)];
586 /* Show or hide the menu bar, based on user setting. */
589 ns_update_auto_hide_menu_bar (void)
592 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
595 NSTRACE (ns_update_auto_hide_menu_bar);
599 && [NSApp respondsToSelector:@selector(setPresentationOptions:)])
601 // Note, "setPresentationOptions" triggers an error unless the
602 // application is active.
603 BOOL menu_bar_should_be_hidden = ns_menu_bar_should_be_hidden ();
605 if (menu_bar_should_be_hidden != ns_menu_bar_is_hidden)
607 NSApplicationPresentationOptions options
608 = NSApplicationPresentationAutoHideDock;
610 if (menu_bar_should_be_hidden)
611 options |= NSApplicationPresentationAutoHideMenuBar;
613 [NSApp setPresentationOptions: options];
615 ns_menu_bar_is_hidden = menu_bar_should_be_hidden;
617 if (!ns_menu_bar_is_hidden)
619 ns_constrain_all_frames ();
631 ns_update_begin (struct frame *f)
632 /* --------------------------------------------------------------------------
633 Prepare for a grouped sequence of drawing calls
634 external (RIF) call; whole frame, called before update_window_begin
635 -------------------------------------------------------------------------- */
637 NSView *view = FRAME_NS_VIEW (f);
638 NSRect r = [view frame];
640 NSTRACE (ns_update_begin);
642 ns_update_auto_hide_menu_bar ();
644 ns_updating_frame = f;
647 /* drawRect may have been called for say the minibuffer, and then clip path
648 is for the minibuffer. But the display engine may draw more because
649 we have set the frame as garbaged. So reset clip path to the whole
651 bp = [[NSBezierPath bezierPathWithRect: r] retain];
655 #ifdef NS_IMPL_GNUSTEP
656 uRect = NSMakeRect (0, 0, 0, 0);
662 ns_update_window_begin (struct window *w)
663 /* --------------------------------------------------------------------------
664 Prepare for a grouped sequence of drawing calls
665 external (RIF) call; for one window, called after update_begin
666 -------------------------------------------------------------------------- */
668 struct frame *f = XFRAME (WINDOW_FRAME (w));
669 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
670 NSTRACE (ns_update_window_begin);
672 set_output_cursor (&w->cursor);
676 if (f == hlinfo->mouse_face_mouse_frame)
678 /* Don't do highlighting for mouse motion during the update. */
679 hlinfo->mouse_face_defer = 1;
681 /* If the frame needs to be redrawn,
682 simply forget about any prior mouse highlighting. */
683 if (FRAME_GARBAGED_P (f))
684 hlinfo->mouse_face_window = Qnil;
686 /* (further code for mouse faces ifdef'd out in other terms elided) */
694 ns_update_window_end (struct window *w, int cursor_on_p,
695 int mouse_face_overwritten_p)
696 /* --------------------------------------------------------------------------
697 Finished a grouped sequence of drawing calls
698 external (RIF) call; for one window called before update_end
699 -------------------------------------------------------------------------- */
701 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (XFRAME (w->frame));
703 /* note: this fn is nearly identical in all terms */
704 if (!w->pseudo_window_p)
709 display_and_set_cursor (w, 1,
710 output_cursor.hpos, output_cursor.vpos,
711 output_cursor.x, output_cursor.y);
713 if (draw_window_fringes (w, 1))
714 x_draw_vertical_border (w);
719 /* If a row with mouse-face was overwritten, arrange for
720 frame_up_to_date to redisplay the mouse highlight. */
721 if (mouse_face_overwritten_p)
723 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
724 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
725 hlinfo->mouse_face_window = Qnil;
728 updated_window = NULL;
729 NSTRACE (update_window_end);
734 ns_update_end (struct frame *f)
735 /* --------------------------------------------------------------------------
736 Finished a grouped sequence of drawing calls
737 external (RIF) call; for whole frame, called after update_window_end
738 -------------------------------------------------------------------------- */
740 NSView *view = FRAME_NS_VIEW (f);
742 /* if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
743 MOUSE_HL_INFO (f)->mouse_face_defer = 0;
747 #ifdef NS_IMPL_GNUSTEP
748 /* trigger flush only in the rectangle we tracked as being drawn */
749 [view unlockFocusNeedsFlush: NO];
750 /*fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", uRect.origin.x, uRect.origin.y, uRect.size.width, uRect.size.height); */
751 [view lockFocusInRect: uRect];
755 [[view window] flushWindow];
758 ns_updating_frame = NULL;
759 NSTRACE (ns_update_end);
764 ns_flush (struct frame *f)
765 /* --------------------------------------------------------------------------
767 NS impl is no-op since currently we flush in ns_update_end and elsewhere
768 -------------------------------------------------------------------------- */
775 ns_focus (struct frame *f, NSRect *r, int n)
776 /* --------------------------------------------------------------------------
777 Internal: Focus on given frame. During small local updates this is used to
778 draw, however during large updates, ns_update_begin and ns_update_end are
779 called to wrap the whole thing, in which case these calls are stubbed out.
780 Except, on GNUstep, we accumulate the rectangle being drawn into, because
781 the back end won't do this automatically, and will just end up flushing
783 -------------------------------------------------------------------------- */
785 // NSTRACE (ns_focus);
786 #ifdef NS_IMPL_GNUSTEP
789 u = NSUnionRect (r[0], r[1]);
794 fprintf (stderr, "focus: %d", c++);
795 if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
796 fprintf (stderr, "\n"); */
798 if (f != ns_updating_frame)
800 NSView *view = FRAME_NS_VIEW (f);
801 if (view != focus_view)
803 if (focus_view != NULL)
805 [focus_view unlockFocus];
806 [[focus_view window] flushWindow];
811 #ifdef NS_IMPL_GNUSTEP
812 r ? [view lockFocusInRect: u] : [view lockFocus];
817 /*if (view) debug_lock++; */
819 #ifdef NS_IMPL_GNUSTEP
822 /* more than one rect being drawn into */
825 [view unlockFocus]; /* add prev rect to redraw list */
826 [view lockFocusInRect: u]; /* focus for draw in new rect */
831 #ifdef NS_IMPL_GNUSTEP
834 /* in batch mode, but in GNUstep must still track rectangles explicitly */
835 uRect = (r ? NSUnionRect (uRect, u) : [FRAME_NS_VIEW (f) visibleRect]);
842 [[NSGraphicsContext currentContext] saveGraphicsState];
844 NSRectClipList (r, 2);
853 ns_unfocus (struct frame *f)
854 /* --------------------------------------------------------------------------
855 Internal: Remove focus on given frame
856 -------------------------------------------------------------------------- */
858 // NSTRACE (ns_unfocus);
862 [[NSGraphicsContext currentContext] restoreGraphicsState];
866 if (f != ns_updating_frame)
868 if (focus_view != NULL)
870 [focus_view unlockFocus];
871 [[focus_view window] flushWindow];
880 ns_clip_to_row (struct window *w, struct glyph_row *row, int area, BOOL gc)
881 /* --------------------------------------------------------------------------
882 Internal (but parallels other terms): Focus drawing on given row
883 -------------------------------------------------------------------------- */
885 struct frame *f = XFRAME (WINDOW_FRAME (w));
887 int window_x, window_y, window_width;
889 window_box (w, area, &window_x, &window_y, &window_width, 0);
891 clip_rect.origin.x = window_x;
892 clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
893 clip_rect.origin.y = max (clip_rect.origin.y, window_y);
894 clip_rect.size.width = window_width;
895 clip_rect.size.height = row->visible_height;
897 ns_focus (f, &clip_rect, 1);
902 ns_ring_bell (struct frame *f)
903 /* --------------------------------------------------------------------------
905 -------------------------------------------------------------------------- */
907 NSTRACE (ns_ring_bell);
910 NSAutoreleasePool *pool;
911 struct frame *frame = SELECTED_FRAME ();
915 pool = [[NSAutoreleasePool alloc] init];
917 view = FRAME_NS_VIEW (frame);
921 NSPoint dim = NSMakePoint (128, 128);
924 r.origin.x += (r.size.width - dim.x) / 2;
925 r.origin.y += (r.size.height - dim.y) / 2;
926 r.size.width = dim.x;
927 r.size.height = dim.y;
928 surr = NSInsetRect (r, -2, -2);
929 ns_focus (frame, &surr, 1);
930 [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
931 [ns_lookup_indexed_color (NS_FACE_FOREGROUND
932 (FRAME_DEFAULT_FACE (frame)), frame) set];
934 [[view window] flushWindow];
936 [[view window] restoreCachedImage];
937 [[view window] flushWindow];
951 ns_reset_terminal_modes (struct terminal *terminal)
952 /* Externally called as hook */
954 NSTRACE (ns_reset_terminal_modes);
959 ns_set_terminal_modes (struct terminal *terminal)
960 /* Externally called as hook */
962 NSTRACE (ns_set_terminal_modes);
967 /* ==========================================================================
969 Frame / window manager related functions
971 ========================================================================== */
975 ns_raise_frame (struct frame *f)
976 /* --------------------------------------------------------------------------
977 Bring window to foreground and make it active
978 -------------------------------------------------------------------------- */
980 NSView *view = FRAME_NS_VIEW (f);
983 FRAME_SAMPLE_VISIBILITY (f);
984 if (FRAME_VISIBLE_P (f))
986 [[view window] makeKeyAndOrderFront: NSApp];
993 ns_lower_frame (struct frame *f)
994 /* --------------------------------------------------------------------------
996 -------------------------------------------------------------------------- */
998 NSView *view = FRAME_NS_VIEW (f);
1001 [[view window] orderBack: NSApp];
1007 ns_frame_raise_lower (struct frame *f, int raise)
1008 /* --------------------------------------------------------------------------
1010 -------------------------------------------------------------------------- */
1012 NSTRACE (ns_frame_raise_lower);
1022 ns_frame_rehighlight (struct frame *frame)
1023 /* --------------------------------------------------------------------------
1024 External (hook): called on things like window switching within frame
1025 -------------------------------------------------------------------------- */
1027 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
1028 struct frame *old_highlight = dpyinfo->x_highlight_frame;
1030 NSTRACE (ns_frame_rehighlight);
1031 if (dpyinfo->x_focus_frame)
1033 dpyinfo->x_highlight_frame
1034 = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1035 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1036 : dpyinfo->x_focus_frame);
1037 if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
1039 fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
1040 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
1044 dpyinfo->x_highlight_frame = 0;
1046 if (dpyinfo->x_highlight_frame &&
1047 dpyinfo->x_highlight_frame != old_highlight)
1051 x_update_cursor (old_highlight, 1);
1052 x_set_frame_alpha (old_highlight);
1054 if (dpyinfo->x_highlight_frame)
1056 x_update_cursor (dpyinfo->x_highlight_frame, 1);
1057 x_set_frame_alpha (dpyinfo->x_highlight_frame);
1064 x_make_frame_visible (struct frame *f)
1065 /* --------------------------------------------------------------------------
1066 External: Show the window (X11 semantics)
1067 -------------------------------------------------------------------------- */
1069 NSTRACE (x_make_frame_visible);
1070 /* XXX: at some points in past this was not needed, as the only place that
1071 called this (frame.c:Fraise_frame ()) also called raise_lower;
1072 if this ends up the case again, comment this out again. */
1073 if (!FRAME_VISIBLE_P (f))
1075 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1076 f->async_visible = 1;
1080 /* Making a new frame from a fullscreen frame will make the new frame
1081 fullscreen also. So skip handleFS as this will print an error. */
1082 if (f->want_fullscreen == FULLSCREEN_BOTH
1083 && ([[view window] styleMask] & NSFullScreenWindowMask) != 0)
1086 if (f->want_fullscreen != FULLSCREEN_NONE)
1097 x_make_frame_invisible (struct frame *f)
1098 /* --------------------------------------------------------------------------
1099 External: Hide the window (X11 semantics)
1100 -------------------------------------------------------------------------- */
1102 NSView * view = FRAME_NS_VIEW (f);
1103 NSTRACE (x_make_frame_invisible);
1105 [[view window] orderOut: NSApp];
1106 f->async_visible = 0;
1107 f->async_iconified = 0;
1112 x_iconify_frame (struct frame *f)
1113 /* --------------------------------------------------------------------------
1114 External: Iconify window
1115 -------------------------------------------------------------------------- */
1117 NSView * view = FRAME_NS_VIEW (f);
1118 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1119 NSTRACE (x_iconify_frame);
1122 if (dpyinfo->x_highlight_frame == f)
1123 dpyinfo->x_highlight_frame = 0;
1125 if ([[view window] windowNumber] <= 0)
1127 /* the window is still deferred. Make it very small, bring it
1128 on screen and order it out. */
1129 NSRect s = { { 100, 100}, {0, 0} };
1131 t = [[view window] frame];
1132 [[view window] setFrame: s display: NO];
1133 [[view window] orderBack: NSApp];
1134 [[view window] orderOut: NSApp];
1135 [[view window] setFrame: t display: NO];
1137 [[view window] miniaturize: NSApp];
1140 /* Free X resources of frame F. */
1143 x_free_frame_resources (struct frame *f)
1145 NSView *view = FRAME_NS_VIEW (f);
1146 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1147 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1148 NSTRACE (x_free_frame_resources);
1151 [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1155 free_frame_menubar (f);
1157 if (FRAME_FACE_CACHE (f))
1158 free_frame_faces (f);
1160 if (f == dpyinfo->x_focus_frame)
1161 dpyinfo->x_focus_frame = 0;
1162 if (f == dpyinfo->x_highlight_frame)
1163 dpyinfo->x_highlight_frame = 0;
1164 if (f == hlinfo->mouse_face_mouse_frame)
1166 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
1167 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
1168 hlinfo->mouse_face_window = Qnil;
1169 hlinfo->mouse_face_deferred_gc = 0;
1170 hlinfo->mouse_face_mouse_frame = 0;
1173 if (f->output_data.ns->miniimage != nil)
1174 [f->output_data.ns->miniimage release];
1176 [[view window] close];
1179 xfree (f->output_data.ns);
1185 x_destroy_window (struct frame *f)
1186 /* --------------------------------------------------------------------------
1187 External: Delete the window
1188 -------------------------------------------------------------------------- */
1190 NSTRACE (x_destroy_window);
1192 x_free_frame_resources (f);
1198 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1199 /* --------------------------------------------------------------------------
1200 External: Position the window
1201 -------------------------------------------------------------------------- */
1203 NSView *view = FRAME_NS_VIEW (f);
1204 NSArray *screens = [NSScreen screens];
1205 NSScreen *fscreen = [screens objectAtIndex: 0];
1206 NSScreen *screen = [[view window] screen];
1208 NSTRACE (x_set_offset);
1215 if (view != nil && screen && fscreen)
1217 f->left_pos = f->size_hint_flags & XNegative
1218 ? [screen visibleFrame].size.width + f->left_pos - FRAME_PIXEL_WIDTH (f)
1220 /* We use visibleFrame here to take menu bar into account.
1221 Ideally we should also adjust left/top with visibleFrame.origin. */
1223 f->top_pos = f->size_hint_flags & YNegative
1224 ? ([screen visibleFrame].size.height + f->top_pos
1225 - FRAME_PIXEL_HEIGHT (f) - FRAME_NS_TITLEBAR_HEIGHT (f)
1226 - FRAME_TOOLBAR_HEIGHT (f))
1228 #ifdef NS_IMPL_GNUSTEP
1229 if (f->left_pos < 100)
1230 f->left_pos = 100; /* don't overlap menu */
1232 /* Constrain the setFrameTopLeftPoint so we don't move behind the
1234 f->output_data.ns->dont_constrain = 0;
1235 [[view window] setFrameTopLeftPoint:
1236 NSMakePoint (SCREENMAXBOUND (f->left_pos),
1237 SCREENMAXBOUND ([fscreen frame].size.height
1238 - NS_TOP_POS (f)))];
1239 f->size_hint_flags &= ~(XNegative|YNegative);
1247 x_set_window_size (struct frame *f, int change_grav, int cols, int rows)
1248 /* --------------------------------------------------------------------------
1249 Adjust window pixel size based on given character grid size
1250 Impl is a bit more complex than other terms, need to do some
1252 -------------------------------------------------------------------------- */
1254 EmacsView *view = FRAME_NS_VIEW (f);
1255 NSWindow *window = [view window];
1256 NSRect wr = [window frame];
1257 int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1258 int pixelwidth, pixelheight;
1260 NSTRACE (x_set_window_size);
1265 /*fprintf (stderr, "\tsetWindowSize: %d x %d, font size %d x %d\n", cols, rows, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f)); */
1269 check_frame_size (f, &rows, &cols);
1271 f->scroll_bar_actual_width = NS_SCROLL_BAR_WIDTH (f);
1272 compute_fringe_widths (f, 0);
1274 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols);
1275 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
1277 /* If we have a toolbar, take its height into account. */
1279 /* NOTE: previously this would generate wrong result if toolbar not
1280 yet displayed and fixing toolbar_height=32 helped, but
1281 now (200903) seems no longer needed */
1282 FRAME_TOOLBAR_HEIGHT (f) =
1283 NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1284 - FRAME_NS_TITLEBAR_HEIGHT (f);
1286 FRAME_TOOLBAR_HEIGHT (f) = 0;
1288 wr.size.width = pixelwidth + f->border_width;
1289 wr.size.height = pixelheight + FRAME_NS_TITLEBAR_HEIGHT (f)
1290 + FRAME_TOOLBAR_HEIGHT (f);
1292 /* Do not try to constrain to this screen. We may have multiple
1293 screens, and want Emacs to span those. Constraining to screen
1294 prevents that, and that is not nice to the user. */
1295 if (f->output_data.ns->zooming)
1296 f->output_data.ns->zooming = 0;
1298 wr.origin.y += FRAME_PIXEL_HEIGHT (f) - pixelheight;
1300 [view setRows: rows andColumns: cols];
1301 [window setFrame: wr display: YES];
1303 /*fprintf (stderr, "\tx_set_window_size %d, %d\t%d, %d\n", cols, rows, pixelwidth, pixelheight); */
1305 /* This is a trick to compensate for Emacs' managing the scrollbar area
1306 as a fixed number of standard character columns. Instead of leaving
1307 blank space for the extra, we chopped it off above. Now for
1308 left-hand scrollbars, we shift all rendering to the left by the
1309 difference between the real width and Emacs' imagined one. For
1310 right-hand bars, don't worry about it since the extra is never used.
1311 (Obviously doesn't work for vertically split windows tho..) */
1313 NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1314 ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1315 - NS_SCROLL_BAR_WIDTH (f), 0)
1316 : NSMakePoint (0, 0);
1317 [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1318 [view setBoundsOrigin: origin];
1321 change_frame_size (f, rows, cols, 0, 1, 0); /* pretend, delay, safe */
1322 FRAME_PIXEL_WIDTH (f) = pixelwidth;
1323 FRAME_PIXEL_HEIGHT (f) = pixelheight;
1324 /* SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */
1326 mark_window_cursors_off (XWINDOW (f->root_window));
1327 cancel_mouse_face (f);
1334 ns_fullscreen_hook (FRAME_PTR f)
1336 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1338 if (! f->async_visible) return;
1339 #ifndef NEW_STYLE_FS
1340 if (f->want_fullscreen == FULLSCREEN_BOTH)
1342 /* Old style fs don't initiate correctly if created from
1343 init/default-frame alist, so use a timer (not nice...).
1345 [NSTimer scheduledTimerWithTimeInterval: 0.5 target: view
1346 selector: @selector (handleFS)
1347 userInfo: nil repeats: NO];
1357 /* ==========================================================================
1361 ========================================================================== */
1365 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1367 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1368 if (idx < 1 || idx >= color_table->avail)
1370 return color_table->colors[idx];
1375 ns_index_color (NSColor *color, struct frame *f)
1377 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1381 if (!color_table->colors)
1383 color_table->size = NS_COLOR_CAPACITY;
1384 color_table->avail = 1; /* skip idx=0 as marker */
1385 color_table->colors = xmalloc (color_table->size * sizeof (NSColor *));
1386 color_table->colors[0] = nil;
1387 color_table->empty_indices = [[NSMutableSet alloc] init];
1390 /* do we already have this color ? */
1391 for (i = 1; i < color_table->avail; i++)
1392 if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1395 if ([color_table->empty_indices count] > 0)
1397 NSNumber *index = [color_table->empty_indices anyObject];
1398 [color_table->empty_indices removeObject: index];
1399 idx = [index unsignedLongValue];
1403 if (color_table->avail == color_table->size)
1404 color_table->colors =
1405 xpalloc (color_table->colors, &color_table->size, 1,
1406 min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1407 idx = color_table->avail++;
1410 color_table->colors[idx] = color;
1412 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1418 ns_free_indexed_color (unsigned long idx, struct frame *f)
1420 struct ns_color_table *color_table;
1427 color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1429 if (idx <= 0 || idx >= color_table->size) {
1430 message1 ("ns_free_indexed_color: Color index out of range.\n");
1434 index = [NSNumber numberWithUnsignedInt: idx];
1435 if ([color_table->empty_indices containsObject: index]) {
1436 message1 ("ns_free_indexed_color: attempt to free already freed color.\n");
1440 color = color_table->colors[idx];
1442 color_table->colors[idx] = nil;
1443 [color_table->empty_indices addObject: index];
1444 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1449 ns_get_color (const char *name, NSColor **col)
1450 /* --------------------------------------------------------------------------
1452 -------------------------------------------------------------------------- */
1453 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1454 X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1455 See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1458 static char hex[20];
1460 float r = -1.0, g, b;
1461 NSString *nsname = [NSString stringWithUTF8String: name];
1463 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1466 if ([nsname isEqualToString: @"ns_selection_color"])
1468 nsname = ns_selection_color;
1469 name = [ns_selection_color UTF8String];
1472 /* First, check for some sort of numeric specification. */
1475 if (name[0] == '0' || name[0] == '1' || name[0] == '.') /* RGB decimal */
1477 NSScanner *scanner = [NSScanner scannerWithString: nsname];
1478 [scanner scanFloat: &r];
1479 [scanner scanFloat: &g];
1480 [scanner scanFloat: &b];
1482 else if (!strncmp(name, "rgb:", 4)) /* A newer X11 format -- rgb:r/g/b */
1483 scaling = (snprintf (hex, sizeof hex, "%s", name + 4) - 2) / 3;
1484 else if (name[0] == '#') /* An old X11 format; convert to newer */
1486 int len = (strlen(name) - 1);
1487 int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1489 scaling = strlen(name+start) / 3;
1490 for (i = 0; i < 3; i++)
1491 sprintf (hex + i * (scaling + 1), "%.*s/", scaling,
1492 name + start + i * scaling);
1493 hex[3 * (scaling + 1) - 1] = '\0';
1499 float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1500 if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1510 *col = [NSColor colorWithCalibratedRed: r green: g blue: b alpha: 1.0];
1515 /* Otherwise, color is expected to be from a list */
1517 NSEnumerator *lenum, *cenum;
1521 #ifdef NS_IMPL_GNUSTEP
1522 /* XXX: who is wrong, the requestor or the implementation? */
1523 if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1525 nsname = @"highlightColor";
1528 lenum = [[NSColorList availableColorLists] objectEnumerator];
1529 while ( (clist = [lenum nextObject]) && new == nil)
1531 cenum = [[clist allKeys] objectEnumerator];
1532 while ( (name = [cenum nextObject]) && new == nil )
1534 if ([name compare: nsname
1535 options: NSCaseInsensitiveSearch] == NSOrderedSame )
1536 new = [clist colorWithKey: name];
1542 *col = [new colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1549 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1550 /* --------------------------------------------------------------------------
1551 Convert a Lisp string object to a NS color
1552 -------------------------------------------------------------------------- */
1554 NSTRACE (ns_lisp_to_color);
1555 if (STRINGP (color))
1556 return ns_get_color (SSDATA (color), col);
1557 else if (SYMBOLP (color))
1558 return ns_get_color (SSDATA (SYMBOL_NAME (color)), col);
1564 ns_color_to_lisp (NSColor *col)
1565 /* --------------------------------------------------------------------------
1566 Convert a color to a lisp string with the RGB equivalent
1567 -------------------------------------------------------------------------- */
1569 CGFloat red, green, blue, alpha, gray;
1572 NSTRACE (ns_color_to_lisp);
1575 if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1577 if ((str =[[col colorNameComponent] UTF8String]))
1580 return build_string ((char *)str);
1583 [[col colorUsingColorSpaceName: NSCalibratedRGBColorSpace]
1584 getRed: &red green: &green blue: &blue alpha: &alpha];
1585 if (red ==green && red ==blue)
1587 [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1588 getWhite: &gray alpha: &alpha];
1589 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1590 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1592 return build_string (buf);
1595 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1596 lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1599 return build_string (buf);
1604 ns_query_color(void *col, XColor *color_def, int setPixel)
1605 /* --------------------------------------------------------------------------
1606 Get ARGB values out of NSColor col and put them into color_def.
1607 If setPixel, set the pixel to a concatenated version.
1608 and set color_def pixel to the resulting index.
1609 -------------------------------------------------------------------------- */
1613 [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1614 color_def->red = r * 65535;
1615 color_def->green = g * 65535;
1616 color_def->blue = b * 65535;
1618 if (setPixel == YES)
1620 = ARGB_TO_ULONG((int)(a*255),
1621 (int)(r*255), (int)(g*255), (int)(b*255));
1626 ns_defined_color (struct frame *f,
1631 /* --------------------------------------------------------------------------
1632 Return true if named color found, and set color_def rgb accordingly.
1633 If makeIndex and alloc are nonzero put the color in the color_table,
1634 and set color_def pixel to the resulting index.
1635 If makeIndex is zero, set color_def pixel to ARGB.
1636 Return false if not found
1637 -------------------------------------------------------------------------- */
1640 NSTRACE (ns_defined_color);
1643 if (ns_get_color (name, &col) != 0) /* Color not found */
1648 if (makeIndex && alloc)
1649 color_def->pixel = ns_index_color (col, f);
1650 ns_query_color (col, color_def, !makeIndex);
1657 ns_get_rgb_color (struct frame *f, float r, float g, float b, float a)
1658 /* --------------------------------------------------------------------------
1659 return an autoreleased RGB color
1660 -------------------------------------------------------------------------- */
1662 /*static int c = 1; fprintf (stderr, "color request %d\n", c++); */
1663 if (r < 0.0) r = 0.0;
1664 else if (r > 1.0) r = 1.0;
1665 if (g < 0.0) g = 0.0;
1666 else if (g > 1.0) g = 1.0;
1667 if (b < 0.0) b = 0.0;
1668 else if (b > 1.0) b = 1.0;
1669 if (a < 0.0) a = 0.0;
1670 else if (a > 1.0) a = 1.0;
1671 return (unsigned long) ns_index_color(
1672 [NSColor colorWithCalibratedRed: r green: g blue: b alpha: a], f);
1677 x_set_frame_alpha (struct frame *f)
1678 /* --------------------------------------------------------------------------
1679 change the entire-frame transparency
1680 -------------------------------------------------------------------------- */
1682 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1683 EmacsView *view = FRAME_NS_VIEW (f);
1685 double alpha_min = 1.0;
1687 if (dpyinfo->x_highlight_frame == f)
1688 alpha = f->alpha[0];
1690 alpha = f->alpha[1];
1692 if (FLOATP (Vframe_alpha_lower_limit))
1693 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1694 else if (INTEGERP (Vframe_alpha_lower_limit))
1695 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1699 else if (1.0 < alpha)
1701 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1704 #ifdef NS_IMPL_COCOA
1705 [[view window] setAlphaValue: alpha];
1710 /* ==========================================================================
1714 ========================================================================== */
1718 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1719 /* --------------------------------------------------------------------------
1720 Programmatically reposition mouse pointer in pixel coordinates
1721 -------------------------------------------------------------------------- */
1723 NSTRACE (x_set_mouse_pixel_position);
1726 /* FIXME: this does not work, and what about GNUstep? */
1727 #ifdef NS_IMPL_COCOA
1728 [FRAME_NS_VIEW (f) lockFocus];
1729 PSsetmouse ((float)pix_x, (float)pix_y);
1730 [FRAME_NS_VIEW (f) unlockFocus];
1737 x_set_mouse_position (struct frame *f, int h, int v)
1738 /* --------------------------------------------------------------------------
1739 Programmatically reposition mouse pointer in character coordinates
1740 -------------------------------------------------------------------------- */
1744 pix_x = FRAME_COL_TO_PIXEL_X (f, h) + FRAME_COLUMN_WIDTH (f) / 2;
1745 pix_y = FRAME_LINE_TO_PIXEL_Y (f, v) + FRAME_LINE_HEIGHT (f) / 2;
1747 if (pix_x < 0) pix_x = 0;
1748 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
1750 if (pix_y < 0) pix_y = 0;
1751 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
1753 x_set_mouse_pixel_position (f, pix_x, pix_y);
1758 note_mouse_movement (struct frame *frame, float x, float y)
1759 /* ------------------------------------------------------------------------
1760 Called by EmacsView on mouseMovement events. Passes on
1761 to emacs mainstream code if we moved off of a rect of interest
1762 known as last_mouse_glyph.
1763 ------------------------------------------------------------------------ */
1765 // NSTRACE (note_mouse_movement);
1767 XSETFRAME (last_mouse_motion_frame, frame);
1769 /* Note, this doesn't get called for enter/leave, since we don't have a
1770 position. Those are taken care of in the corresponding NSView methods. */
1772 /* has movement gone beyond last rect we were tracking? */
1773 if (x < last_mouse_glyph.origin.x ||
1774 x >= (last_mouse_glyph.origin.x + last_mouse_glyph.size.width) ||
1775 y < last_mouse_glyph.origin.y ||
1776 y >= (last_mouse_glyph.origin.y + last_mouse_glyph.size.height))
1778 ns_update_begin(frame);
1779 frame->mouse_moved = 1;
1780 note_mouse_highlight (frame, x, y);
1781 remember_mouse_glyph (frame, x, y, &last_mouse_glyph);
1782 ns_update_end(frame);
1791 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1792 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1794 /* --------------------------------------------------------------------------
1795 External (hook): inform emacs about mouse position and hit parts.
1796 If a scrollbar is being dragged, set bar_window, part, x, y, time.
1797 x & y should be position in the scrollbar (the whole bar, not the handle)
1798 and length of scrollbar respectively
1799 -------------------------------------------------------------------------- */
1803 Lisp_Object frame, tail;
1805 struct ns_display_info *dpyinfo;
1807 NSTRACE (ns_mouse_position);
1811 fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1815 dpyinfo = FRAME_NS_DISPLAY_INFO (*fp);
1819 if (last_mouse_scroll_bar != nil && insist == 0)
1821 /* TODO: we do not use this path at the moment because drag events will
1822 go directly to the EmacsScroller. Leaving code in for now. */
1823 [last_mouse_scroll_bar getMouseMotionPart: (int *)part window: bar_window
1825 if (time) *time = last_mouse_movement_time;
1826 last_mouse_scroll_bar = nil;
1830 /* Clear the mouse-moved flag for every frame on this display. */
1831 FOR_EACH_FRAME (tail, frame)
1832 if (FRAME_NS_P (XFRAME (frame))
1833 && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1834 XFRAME (frame)->mouse_moved = 0;
1836 last_mouse_scroll_bar = nil;
1837 if (last_mouse_frame && FRAME_LIVE_P (last_mouse_frame))
1838 f = last_mouse_frame;
1840 f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame
1841 : SELECTED_FRAME ();
1843 if (f && f->output_data.ns) /* TODO: 2nd check no longer needed? */
1845 view = FRAME_NS_VIEW (*fp);
1847 position = [[view window] mouseLocationOutsideOfEventStream];
1848 position = [view convertPoint: position fromView: nil];
1849 remember_mouse_glyph (f, position.x, position.y, &last_mouse_glyph);
1850 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1852 if (bar_window) *bar_window = Qnil;
1853 if (part) *part = 0; /*scroll_bar_handle; */
1855 if (x) XSETINT (*x, lrint (position.x));
1856 if (y) XSETINT (*y, lrint (position.y));
1857 if (time) *time = last_mouse_movement_time;
1867 ns_frame_up_to_date (struct frame *f)
1868 /* --------------------------------------------------------------------------
1869 External (hook): Fix up mouse highlighting right after a full update.
1870 Some highlighting was deferred if GC was happening during
1871 note_mouse_highlight (), while other highlighting was deferred for update.
1872 -------------------------------------------------------------------------- */
1874 NSTRACE (ns_frame_up_to_date);
1878 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1879 if ((hlinfo->mouse_face_deferred_gc || f ==hlinfo->mouse_face_mouse_frame)
1880 /*&& hlinfo->mouse_face_mouse_frame*/)
1884 if (hlinfo->mouse_face_mouse_frame)
1885 note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
1886 hlinfo->mouse_face_mouse_x,
1887 hlinfo->mouse_face_mouse_y);
1888 hlinfo->mouse_face_deferred_gc = 0;
1897 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1898 /* --------------------------------------------------------------------------
1899 External (RIF): set frame mouse pointer type.
1900 -------------------------------------------------------------------------- */
1902 NSTRACE (ns_define_frame_cursor);
1903 if (FRAME_POINTER_TYPE (f) != cursor)
1905 EmacsView *view = FRAME_NS_VIEW (f);
1906 FRAME_POINTER_TYPE (f) = cursor;
1907 [[view window] invalidateCursorRectsForView: view];
1908 /* Redisplay assumes this function also draws the changed frame
1909 cursor, but this function doesn't, so do it explicitly. */
1910 x_update_cursor (f, 1);
1916 /* ==========================================================================
1920 ========================================================================== */
1924 ns_convert_key (unsigned code)
1925 /* --------------------------------------------------------------------------
1926 Internal call used by NSView-keyDown.
1927 -------------------------------------------------------------------------- */
1929 const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym)
1930 / sizeof (convert_ns_to_X_keysym[0]));
1932 /* An array would be faster, but less easy to read. */
1933 for (keysym = 0; keysym < last_keysym; keysym += 2)
1934 if (code == convert_ns_to_X_keysym[keysym])
1935 return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
1937 /* if decide to use keyCode and Carbon table, use this line:
1938 return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
1943 x_get_keysym_name (int keysym)
1944 /* --------------------------------------------------------------------------
1945 Called by keyboard.c. Not sure if the return val is important, except
1947 -------------------------------------------------------------------------- */
1949 static char value[16];
1950 NSTRACE (x_get_keysym_name);
1951 sprintf (value, "%d", keysym);
1957 /* ==========================================================================
1959 Block drawing operations
1961 ========================================================================== */
1965 ns_redraw_scroll_bars (struct frame *f)
1969 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
1970 NSTRACE (ns_redraw_scroll_bars);
1971 for (i =[subviews count]-1; i >= 0; i--)
1973 view = [subviews objectAtIndex: i];
1974 if (![view isKindOfClass: [EmacsScroller class]]) continue;
1981 ns_clear_frame (struct frame *f)
1982 /* --------------------------------------------------------------------------
1983 External (hook): Erase the entire frame
1984 -------------------------------------------------------------------------- */
1986 NSView *view = FRAME_NS_VIEW (f);
1989 NSTRACE (ns_clear_frame);
1991 /* comes on initial frame because we have
1992 after-make-frame-functions = select-frame */
1993 if (!FRAME_DEFAULT_FACE (f))
1996 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
1998 output_cursor.hpos = output_cursor.vpos = 0;
1999 output_cursor.x = -1;
2004 ns_focus (f, &r, 1);
2005 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
2009 /* as of 2006/11 or so this is now needed */
2010 ns_redraw_scroll_bars (f);
2016 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2017 /* --------------------------------------------------------------------------
2018 External (RIF): Clear section of frame
2019 -------------------------------------------------------------------------- */
2021 NSRect r = NSMakeRect (x, y, width, height);
2022 NSView *view = FRAME_NS_VIEW (f);
2023 struct face *face = FRAME_DEFAULT_FACE (f);
2028 NSTRACE (ns_clear_frame_area);
2030 r = NSIntersectionRect (r, [view frame]);
2031 ns_focus (f, &r, 1);
2032 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2042 ns_scroll_run (struct window *w, struct run *run)
2043 /* --------------------------------------------------------------------------
2044 External (RIF): Insert or delete n lines at line vpos
2045 -------------------------------------------------------------------------- */
2047 struct frame *f = XFRAME (w->frame);
2048 int x, y, width, height, from_y, to_y, bottom_y;
2050 NSTRACE (ns_scroll_run);
2052 /* begin copy from other terms */
2053 /* Get frame-relative bounding box of the text display area of W,
2054 without mode lines. Include in this box the left and right
2056 window_box (w, -1, &x, &y, &width, &height);
2058 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2059 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2060 bottom_y = y + height;
2064 /* Scrolling up. Make sure we don't copy part of the mode
2065 line at the bottom. */
2066 if (from_y + run->height > bottom_y)
2067 height = bottom_y - from_y;
2069 height = run->height;
2073 /* Scrolling down. Make sure we don't copy over the mode line.
2075 if (to_y + run->height > bottom_y)
2076 height = bottom_y - to_y;
2078 height = run->height;
2080 /* end copy from other terms */
2091 NSRect srcRect = NSMakeRect (x, from_y, width, height);
2092 NSRect dstRect = NSMakeRect (x, to_y, width, height);
2093 NSPoint dstOrigin = NSMakePoint (x, to_y);
2095 ns_focus (f, &dstRect, 1);
2096 NSCopyBits (0, srcRect , dstOrigin);
2105 ns_after_update_window_line (struct glyph_row *desired_row)
2106 /* --------------------------------------------------------------------------
2107 External (RIF): preparatory to fringe update after text was updated
2108 -------------------------------------------------------------------------- */
2110 struct window *w = updated_window;
2114 NSTRACE (ns_after_update_window_line);
2116 /* begin copy from other terms */
2119 if (!desired_row->mode_line_p && !w->pseudo_window_p)
2120 desired_row->redraw_fringe_bitmaps_p = 1;
2122 /* When a window has disappeared, make sure that no rest of
2123 full-width rows stays visible in the internal border. */
2124 if (windows_or_buffers_changed
2125 && desired_row->full_width_p
2126 && (f = XFRAME (w->frame),
2127 width = FRAME_INTERNAL_BORDER_WIDTH (f),
2129 && (height = desired_row->visible_height,
2132 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2135 ns_clear_frame_area (f, 0, y, width, height);
2136 ns_clear_frame_area (f,
2137 FRAME_PIXEL_WIDTH (f) - width,
2145 ns_shift_glyphs_for_insert (struct frame *f,
2146 int x, int y, int width, int height,
2148 /* --------------------------------------------------------------------------
2149 External (RIF): copy an area horizontally, don't worry about clearing src
2150 -------------------------------------------------------------------------- */
2152 NSRect srcRect = NSMakeRect (x, y, width, height);
2153 NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2154 NSPoint dstOrigin = dstRect.origin;
2156 NSTRACE (ns_shift_glyphs_for_insert);
2158 ns_focus (f, &dstRect, 1);
2159 NSCopyBits (0, srcRect, dstOrigin);
2165 /* ==========================================================================
2167 Character encoding and metrics
2169 ========================================================================== */
2173 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2174 /* --------------------------------------------------------------------------
2175 External (RIF); compute left/right overhang of whole string and set in s
2176 -------------------------------------------------------------------------- */
2178 struct font *font = s->font;
2182 struct font_metrics metrics;
2183 unsigned int codes[2];
2184 codes[0] = *(s->char2b);
2185 codes[1] = *(s->char2b + s->nchars - 1);
2187 font->driver->text_extents (font, codes, 2, &metrics);
2188 s->left_overhang = -metrics.lbearing;
2190 = metrics.rbearing > metrics.width
2191 ? metrics.rbearing - metrics.width : 0;
2195 s->left_overhang = 0;
2196 s->right_overhang = ((struct nsfont_info *)font)->ital ?
2197 FONT_HEIGHT (font) * 0.2 : 0;
2203 /* ==========================================================================
2205 Fringe and cursor drawing
2207 ========================================================================== */
2210 extern int max_used_fringe_bitmap;
2212 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2213 struct draw_fringe_bitmap_params *p)
2214 /* --------------------------------------------------------------------------
2215 External (RIF); fringe-related
2216 -------------------------------------------------------------------------- */
2218 struct frame *f = XFRAME (WINDOW_FRAME (w));
2219 struct face *face = p->face;
2221 static EmacsImage **bimgs = NULL;
2222 static int nBimgs = 0;
2224 /* grow bimgs if needed */
2225 if (nBimgs < max_used_fringe_bitmap)
2227 bimgs = xrealloc (bimgs, max_used_fringe_bitmap * sizeof *bimgs);
2228 memset (bimgs + nBimgs, 0,
2229 (max_used_fringe_bitmap - nBimgs) * sizeof *bimgs);
2230 nBimgs = max_used_fringe_bitmap;
2233 /* Must clip because of partially visible lines. */
2234 rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
2235 ns_clip_to_row (w, row, -1, YES);
2239 int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
2241 /* If the fringe is adjacent to the left (right) scroll bar of a
2242 leftmost (rightmost, respectively) window, then extend its
2243 background to the gap between the fringe and the bar. */
2244 if ((WINDOW_LEFTMOST_P (w)
2245 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
2246 || (WINDOW_RIGHTMOST_P (w)
2247 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w)))
2249 int sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
2253 int bar_area_x = WINDOW_SCROLL_BAR_AREA_X (w);
2254 int bar_area_width = (WINDOW_CONFIG_SCROLL_BAR_COLS (w)
2255 * FRAME_COLUMN_WIDTH (f));
2259 /* Bitmap fills the fringe. */
2260 if (bar_area_x + bar_area_width == p->x)
2261 bx = bar_area_x + sb_width;
2262 else if (p->x + p->wd == bar_area_x)
2266 int header_line_height = WINDOW_HEADER_LINE_HEIGHT (w);
2268 nx = bar_area_width - sb_width;
2269 by = WINDOW_TO_FRAME_PIXEL_Y (w, max (header_line_height,
2271 ny = row->visible_height;
2276 if (bar_area_x + bar_area_width == bx)
2278 bx = bar_area_x + sb_width;
2279 nx += bar_area_width - sb_width;
2281 else if (bx + nx == bar_area_x)
2282 nx += bar_area_width - sb_width;
2287 if (bx >= 0 && nx > 0)
2289 NSRect r = NSMakeRect (bx, by, nx, ny);
2291 [ns_lookup_indexed_color (face->background, f) set];
2298 NSRect r = NSMakeRect (p->x, p->y, p->wd, p->h);
2299 EmacsImage *img = bimgs[p->which - 1];
2303 unsigned short *bits = p->bits + p->dh;
2306 unsigned char *cbits = xmalloc (len);
2308 for (i = 0; i < len; i++)
2309 cbits[i] = ~(bits[i] & 0xff);
2310 img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2312 bimgs[p->which - 1] = img;
2317 /* Since we composite the bitmap instead of just blitting it, we need
2318 to erase the whole background. */
2319 [ns_lookup_indexed_color(face->background, f) set];
2321 [img setXBMColor: ns_lookup_indexed_color(face->foreground, f)];
2322 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
2324 fromRect: NSZeroRect
2325 operation: NSCompositeSourceOver
2331 NSPoint pt = r.origin;
2333 [img compositeToPoint: pt operation: NSCompositeSourceOver];
2342 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2343 int x, int y, int cursor_type, int cursor_width,
2344 int on_p, int active_p)
2345 /* --------------------------------------------------------------------------
2346 External call (RIF): draw cursor.
2347 Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2348 -------------------------------------------------------------------------- */
2351 int fx, fy, h, cursor_height;
2352 struct frame *f = WINDOW_XFRAME (w);
2353 struct glyph *phys_cursor_glyph;
2355 struct glyph *cursor_glyph;
2357 NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2359 /* If cursor is out of bounds, don't draw garbage. This can happen
2360 in mini-buffer windows when switching between echo area glyphs
2363 NSTRACE (dumpcursor);
2368 w->phys_cursor_type = cursor_type;
2369 w->phys_cursor_on_p = on_p;
2371 if (cursor_type == NO_CURSOR)
2373 w->phys_cursor_width = 0;
2377 if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2379 if (glyph_row->exact_window_width_line_p
2380 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2382 glyph_row->cursor_in_fringe_p = 1;
2383 draw_fringe_bitmap (w, glyph_row, 0);
2388 /* We draw the cursor (with NSRectFill), then draw the glyph on top
2389 (other terminals do it the other way round). We must set
2390 w->phys_cursor_width to the cursor width. For bar cursors, that
2391 is CURSOR_WIDTH; for box cursors, it is the glyph width. */
2392 get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2394 /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2395 to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2396 if (cursor_type == BAR_CURSOR)
2398 if (cursor_width < 1)
2399 cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2400 w->phys_cursor_width = cursor_width;
2402 /* If we have an HBAR, "cursor_width" MAY specify height. */
2403 else if (cursor_type == HBAR_CURSOR)
2405 cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2406 fy += h - cursor_height;
2410 r.origin.x = fx, r.origin.y = fy;
2412 r.size.width = w->phys_cursor_width;
2414 /* TODO: only needed in rare cases with last-resort font in HELLO..
2415 should we do this more efficiently? */
2416 ns_clip_to_row (w, glyph_row, -1, NO); /* do ns_focus(f, &r, 1); if remove */
2419 face = FACE_FROM_ID (f, phys_cursor_glyph->face_id);
2420 if (face && NS_FACE_BACKGROUND (face)
2421 == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2423 [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2424 hollow_color = FRAME_CURSOR_COLOR (f);
2427 [FRAME_CURSOR_COLOR (f) set];
2429 #ifdef NS_IMPL_COCOA
2430 /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2431 atomic. Cleaner ways of doing this should be investigated.
2432 One way would be to set a global variable DRAWING_CURSOR
2433 when making the call to draw_phys..(), don't focus in that
2434 case, then move the ns_unfocus() here after that call. */
2435 NSDisableScreenUpdates ();
2438 switch (cursor_type)
2442 case FILLED_BOX_CURSOR:
2445 case HOLLOW_BOX_CURSOR:
2448 NSRectFill (NSInsetRect (r, 1, 1));
2449 [FRAME_CURSOR_COLOR (f) set];
2456 /* If the character under cursor is R2L, draw the bar cursor
2457 on the right of its glyph, rather than on the left. */
2458 cursor_glyph = get_phys_cursor_glyph (w);
2459 if ((cursor_glyph->resolved_level & 1) != 0)
2460 s.origin.x += cursor_glyph->pixel_width - s.size.width;
2467 /* draw the character under the cursor */
2468 if (cursor_type != NO_CURSOR)
2469 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2471 #ifdef NS_IMPL_COCOA
2472 NSEnableScreenUpdates ();
2479 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2480 /* --------------------------------------------------------------------------
2481 External (RIF): Draw a vertical line.
2482 -------------------------------------------------------------------------- */
2484 struct frame *f = XFRAME (WINDOW_FRAME (w));
2486 NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2488 NSTRACE (ns_draw_vertical_window_border);
2490 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2492 [ns_lookup_indexed_color(face->foreground, f) set];
2494 ns_focus (f, &r, 1);
2501 show_hourglass (struct atimer *timer)
2503 if (hourglass_shown_p)
2508 /* TODO: add NSProgressIndicator to selected frame (see macfns.c) */
2510 hourglass_shown_p = 1;
2516 hide_hourglass (void)
2518 if (!hourglass_shown_p)
2523 /* TODO: remove NSProgressIndicator from all frames */
2525 hourglass_shown_p = 0;
2531 /* ==========================================================================
2533 Glyph drawing operations
2535 ========================================================================== */
2538 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2539 /* --------------------------------------------------------------------------
2540 Wrapper utility to account for internal border width on full-width lines,
2541 and allow top full-width rows to hit the frame top. nr should be pointer
2542 to two successive NSRects. Number of rects actually used is returned.
2543 -------------------------------------------------------------------------- */
2545 int n = get_glyph_string_clip_rects (s, nr, 2);
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 /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
2871 if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
2873 ns_draw_box (r, abs (thickness),
2874 ns_lookup_indexed_color (face->box_color, s->f),
2879 ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2880 1, 1, left_p, right_p, s);
2886 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2887 /* --------------------------------------------------------------------------
2888 Modeled after x_draw_glyph_string_background, which draws BG in
2889 certain cases. Others are left to the text rendering routine.
2890 -------------------------------------------------------------------------- */
2892 NSTRACE (ns_maybe_dumpglyphs_background);
2894 if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2896 int box_line_width = max (s->face->box_line_width, 0);
2897 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2898 || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2901 if (s->hl == DRAW_MOUSE_FACE)
2903 face = FACE_FROM_ID (s->f,
2904 MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2906 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2909 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2911 [(NS_FACE_BACKGROUND (face) != 0
2912 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2913 : FRAME_BACKGROUND_COLOR (s->f)) set];
2916 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (s->f);
2917 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2920 if (s->hl != DRAW_CURSOR)
2922 NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2923 s->background_width,
2924 s->height-2*box_line_width);
2928 s->background_filled_p = 1;
2935 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2936 /* --------------------------------------------------------------------------
2937 Renders an image and associated borders.
2938 -------------------------------------------------------------------------- */
2940 EmacsImage *img = s->img->pixmap;
2941 int box_line_vwidth = max (s->face->box_line_width, 0);
2942 int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2943 int bg_x, bg_y, bg_height;
2950 NSTRACE (ns_dumpglyphs_image);
2952 if (s->face->box != FACE_NO_BOX
2953 && s->first_glyph->left_box_line_p && s->slice.x == 0)
2954 x += abs (s->face->box_line_width);
2957 bg_y = s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2958 bg_height = s->height;
2959 /* other terms have this, but was causing problems w/tabbar mode */
2960 /* - 2 * box_line_vwidth; */
2962 if (s->slice.x == 0) x += s->img->hmargin;
2963 if (s->slice.y == 0) y += s->img->vmargin;
2965 /* Draw BG: if we need larger area than image itself cleared, do that,
2966 otherwise, since we composite the image under NS (instead of mucking
2967 with its background color), we must clear just the image area. */
2968 if (s->hl == DRAW_MOUSE_FACE)
2970 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2972 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2975 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2977 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
2979 if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
2980 || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
2982 br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
2983 s->background_filled_p = 1;
2987 br = NSMakeRect (x, y, s->slice.width, s->slice.height);
2992 /* Draw the image.. do we need to draw placeholder if img ==nil? */
2995 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
2996 NSRect dr = NSMakeRect (x, y, s->slice.width, s->slice.height);
2997 NSRect ir = NSMakeRect (s->slice.x, s->slice.y,
2998 s->slice.width, s->slice.height);
3001 operation: NSCompositeSourceOver
3006 [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3007 operation: NSCompositeSourceOver];
3011 if (s->hl == DRAW_CURSOR)
3013 [FRAME_CURSOR_COLOR (s->f) set];
3014 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3015 tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3017 /* Currently on NS img->mask is always 0. Since
3018 get_window_cursor_type specifies a hollow box cursor when on
3019 a non-masked image we never reach this clause. But we put it
3020 in in anticipation of better support for image masks on
3022 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3026 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3029 /* Draw underline, overline, strike-through. */
3030 ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3032 /* Draw relief, if requested */
3033 if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3035 if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3037 th = tool_bar_button_relief >= 0 ?
3038 tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3039 raised_p = (s->hl == DRAW_IMAGE_RAISED);
3043 th = abs (s->img->relief);
3044 raised_p = (s->img->relief > 0);
3047 r.origin.x = x - th;
3048 r.origin.y = y - th;
3049 r.size.width = s->slice.width + 2*th-1;
3050 r.size.height = s->slice.height + 2*th-1;
3051 ns_draw_relief (r, th, raised_p,
3053 s->slice.y + s->slice.height == s->img->height,
3055 s->slice.x + s->slice.width == s->img->width, s);
3058 /* If there is no mask, the background won't be seen,
3059 so draw a rectangle on the image for the cursor.
3060 Do this for all images, getting transparency right is not reliable. */
3061 if (s->hl == DRAW_CURSOR)
3063 int thickness = abs (s->img->relief);
3064 if (thickness == 0) thickness = 1;
3065 ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3071 ns_dumpglyphs_stretch (struct glyph_string *s)
3076 NSColor *fgCol, *bgCol;
3078 if (!s->background_filled_p)
3080 n = ns_get_glyph_string_clip_rect (s, r);
3081 *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3083 ns_focus (s->f, r, n);
3085 if (s->hl == DRAW_MOUSE_FACE)
3087 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3089 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3092 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3094 bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3095 fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3097 for (i = 0; i < n; ++i)
3099 if (!s->row->full_width_p)
3101 int overrun, leftoverrun;
3103 /* truncate to avoid overwriting fringe and/or scrollbar */
3104 overrun = max (0, (s->x + s->background_width)
3105 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3106 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3107 r[i].size.width -= overrun;
3109 /* truncate to avoid overwriting to left of the window box */
3110 leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3111 + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3113 if (leftoverrun > 0)
3115 r[i].origin.x += leftoverrun;
3116 r[i].size.width -= leftoverrun;
3119 /* XXX: Try to work between problem where a stretch glyph on
3120 a partially-visible bottom row will clear part of the
3121 modeline, and another where list-buffers headers and similar
3122 rows erroneously have visible_height set to 0. Not sure
3123 where this is coming from as other terms seem not to show. */
3124 r[i].size.height = min (s->height, s->row->visible_height);
3129 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3130 overwriting cursor (usually when cursor on a tab) */
3131 if (s->hl == DRAW_CURSOR)
3136 width = s->w->phys_cursor_width;
3137 r[i].size.width -= width;
3138 r[i].origin.x += width;
3142 /* Draw overlining, etc. on the cursor. */
3143 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3144 ns_draw_text_decoration (s, face, bgCol, width, x);
3146 ns_draw_text_decoration (s, face, fgCol, width, x);
3153 /* Draw overlining, etc. on the stretch glyph (or the part
3154 of the stretch glyph after the cursor). */
3155 ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3159 s->background_filled_p = 1;
3165 ns_draw_glyph_string (struct glyph_string *s)
3166 /* --------------------------------------------------------------------------
3167 External (RIF): Main draw-text call.
3168 -------------------------------------------------------------------------- */
3170 /* TODO (optimize): focus for box and contents draw */
3173 char box_drawn_p = 0;
3175 NSTRACE (ns_draw_glyph_string);
3177 if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3180 struct glyph_string *next;
3182 for (width = 0, next = s->next;
3183 next && width < s->right_overhang;
3184 width += next->width, next = next->next)
3185 if (next->first_glyph->type != IMAGE_GLYPH)
3187 if (next->first_glyph->type != STRETCH_GLYPH)
3189 n = ns_get_glyph_string_clip_rect (s->next, r);
3190 ns_focus (s->f, r, n);
3191 ns_maybe_dumpglyphs_background (s->next, 1);
3196 ns_dumpglyphs_stretch (s->next);
3198 next->num_clips = 0;
3202 if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3203 && (s->first_glyph->type == CHAR_GLYPH
3204 || s->first_glyph->type == COMPOSITE_GLYPH))
3206 n = ns_get_glyph_string_clip_rect (s, r);
3207 ns_focus (s->f, r, n);
3208 ns_maybe_dumpglyphs_background (s, 1);
3209 ns_dumpglyphs_box_or_relief (s);
3214 switch (s->first_glyph->type)
3218 n = ns_get_glyph_string_clip_rect (s, r);
3219 ns_focus (s->f, r, n);
3220 ns_dumpglyphs_image (s, r[0]);
3225 ns_dumpglyphs_stretch (s);
3229 case COMPOSITE_GLYPH:
3230 n = ns_get_glyph_string_clip_rect (s, r);
3231 ns_focus (s->f, r, n);
3233 if (s->for_overlaps || (s->cmp_from > 0
3234 && ! s->first_glyph->u.cmp.automatic))
3235 s->background_filled_p = 1;
3237 ns_maybe_dumpglyphs_background
3238 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3240 ns_tmp_flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3241 (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3242 (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3243 NS_DUMPGLYPH_NORMAL));
3244 ns_tmp_font = (struct nsfont_info *)s->face->font;
3245 if (ns_tmp_font == NULL)
3246 ns_tmp_font = (struct nsfont_info *)FRAME_FONT (s->f);
3248 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3250 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3251 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3252 NS_FACE_FOREGROUND (s->face) = tmp;
3255 ns_tmp_font->font.driver->draw
3256 (s, 0, s->nchars, s->x, s->y,
3257 (ns_tmp_flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3258 || ns_tmp_flags == NS_DUMPGLYPH_MOUSEFACE);
3260 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3262 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3263 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3264 NS_FACE_FOREGROUND (s->face) = tmp;
3270 case GLYPHLESS_GLYPH:
3271 n = ns_get_glyph_string_clip_rect (s, r);
3272 ns_focus (s->f, r, n);
3274 if (s->for_overlaps || (s->cmp_from > 0
3275 && ! s->first_glyph->u.cmp.automatic))
3276 s->background_filled_p = 1;
3278 ns_maybe_dumpglyphs_background
3279 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3281 /* Not yet implemented. */
3290 /* Draw box if not done already. */
3291 if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3293 n = ns_get_glyph_string_clip_rect (s, r);
3294 ns_focus (s->f, r, n);
3295 ns_dumpglyphs_box_or_relief (s);
3304 /* ==========================================================================
3308 ========================================================================== */
3312 ns_send_appdefined (int value)
3313 /* --------------------------------------------------------------------------
3314 Internal: post an appdefined event which EmacsApp-sendEvent will
3315 recognize and take as a command to halt the event loop.
3316 -------------------------------------------------------------------------- */
3318 /*NSTRACE (ns_send_appdefined); */
3320 /* Only post this event if we haven't already posted one. This will end
3321 the [NXApp run] main loop after having processed all events queued at
3323 if (send_appdefined)
3327 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
3328 send_appdefined = NO;
3330 /* Don't need wakeup timer any more */
3333 [timed_entry invalidate];
3334 [timed_entry release];
3338 nxev = [NSEvent otherEventWithType: NSApplicationDefined
3339 location: NSMakePoint (0, 0)
3342 windowNumber: [[NSApp mainWindow] windowNumber]
3343 context: [NSApp context]
3348 /* Post an application defined event on the event queue. When this is
3349 received the [NXApp run] will return, thus having processed all
3350 events which are currently queued. */
3351 [NSApp postEvent: nxev atStart: NO];
3356 ns_read_socket (struct terminal *terminal, struct input_event *hold_quit)
3357 /* --------------------------------------------------------------------------
3358 External (hook): Post an event to ourself and keep reading events until
3359 we read it back again. In effect process all events which were waiting.
3360 From 21+ we have to manage the event buffer ourselves.
3361 -------------------------------------------------------------------------- */
3363 struct input_event ev;
3366 /* NSTRACE (ns_read_socket); */
3368 if ([NSApp modalWindow] != nil)
3371 if (hold_event_q.nr > 0)
3374 for (i = 0; i < hold_event_q.nr; ++i)
3375 kbd_buffer_store_event_hold (&hold_event_q.q[i], hold_quit);
3376 hold_event_q.nr = 0;
3381 n_emacs_events_pending = 0;
3384 q_event_ptr = hold_quit;
3386 /* we manage autorelease pools by allocate/reallocate each time around
3387 the loop; strict nesting is occasionally violated but seems not to
3388 matter.. earlier methods using full nesting caused major memory leaks */
3389 [outerpool release];
3390 outerpool = [[NSAutoreleasePool alloc] init];
3392 /* If have pending open-file requests, attend to the next one of those. */
3393 if (ns_pending_files && [ns_pending_files count] != 0
3394 && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3396 [ns_pending_files removeObjectAtIndex: 0];
3398 /* Deal with pending service requests. */
3399 else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3401 NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3402 withArg: [ns_pending_service_args objectAtIndex: 0]])
3404 [ns_pending_service_names removeObjectAtIndex: 0];
3405 [ns_pending_service_args removeObjectAtIndex: 0];
3409 /* Run and wait for events. We must always send one NX_APPDEFINED event
3410 to ourself, otherwise [NXApp run] will never exit. */
3411 send_appdefined = YES;
3412 ns_send_appdefined (-1);
3414 if (++apploopnr != 1)
3422 nevents = n_emacs_events_pending;
3423 n_emacs_events_pending = 0;
3424 emacs_event = q_event_ptr = NULL;
3432 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3433 fd_set *exceptfds, EMACS_TIME *timeout, sigset_t *sigmask)
3434 /* --------------------------------------------------------------------------
3435 Replacement for select, checking for events
3436 -------------------------------------------------------------------------- */
3441 struct input_event event;
3444 /* NSTRACE (ns_select); */
3446 for (k = 0; k < nfds+1; k++)
3448 if (readfds && FD_ISSET(k, readfds)) ++nr;
3449 if (writefds && FD_ISSET(k, writefds)) ++nr;
3453 || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0))
3454 return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
3456 [outerpool release];
3457 outerpool = [[NSAutoreleasePool alloc] init];
3460 send_appdefined = YES;
3463 pthread_mutex_lock (&select_mutex);
3468 select_readfds = *readfds;
3469 select_valid += SELECT_HAVE_READ;
3473 select_writefds = *writefds;
3474 select_valid += SELECT_HAVE_WRITE;
3479 select_timeout = *timeout;
3480 select_valid += SELECT_HAVE_TMO;
3483 pthread_mutex_unlock (&select_mutex);
3485 /* Inform fd_handler that select should be called */
3487 write (selfds[1], &c, 1);
3489 else if (nr == 0 && timeout)
3491 /* No file descriptor, just a timeout, no need to wake fd_handler */
3492 double time = EMACS_TIME_TO_DOUBLE (*timeout);
3493 timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3496 @selector (timeout_handler:)
3501 else /* No timeout and no file descriptors, can this happen? */
3503 /* Send appdefined so we exit from the loop */
3504 ns_send_appdefined (-1);
3509 emacs_event = &event;
3510 if (++apploopnr != 1)
3517 if (nr > 0 && readfds)
3520 write (selfds[1], &c, 1);
3524 ev = last_appdefined_event;
3529 if ([ev type] != NSApplicationDefined)
3533 last_appdefined_event = 0;
3537 /* The NX_APPDEFINED event we received was a timeout. */
3542 /* The NX_APPDEFINED event we received was the result of
3543 at least one real input event arriving. */
3549 /* Received back from select () in fd_handler; copy the results */
3550 pthread_mutex_lock (&select_mutex);
3551 if (readfds) *readfds = select_readfds;
3552 if (writefds) *writefds = select_writefds;
3553 if (timeout) *timeout = select_timeout;
3554 pthread_mutex_unlock (&select_mutex);
3564 /* ==========================================================================
3568 ========================================================================== */
3572 ns_set_vertical_scroll_bar (struct window *window,
3573 int portion, int whole, int position)
3574 /* --------------------------------------------------------------------------
3575 External (hook): Update or add scrollbar
3576 -------------------------------------------------------------------------- */
3580 struct frame *f = XFRAME (WINDOW_FRAME (window));
3581 EmacsView *view = FRAME_NS_VIEW (f);
3582 int window_y, window_height;
3583 int top, left, height, width, sb_width, sb_left;
3585 BOOL fringe_extended_p;
3587 /* optimization; display engine sends WAY too many of these.. */
3588 if (!NILP (window->vertical_scroll_bar))
3590 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3591 if ([bar checkSamePosition: position portion: portion whole: whole])
3593 if (view->scrollbarsNeedingUpdate == 0)
3595 if (!windows_or_buffers_changed)
3599 view->scrollbarsNeedingUpdate--;
3603 NSTRACE (ns_set_vertical_scroll_bar);
3605 /* Get dimensions. */
3606 window_box (window, -1, 0, &window_y, 0, &window_height);
3608 height = window_height;
3609 width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3610 left = WINDOW_SCROLL_BAR_AREA_X (window);
3612 /* allow for displaying a skinnier scrollbar than char area allotted */
3613 sb_width = (WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) > 0) ?
3614 WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) : width;
3617 r = NSMakeRect (sb_left, top, sb_width, height);
3618 /* the parent view is flipped, so we need to flip y value */
3620 r.origin.y = (v.size.height - r.size.height - r.origin.y);
3622 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (window))
3623 fringe_extended_p = (WINDOW_LEFTMOST_P (window)
3624 && WINDOW_LEFT_FRINGE_WIDTH (window)
3625 && (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (window)
3626 || WINDOW_LEFT_MARGIN_COLS (window) == 0));
3628 fringe_extended_p = (WINDOW_RIGHTMOST_P (window)
3629 && WINDOW_RIGHT_FRINGE_WIDTH (window)
3630 && (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (window)
3631 || WINDOW_RIGHT_MARGIN_COLS (window) == 0));
3633 XSETWINDOW (win, window);
3636 /* we want at least 5 lines to display a scrollbar */
3637 if (WINDOW_TOTAL_LINES (window) < 5)
3639 if (!NILP (window->vertical_scroll_bar))
3641 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3642 [bar removeFromSuperview];
3643 wset_vertical_scroll_bar (window, Qnil);
3645 ns_clear_frame_area (f, sb_left, top, width, height);
3650 if (NILP (window->vertical_scroll_bar))
3652 if (width > 0 && height > 0)
3654 if (fringe_extended_p)
3655 ns_clear_frame_area (f, sb_left, top, sb_width, height);
3657 ns_clear_frame_area (f, left, top, width, height);
3660 bar = [[EmacsScroller alloc] initFrame: r window: win];
3661 wset_vertical_scroll_bar (window, make_save_value (bar, 0));
3666 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3667 oldRect = [bar frame];
3668 r.size.width = oldRect.size.width;
3669 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3671 if (oldRect.origin.x != r.origin.x)
3672 ns_clear_frame_area (f, sb_left, top, width, height);
3677 [bar setPosition: position portion: portion whole: whole];
3683 ns_condemn_scroll_bars (struct frame *f)
3684 /* --------------------------------------------------------------------------
3685 External (hook): arrange for all frame's scrollbars to be removed
3686 at next call to judge_scroll_bars, except for those redeemed.
3687 -------------------------------------------------------------------------- */
3691 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3693 NSTRACE (ns_condemn_scroll_bars);
3695 for (i =[subviews count]-1; i >= 0; i--)
3697 view = [subviews objectAtIndex: i];
3698 if ([view isKindOfClass: [EmacsScroller class]])
3705 ns_redeem_scroll_bar (struct window *window)
3706 /* --------------------------------------------------------------------------
3707 External (hook): arrange to spare this window's scrollbar
3708 at next call to judge_scroll_bars.
3709 -------------------------------------------------------------------------- */
3712 NSTRACE (ns_redeem_scroll_bar);
3713 if (!NILP (window->vertical_scroll_bar))
3715 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3722 ns_judge_scroll_bars (struct frame *f)
3723 /* --------------------------------------------------------------------------
3724 External (hook): destroy all scrollbars on frame that weren't
3725 redeemed after call to condemn_scroll_bars.
3726 -------------------------------------------------------------------------- */
3730 EmacsView *eview = FRAME_NS_VIEW (f);
3731 NSArray *subviews = [[eview superview] subviews];
3734 NSTRACE (ns_judge_scroll_bars);
3735 for (i = [subviews count]-1; i >= 0; --i)
3737 view = [subviews objectAtIndex: i];
3738 if (![view isKindOfClass: [EmacsScroller class]]) continue;
3744 [eview updateFrameSize: NO];
3749 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
3751 /* XXX irrelevant under NS */
3756 /* ==========================================================================
3760 ========================================================================== */
3763 x_display_pixel_height (struct ns_display_info *dpyinfo)
3765 NSScreen *screen = [NSScreen mainScreen];
3766 return [screen frame].size.height;
3770 x_display_pixel_width (struct ns_display_info *dpyinfo)
3772 NSScreen *screen = [NSScreen mainScreen];
3773 return [screen frame].size.width;
3777 static Lisp_Object ns_string_to_lispmod (const char *s)
3778 /* --------------------------------------------------------------------------
3779 Convert modifier name to lisp symbol
3780 -------------------------------------------------------------------------- */
3782 if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
3784 else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
3786 else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
3788 else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
3790 else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
3792 else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
3800 ns_default (const char *parameter, Lisp_Object *result,
3801 Lisp_Object yesval, Lisp_Object noval,
3802 BOOL is_float, BOOL is_modstring)
3803 /* --------------------------------------------------------------------------
3804 Check a parameter value in user's preferences
3805 -------------------------------------------------------------------------- */
3807 const char *value = ns_get_defaults_value (parameter);
3813 if (c_strcasecmp (value, "YES") == 0)
3815 else if (c_strcasecmp (value, "NO") == 0)
3817 else if (is_float && (f = strtod (value, &pos), pos != value))
3818 *result = make_float (f);
3819 else if (is_modstring && value)
3820 *result = ns_string_to_lispmod (value);
3821 else fprintf (stderr,
3822 "Bad value for default \"%s\": \"%s\"\n", parameter, value);
3828 ns_initialize_display_info (struct ns_display_info *dpyinfo)
3829 /* --------------------------------------------------------------------------
3830 Initialize global info and storage for display.
3831 -------------------------------------------------------------------------- */
3833 NSScreen *screen = [NSScreen mainScreen];
3834 NSWindowDepth depth = [screen depth];
3835 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
3837 dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
3838 dpyinfo->resy = 72.27;
3839 dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
3840 NSColorSpaceFromDepth (depth)]
3841 && ![NSCalibratedWhiteColorSpace isEqualToString:
3842 NSColorSpaceFromDepth (depth)];
3843 dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
3844 dpyinfo->image_cache = make_image_cache ();
3845 dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
3846 dpyinfo->color_table->colors = NULL;
3847 dpyinfo->root_window = 42; /* a placeholder.. */
3849 hlinfo->mouse_face_mouse_frame = NULL;
3850 hlinfo->mouse_face_deferred_gc = 0;
3851 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
3852 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
3853 hlinfo->mouse_face_face_id = DEFAULT_FACE_ID;
3854 hlinfo->mouse_face_window = hlinfo->mouse_face_overlay = Qnil;
3855 hlinfo->mouse_face_hidden = 0;
3857 hlinfo->mouse_face_mouse_x = hlinfo->mouse_face_mouse_y = 0;
3858 hlinfo->mouse_face_defer = 0;
3860 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
3862 dpyinfo->n_fonts = 0;
3863 dpyinfo->smallest_font_height = 1;
3864 dpyinfo->smallest_char_width = 1;
3868 /* This and next define (many of the) public functions in this file. */
3869 /* x_... are generic versions in xdisp.c that we, and other terms, get away
3870 with using despite presence in the "system dependent" redisplay
3871 interface. In addition, many of the ns_ methods have code that is
3872 shared with all terms, indicating need for further refactoring. */
3873 extern frame_parm_handler ns_frame_parm_handlers[];
3874 static struct redisplay_interface ns_redisplay_interface =
3876 ns_frame_parm_handlers,
3880 x_clear_end_of_line,
3882 ns_after_update_window_line,
3883 ns_update_window_begin,
3884 ns_update_window_end,
3887 0, /* flush_display_optional */
3888 x_clear_window_mouse_face,
3889 x_get_glyph_overhangs,
3890 x_fix_overlapping_area,
3891 ns_draw_fringe_bitmap,
3892 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
3893 0, /* destroy_fringe_bitmap */
3894 ns_compute_glyph_string_overhangs,
3895 ns_draw_glyph_string, /* interface to nsfont.m */
3896 ns_define_frame_cursor,
3897 ns_clear_frame_area,
3898 ns_draw_window_cursor,
3899 ns_draw_vertical_window_border,
3900 ns_shift_glyphs_for_insert
3905 ns_delete_display (struct ns_display_info *dpyinfo)
3911 /* This function is called when the last frame on a display is deleted. */
3913 ns_delete_terminal (struct terminal *terminal)
3915 struct ns_display_info *dpyinfo = terminal->display_info.ns;
3917 /* Protect against recursive calls. delete_frame in
3918 delete_terminal calls us back when it deletes our last frame. */
3919 if (!terminal->name)
3924 x_destroy_all_bitmaps (dpyinfo);
3925 ns_delete_display (dpyinfo);
3930 static struct terminal *
3931 ns_create_terminal (struct ns_display_info *dpyinfo)
3932 /* --------------------------------------------------------------------------
3933 Set up use of NS before we make the first connection.
3934 -------------------------------------------------------------------------- */
3936 struct terminal *terminal;
3938 NSTRACE (ns_create_terminal);
3940 terminal = create_terminal ();
3942 terminal->type = output_ns;
3943 terminal->display_info.ns = dpyinfo;
3944 dpyinfo->terminal = terminal;
3946 terminal->rif = &ns_redisplay_interface;
3948 terminal->clear_frame_hook = ns_clear_frame;
3949 terminal->ins_del_lines_hook = 0; /* XXX vestigial? */
3950 terminal->delete_glyphs_hook = 0; /* XXX vestigial? */
3951 terminal->ring_bell_hook = ns_ring_bell;
3952 terminal->reset_terminal_modes_hook = ns_reset_terminal_modes;
3953 terminal->set_terminal_modes_hook = ns_set_terminal_modes;
3954 terminal->update_begin_hook = ns_update_begin;
3955 terminal->update_end_hook = ns_update_end;
3956 terminal->set_terminal_window_hook = NULL; /* XXX vestigial? */
3957 terminal->read_socket_hook = ns_read_socket;
3958 terminal->frame_up_to_date_hook = ns_frame_up_to_date;
3959 terminal->mouse_position_hook = ns_mouse_position;
3960 terminal->frame_rehighlight_hook = ns_frame_rehighlight;
3961 terminal->frame_raise_lower_hook = ns_frame_raise_lower;
3963 terminal->fullscreen_hook = ns_fullscreen_hook;
3965 terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
3966 terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
3967 terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
3968 terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
3970 terminal->delete_frame_hook = x_destroy_window;
3971 terminal->delete_terminal_hook = ns_delete_terminal;
3973 terminal->scroll_region_ok = 1;
3974 terminal->char_ins_del_ok = 1;
3975 terminal->line_ins_del_ok = 1;
3976 terminal->fast_clear_end_of_line = 1;
3977 terminal->memory_below_frame = 0;
3983 struct ns_display_info *
3984 ns_term_init (Lisp_Object display_name)
3985 /* --------------------------------------------------------------------------
3986 Start the Application and get things rolling.
3987 -------------------------------------------------------------------------- */
3989 struct terminal *terminal;
3990 struct ns_display_info *dpyinfo;
3991 static int ns_initialized = 0;
3994 if (ns_initialized) return x_display_list;
3997 NSTRACE (ns_term_init);
3999 [outerpool release];
4000 outerpool = [[NSAutoreleasePool alloc] init];
4002 /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4003 /*GSDebugAllocationActive (YES); */
4007 Fset_input_interrupt_mode (Qnil);
4009 if (selfds[0] == -1)
4011 if (pipe (selfds) == -1)
4013 fprintf (stderr, "Failed to create pipe: %s\n",
4014 emacs_strerror (errno));
4018 fcntl (selfds[0], F_SETFL, O_NONBLOCK|fcntl (selfds[0], F_GETFL));
4019 FD_ZERO (&select_readfds);
4020 FD_ZERO (&select_writefds);
4021 pthread_mutex_init (&select_mutex, NULL);
4024 ns_pending_files = [[NSMutableArray alloc] init];
4025 ns_pending_service_names = [[NSMutableArray alloc] init];
4026 ns_pending_service_args = [[NSMutableArray alloc] init];
4028 /* Start app and create the main menu, window, view.
4029 Needs to be here because ns_initialize_display_info () uses AppKit classes.
4030 The view will then ask the NSApp to stop and return to Emacs. */
4031 [EmacsApp sharedApplication];
4034 [NSApp setDelegate: NSApp];
4036 /* Start the select thread. */
4037 [NSThread detachNewThreadSelector:@selector (fd_handler:)
4041 /* debugging: log all notifications */
4042 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
4043 selector: @selector (logNotification:)
4044 name: nil object: nil]; */
4046 dpyinfo = xzalloc (sizeof *dpyinfo);
4048 ns_initialize_display_info (dpyinfo);
4049 terminal = ns_create_terminal (dpyinfo);
4051 terminal->kboard = xmalloc (sizeof *terminal->kboard);
4052 init_kboard (terminal->kboard);
4053 kset_window_system (terminal->kboard, Qns);
4054 terminal->kboard->next_kboard = all_kboards;
4055 all_kboards = terminal->kboard;
4056 /* Don't let the initial kboard remain current longer than necessary.
4057 That would cause problems if a file loaded on startup tries to
4058 prompt in the mini-buffer. */
4059 if (current_kboard == initial_kboard)
4060 current_kboard = terminal->kboard;
4061 terminal->kboard->reference_count++;
4063 dpyinfo->next = x_display_list;
4064 x_display_list = dpyinfo;
4066 /* Put it on ns_display_name_list */
4067 ns_display_name_list = Fcons (Fcons (display_name, Qnil),
4068 ns_display_name_list);
4069 dpyinfo->name_list_element = XCAR (ns_display_name_list);
4071 terminal->name = xstrdup (SSDATA (display_name));
4075 if (!inhibit_x_resources)
4077 ns_default ("GSFontAntiAlias", &ns_antialias_text,
4080 /* this is a standard variable */
4081 ns_default ("AppleAntiAliasingThreshold", &tmp,
4082 make_float (10.0), make_float (6.0), YES, NO);
4083 ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4086 ns_selection_color = [[NSUserDefaults standardUserDefaults]
4087 stringForKey: @"AppleHighlightColor"];
4088 if (ns_selection_color == nil)
4089 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
4092 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4096 Lisp_Object color_file, color_map, color;
4100 color_file = Fexpand_file_name (build_string ("rgb.txt"),
4101 Fsymbol_value (intern ("data-directory")));
4102 if (NILP (Ffile_readable_p (color_file)))
4103 fatal ("Could not find %s.\n", SDATA (color_file));
4105 color_map = Fx_load_color_file (color_file);
4106 if (NILP (color_map))
4107 fatal ("Could not read %s.\n", SDATA (color_file));
4109 cl = [[NSColorList alloc] initWithName: @"Emacs"];
4110 for ( ; CONSP (color_map); color_map = XCDR (color_map))
4112 color = XCAR (color_map);
4113 name = SSDATA (XCAR (color));
4114 c = XINT (XCDR (color));
4116 [NSColor colorWithCalibratedRed: RED_FROM_ULONG (c) / 255.0
4117 green: GREEN_FROM_ULONG (c) / 255.0
4118 blue: BLUE_FROM_ULONG (c) / 255.0
4120 forKey: [NSString stringWithUTF8String: name]];
4122 [cl writeToFile: nil];
4127 #ifdef NS_IMPL_GNUSTEP
4128 Vwindow_system_version = build_string (gnustep_base_version);
4130 /*PSnextrelease (128, c); */
4131 char c[DBL_BUFSIZE_BOUND];
4132 int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4133 Vwindow_system_version = make_unibyte_string (c, len);
4137 delete_keyboard_wait_descriptor (0);
4139 ns_app_name = [[NSProcessInfo processInfo] processName];
4141 /* Set up OS X app menu */
4142 #ifdef NS_IMPL_COCOA
4146 /* set up the application menu */
4147 svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4148 [svcsMenu setAutoenablesItems: NO];
4149 appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4150 [appMenu setAutoenablesItems: NO];
4151 mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4152 dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4154 [appMenu insertItemWithTitle: @"About Emacs"
4155 action: @selector (orderFrontStandardAboutPanel:)
4158 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4159 [appMenu insertItemWithTitle: @"Preferences..."
4160 action: @selector (showPreferencesWindow:)
4163 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4164 item = [appMenu insertItemWithTitle: @"Services"
4165 action: @selector (menuDown:)
4168 [appMenu setSubmenu: svcsMenu forItem: item];
4169 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4170 [appMenu insertItemWithTitle: @"Hide Emacs"
4171 action: @selector (hide:)
4174 item = [appMenu insertItemWithTitle: @"Hide Others"
4175 action: @selector (hideOtherApplications:)
4178 [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4179 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4180 [appMenu insertItemWithTitle: @"Quit Emacs"
4181 action: @selector (terminate:)
4185 item = [mainMenu insertItemWithTitle: ns_app_name
4186 action: @selector (menuDown:)
4189 [mainMenu setSubmenu: appMenu forItem: item];
4190 [dockMenu insertItemWithTitle: @"New Frame"
4191 action: @selector (newFrame:)
4195 [NSApp setMainMenu: mainMenu];
4196 [NSApp setAppleMenu: appMenu];
4197 [NSApp setServicesMenu: svcsMenu];
4198 /* Needed at least on Cocoa, to get dock menu to show windows */
4199 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4201 [[NSNotificationCenter defaultCenter]
4202 addObserver: mainMenu
4203 selector: @selector (trackingNotification:)
4204 name: NSMenuDidBeginTrackingNotification object: mainMenu];
4205 [[NSNotificationCenter defaultCenter]
4206 addObserver: mainMenu
4207 selector: @selector (trackingNotification:)
4208 name: NSMenuDidEndTrackingNotification object: mainMenu];
4210 #endif /* MAC OS X menu setup */
4212 /* Register our external input/output types, used for determining
4213 applicable services and also drag/drop eligibility. */
4214 ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
4215 ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
4217 ns_drag_types = [[NSArray arrayWithObjects:
4219 NSTabularTextPboardType,
4220 NSFilenamesPboardType,
4223 NSFontPboardType, nil] retain];
4225 #ifndef NEW_STYLE_FS
4226 /* If fullscreen is in init/default-frame-alist, focus isn't set
4227 right for fullscreen windows, so set this. */
4228 [NSApp activateIgnoringOtherApps:YES];
4232 ns_do_open_file = YES;
4238 ns_term_shutdown (int sig)
4240 [[NSUserDefaults standardUserDefaults] synchronize];
4242 /* code not reached in emacs.c after this is called by shut_down_emacs: */
4243 if (STRINGP (Vauto_save_list_file_name))
4244 unlink (SSDATA (Vauto_save_list_file_name));
4246 if (sig == 0 || sig == SIGTERM)
4248 [NSApp terminate: NSApp];
4250 else // force a stack trace to happen
4257 /* ==========================================================================
4259 EmacsApp implementation
4261 ========================================================================== */
4264 @implementation EmacsApp
4266 - (void)logNotification: (NSNotification *)notification
4268 const char *name = [[notification name] UTF8String];
4269 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4270 && !strstr (name, "WindowNumber"))
4271 NSLog (@"notification: '%@'", [notification name]);
4275 - (void)sendEvent: (NSEvent *)theEvent
4276 /* --------------------------------------------------------------------------
4277 Called when NSApp is running for each event received. Used to stop
4278 the loop when we choose, since there's no way to just run one iteration.
4279 -------------------------------------------------------------------------- */
4281 int type = [theEvent type];
4282 NSWindow *window = [theEvent window];
4283 /* NSTRACE (sendEvent); */
4284 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4286 #ifdef NS_IMPL_COCOA
4287 if (type == NSApplicationDefined
4288 && [theEvent data2] == NSAPP_DATA2_RUNASSCRIPT)
4296 if (type == NSCursorUpdate && window == nil)
4298 fprintf (stderr, "Dropping external cursor update event.\n");
4302 if (type == NSApplicationDefined)
4304 /* Events posted by ns_send_appdefined interrupt the run loop here.
4305 But, if a modal window is up, an appdefined can still come through,
4306 (e.g., from a makeKeyWindow event) but stopping self also stops the
4307 modal loop. Just defer it until later. */
4308 if ([NSApp modalWindow] == nil)
4310 last_appdefined_event = theEvent;
4315 send_appdefined = YES;
4319 [super sendEvent: theEvent];
4323 - (void)showPreferencesWindow: (id)sender
4325 struct frame *emacsframe = SELECTED_FRAME ();
4326 NSEvent *theEvent = [NSApp currentEvent];
4330 emacs_event->kind = NS_NONKEY_EVENT;
4331 emacs_event->code = KEY_NS_SHOW_PREFS;
4332 emacs_event->modifiers = 0;
4333 EV_TRAILER (theEvent);
4337 - (void)newFrame: (id)sender
4339 struct frame *emacsframe = SELECTED_FRAME ();
4340 NSEvent *theEvent = [NSApp currentEvent];
4344 emacs_event->kind = NS_NONKEY_EVENT;
4345 emacs_event->code = KEY_NS_NEW_FRAME;
4346 emacs_event->modifiers = 0;
4347 EV_TRAILER (theEvent);
4351 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4352 - (BOOL) openFile: (NSString *)fileName
4354 struct frame *emacsframe = SELECTED_FRAME ();
4355 NSEvent *theEvent = [NSApp currentEvent];
4360 emacs_event->kind = NS_NONKEY_EVENT;
4361 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4362 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4363 ns_input_line = Qnil; /* can be start or cons start,end */
4364 emacs_event->modifiers =0;
4365 EV_TRAILER (theEvent);
4371 /* **************************************************************************
4373 EmacsApp delegate implementation
4375 ************************************************************************** */
4377 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4378 /* --------------------------------------------------------------------------
4379 When application is loaded, terminate event loop in ns_term_init
4380 -------------------------------------------------------------------------- */
4382 NSTRACE (applicationDidFinishLaunching);
4383 [NSApp setServicesProvider: NSApp];
4384 ns_send_appdefined (-2);
4388 /* Termination sequences:
4391 MenuBar | File | Exit:
4392 Select Quit from App menubar:
4394 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4397 Select Quit from Dock menu:
4400 Cancel -> Nothing else
4404 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4409 - (void) terminate: (id)sender
4411 struct frame *emacsframe = SELECTED_FRAME ();
4416 emacs_event->kind = NS_NONKEY_EVENT;
4417 emacs_event->code = KEY_NS_POWER_OFF;
4418 emacs_event->arg = Qt; /* mark as non-key event */
4419 EV_TRAILER ((id)nil);
4423 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4427 if (NILP (ns_confirm_quit)) // || ns_shutdown_properly --> TO DO
4428 return NSTerminateNow;
4430 ret = NSRunAlertPanel(ns_app_name,
4431 @"Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?",
4432 @"Save Buffers and Exit", @"Cancel", nil);
4434 if (ret == NSAlertDefaultReturn)
4435 return NSTerminateNow;
4436 else if (ret == NSAlertAlternateReturn)
4437 return NSTerminateCancel;
4438 return NSTerminateNow; /* just in case */
4442 not_in_argv (NSString *arg)
4445 const char *a = [arg UTF8String];
4446 for (k = 1; k < initial_argc; ++k)
4447 if (strcmp (a, initial_argv[k]) == 0) return 0;
4451 /* Notification from the Workspace to open a file */
4452 - (BOOL)application: sender openFile: (NSString *)file
4454 if (ns_do_open_file || not_in_argv (file))
4455 [ns_pending_files addObject: file];
4460 /* Open a file as a temporary file */
4461 - (BOOL)application: sender openTempFile: (NSString *)file
4463 if (ns_do_open_file || not_in_argv (file))
4464 [ns_pending_files addObject: file];
4469 /* Notification from the Workspace to open a file noninteractively (?) */
4470 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4472 if (ns_do_open_file || not_in_argv (file))
4473 [ns_pending_files addObject: file];
4477 /* Notification from the Workspace to open multiple files */
4478 - (void)application: sender openFiles: (NSArray *)fileList
4480 NSEnumerator *files = [fileList objectEnumerator];
4482 /* Don't open files from the command line unconditionally,
4483 Cocoa parses the command line wrong, --option value tries to open value
4484 if --option is the last option. */
4485 while ((file = [files nextObject]) != nil)
4486 if (ns_do_open_file || not_in_argv (file))
4487 [ns_pending_files addObject: file];
4489 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4494 /* Handle dock menu requests. */
4495 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4501 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4502 - (void)applicationWillBecomeActive: (NSNotification *)notification
4504 //ns_app_active=YES;
4506 - (void)applicationDidBecomeActive: (NSNotification *)notification
4508 NSTRACE (applicationDidBecomeActive);
4510 //ns_app_active=YES;
4512 ns_update_auto_hide_menu_bar ();
4513 // No constraining takes place when the application is not active.
4514 ns_constrain_all_frames ();
4516 - (void)applicationDidResignActive: (NSNotification *)notification
4519 ns_send_appdefined (-1);
4524 /* ==========================================================================
4526 EmacsApp aux handlers for managing event loop
4528 ========================================================================== */
4531 - (void)timeout_handler: (NSTimer *)timedEntry
4532 /* --------------------------------------------------------------------------
4533 The timeout specified to ns_select has passed.
4534 -------------------------------------------------------------------------- */
4536 /*NSTRACE (timeout_handler); */
4537 ns_send_appdefined (-2);
4540 - (void)fd_handler:(id)unused
4541 /* --------------------------------------------------------------------------
4542 Check data waiting on file descriptors and terminate if so
4543 -------------------------------------------------------------------------- */
4546 int waiting = 1, nfds;
4549 SELECT_TYPE readfds, writefds, *wfds;
4550 EMACS_TIME timeout, *tmo;
4551 NSAutoreleasePool *pool = nil;
4553 /* NSTRACE (fd_handler); */
4558 pool = [[NSAutoreleasePool alloc] init];
4564 FD_SET (selfds[0], &fds);
4565 result = select (selfds[0]+1, &fds, NULL, NULL, NULL);
4568 read (selfds[0], &c, 1);
4569 if (c == 'g') waiting = 0;
4574 pthread_mutex_lock (&select_mutex);
4577 if (select_valid & SELECT_HAVE_READ)
4578 readfds = select_readfds;
4582 if (select_valid & SELECT_HAVE_WRITE)
4584 writefds = select_writefds;
4589 if (select_valid & SELECT_HAVE_TMO)
4591 timeout = select_timeout;
4597 pthread_mutex_unlock (&select_mutex);
4599 FD_SET (selfds[0], &readfds);
4600 if (selfds[0] >= nfds) nfds = selfds[0]+1;
4602 result = pselect (nfds, &readfds, wfds, NULL, tmo, NULL);
4605 ns_send_appdefined (-2);
4606 else if (result > 0)
4608 if (FD_ISSET (selfds[0], &readfds))
4610 read (selfds[0], &c, 1);
4611 if (c == 's') waiting = 1;
4615 pthread_mutex_lock (&select_mutex);
4616 if (select_valid & SELECT_HAVE_READ)
4617 select_readfds = readfds;
4618 if (select_valid & SELECT_HAVE_WRITE)
4619 select_writefds = writefds;
4620 if (select_valid & SELECT_HAVE_TMO)
4621 select_timeout = timeout;
4622 pthread_mutex_unlock (&select_mutex);
4624 ns_send_appdefined (result);
4634 /* ==========================================================================
4638 ========================================================================== */
4640 /* called from system: queue for next pass through event loop */
4641 - (void)requestService: (NSPasteboard *)pboard
4642 userData: (NSString *)userData
4643 error: (NSString **)error
4645 [ns_pending_service_names addObject: userData];
4646 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
4647 SSDATA (ns_string_from_pasteboard (pboard))]];
4651 /* called from ns_read_socket to clear queue */
4652 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
4654 struct frame *emacsframe = SELECTED_FRAME ();
4655 NSEvent *theEvent = [NSApp currentEvent];
4660 emacs_event->kind = NS_NONKEY_EVENT;
4661 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
4662 ns_input_spi_name = build_string ([name UTF8String]);
4663 ns_input_spi_arg = build_string ([arg UTF8String]);
4664 emacs_event->modifiers = EV_MODIFIERS (theEvent);
4665 EV_TRAILER (theEvent);
4675 /* ==========================================================================
4677 EmacsView implementation
4679 ========================================================================== */
4682 @implementation EmacsView
4684 /* needed to inform when window closed from LISP */
4685 - (void) setWindowClosing: (BOOL)closing
4687 windowClosing = closing;
4693 NSTRACE (EmacsView_dealloc);
4695 if (fs_state == FULLSCREEN_BOTH)
4696 [nonfs_window release];
4701 /* called on font panel selection */
4702 - (void)changeFont: (id)sender
4704 NSEvent *e =[[self window] currentEvent];
4705 struct face *face =FRAME_DEFAULT_FACE (emacsframe);
4709 NSTRACE (changeFont);
4713 if ((newFont = [sender convertFont:
4714 ((struct nsfont_info *)face->font)->nsfont]))
4716 SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
4718 emacs_event->kind = NS_NONKEY_EVENT;
4719 emacs_event->modifiers = 0;
4720 emacs_event->code = KEY_NS_CHANGE_FONT;
4722 size = [newFont pointSize];
4723 ns_input_fontsize = make_number (lrint (size));
4724 ns_input_font = build_string ([[newFont familyName] UTF8String]);
4730 - (BOOL)acceptsFirstResponder
4732 NSTRACE (acceptsFirstResponder);
4737 - (void)resetCursorRects
4739 NSRect visible = [self visibleRect];
4740 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
4741 NSTRACE (resetCursorRects);
4743 if (currentCursor == nil)
4744 currentCursor = [NSCursor arrowCursor];
4746 if (!NSIsEmptyRect (visible))
4747 [self addCursorRect: visible cursor: currentCursor];
4748 [currentCursor setOnMouseEntered: YES];
4753 /*****************************************************************************/
4754 /* Keyboard handling. */
4757 - (void)keyDown: (NSEvent *)theEvent
4759 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
4761 unsigned fnKeysym = 0;
4763 static NSMutableArray *nsEvArray;
4764 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
4765 static BOOL firstTime = YES;
4771 /* Rhapsody and OS X give up and down events for the arrow keys */
4772 if (ns_fake_keydown == YES)
4773 ns_fake_keydown = NO;
4774 else if ([theEvent type] != NSKeyDown)
4780 if (![[self window] isKeyWindow]
4781 && [[theEvent window] isKindOfClass: [EmacsWindow class]]
4782 /* we must avoid an infinite loop here. */
4783 && (EmacsView *)[[theEvent window] delegate] != self)
4785 /* XXX: There is an occasional condition in which, when Emacs display
4786 updates a different frame from the current one, and temporarily
4787 selects it, then processes some interrupt-driven input
4788 (dispnew.c:3878), OS will send the event to the correct NSWindow, but
4789 for some reason that window has its first responder set to the NSView
4790 most recently updated (I guess), which is not the correct one. */
4791 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
4795 if (nsEvArray == nil)
4796 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
4798 [NSCursor setHiddenUntilMouseMoves: YES];
4800 if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
4802 clear_mouse_face (hlinfo);
4803 hlinfo->mouse_face_hidden = 1;
4806 if (!processingCompose)
4808 /* When using screen sharing, no left or right information is sent,
4809 so use Left key in those cases. */
4810 int is_left_key, is_right_key;
4812 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
4813 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
4815 /* (Carbon way: [theEvent keyCode]) */
4817 /* is it a "function key"? */
4818 fnKeysym = ns_convert_key (code);
4821 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
4822 because Emacs treats Delete and KP-Delete same (in simple.el). */
4823 if (fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
4824 code = 0xFF08; /* backspace */
4829 /* are there modifiers? */
4830 emacs_event->modifiers = 0;
4831 flags = [theEvent modifierFlags];
4833 if (flags & NSHelpKeyMask)
4834 emacs_event->modifiers |= hyper_modifier;
4836 if (flags & NSShiftKeyMask)
4837 emacs_event->modifiers |= shift_modifier;
4839 is_right_key = (flags & NSRightCommandKeyMask) == NSRightCommandKeyMask;
4840 is_left_key = (flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask
4841 || (! is_right_key && (flags & NSCommandKeyMask) == NSCommandKeyMask);
4844 emacs_event->modifiers |= parse_solitary_modifier
4845 (EQ (ns_right_command_modifier, Qleft)
4846 ? ns_command_modifier
4847 : ns_right_command_modifier);
4851 emacs_event->modifiers |= parse_solitary_modifier
4852 (ns_command_modifier);
4854 /* if super (default), take input manager's word so things like
4855 dvorak / qwerty layout work */
4856 if (EQ (ns_command_modifier, Qsuper)
4858 && [[theEvent characters] length] != 0)
4860 /* XXX: the code we get will be unshifted, so if we have
4861 a shift modifier, must convert ourselves */
4862 if (!(flags & NSShiftKeyMask))
4863 code = [[theEvent characters] characterAtIndex: 0];
4865 /* this is ugly and also requires linking w/Carbon framework
4866 (for LMGetKbdType) so for now leave this rare (?) case
4867 undealt with.. in future look into CGEvent methods */
4870 long smv = GetScriptManagerVariable (smKeyScript);
4871 Handle uchrHandle = GetResource
4872 ('uchr', GetScriptVariable (smv, smScriptKeys));
4874 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
4875 [[theEvent characters] characterAtIndex: 0],
4876 kUCKeyActionDisplay,
4877 (flags & ~NSCommandKeyMask) >> 8,
4878 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
4879 &dummy, 1, &dummy, &code);
4886 is_right_key = (flags & NSRightControlKeyMask) == NSRightControlKeyMask;
4887 is_left_key = (flags & NSLeftControlKeyMask) == NSLeftControlKeyMask
4888 || (! is_right_key && (flags & NSControlKeyMask) == NSControlKeyMask);
4891 emacs_event->modifiers |= parse_solitary_modifier
4892 (EQ (ns_right_control_modifier, Qleft)
4893 ? ns_control_modifier
4894 : ns_right_control_modifier);
4897 emacs_event->modifiers |= parse_solitary_modifier
4898 (ns_control_modifier);
4900 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
4901 emacs_event->modifiers |=
4902 parse_solitary_modifier (ns_function_modifier);
4904 left_is_none = NILP (ns_alternate_modifier)
4905 || EQ (ns_alternate_modifier, Qnone);
4907 is_right_key = (flags & NSRightAlternateKeyMask)
4908 == NSRightAlternateKeyMask;
4909 is_left_key = (flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask
4911 && (flags & NSAlternateKeyMask) == NSAlternateKeyMask);
4915 if ((NILP (ns_right_alternate_modifier)
4916 || EQ (ns_right_alternate_modifier, Qnone)
4917 || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
4919 { /* accept pre-interp alt comb */
4920 if ([[theEvent characters] length] > 0)
4921 code = [[theEvent characters] characterAtIndex: 0];
4922 /*HACK: clear lone shift modifier to stop next if from firing */
4923 if (emacs_event->modifiers == shift_modifier)
4924 emacs_event->modifiers = 0;
4927 emacs_event->modifiers |= parse_solitary_modifier
4928 (EQ (ns_right_alternate_modifier, Qleft)
4929 ? ns_alternate_modifier
4930 : ns_right_alternate_modifier);
4933 if (is_left_key) /* default = meta */
4935 if (left_is_none && !fnKeysym)
4936 { /* accept pre-interp alt comb */
4937 if ([[theEvent characters] length] > 0)
4938 code = [[theEvent characters] characterAtIndex: 0];
4939 /*HACK: clear lone shift modifier to stop next if from firing */
4940 if (emacs_event->modifiers == shift_modifier)
4941 emacs_event->modifiers = 0;
4944 emacs_event->modifiers |=
4945 parse_solitary_modifier (ns_alternate_modifier);
4949 fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
4950 code, fnKeysym, flags, emacs_event->modifiers);
4952 /* if it was a function key or had modifiers, pass it directly to emacs */
4953 if (fnKeysym || (emacs_event->modifiers
4954 && (emacs_event->modifiers != shift_modifier)
4955 && [[theEvent charactersIgnoringModifiers] length] > 0))
4956 /*[[theEvent characters] length] */
4958 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4960 code |= (1<<28)|(3<<16);
4961 else if (code == 0x7f)
4962 code |= (1<<28)|(3<<16);
4964 emacs_event->kind = code > 0xFF
4965 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4967 emacs_event->code = code;
4968 EV_TRAILER (theEvent);
4974 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
4975 /* if we get here we should send the key for input manager processing */
4976 if (firstTime && [[NSInputManager currentInputManager]
4977 wantsToDelayTextChangeNotifications] == NO)
4979 "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
4982 if (NS_KEYLOG && !processingCompose)
4983 fprintf (stderr, "keyDown: Begin compose sequence.\n");
4985 processingCompose = YES;
4986 [nsEvArray addObject: theEvent];
4987 [self interpretKeyEvents: nsEvArray];
4988 [nsEvArray removeObject: theEvent];
4992 #ifdef NS_IMPL_COCOA
4993 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
4994 decided not to send key-down for.
4995 See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
4996 This only applies on Tiger and earlier.
4997 If it matches one of these, send it on to keyDown. */
4998 -(void)keyUp: (NSEvent *)theEvent
5000 int flags = [theEvent modifierFlags];
5001 int code = [theEvent keyCode];
5002 if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
5003 code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
5006 fprintf (stderr, "keyUp: passed test");
5007 ns_fake_keydown = YES;
5008 [self keyDown: theEvent];
5014 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
5017 /* <NSTextInput>: called when done composing;
5018 NOTE: also called when we delete over working text, followed immed.
5019 by doCommandBySelector: deleteBackward: */
5020 - (void)insertText: (id)aString
5023 int len = [(NSString *)aString length];
5027 NSLog (@"insertText '%@'\tlen = %d", aString, len);
5028 processingCompose = NO;
5033 /* first, clear any working text */
5034 if (workingText != nil)
5035 [self deleteWorkingText];
5037 /* now insert the string as keystrokes */
5038 for (i =0; i<len; i++)
5040 code = [aString characterAtIndex: i];
5041 /* TODO: still need this? */
5043 code = '~'; /* 0x7E */
5044 if (code != 32) /* Space */
5045 emacs_event->modifiers = 0;
5047 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5048 emacs_event->code = code;
5049 EV_TRAILER ((id)nil);
5054 /* <NSTextInput>: inserts display of composing characters */
5055 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
5057 NSString *str = [aString respondsToSelector: @selector (string)] ?
5058 [aString string] : aString;
5060 NSLog (@"setMarkedText '%@' len =%d range %d from %d", str, [str length],
5061 selRange.length, selRange.location);
5063 if (workingText != nil)
5064 [self deleteWorkingText];
5065 if ([str length] == 0)
5071 processingCompose = YES;
5072 workingText = [str copy];
5073 ns_working_text = build_string ([workingText UTF8String]);
5075 emacs_event->kind = NS_TEXT_EVENT;
5076 emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
5077 EV_TRAILER ((id)nil);
5081 /* delete display of composing characters [not in <NSTextInput>] */
5082 - (void)deleteWorkingText
5084 if (workingText == nil)
5087 NSLog(@"deleteWorkingText len =%d\n", [workingText length]);
5088 [workingText release];
5090 processingCompose = NO;
5095 emacs_event->kind = NS_TEXT_EVENT;
5096 emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
5097 EV_TRAILER ((id)nil);
5101 - (BOOL)hasMarkedText
5103 return workingText != nil;
5107 - (NSRange)markedRange
5109 NSRange rng = workingText != nil
5110 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
5112 NSLog (@"markedRange request");
5120 NSLog (@"unmark (accept) text");
5121 [self deleteWorkingText];
5122 processingCompose = NO;
5126 /* used to position char selection windows, etc. */
5127 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
5131 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
5133 NSLog (@"firstRectForCharRange request");
5135 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
5136 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
5137 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
5138 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
5139 +FRAME_LINE_HEIGHT (emacsframe));
5141 pt = [self convertPoint: pt toView: nil];
5142 pt = [[self window] convertBaseToScreen: pt];
5148 - (NSInteger)conversationIdentifier
5150 return (NSInteger)self;
5154 - (void)doCommandBySelector: (SEL)aSelector
5157 NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
5159 if (aSelector == @selector (deleteBackward:))
5161 /* happens when user backspaces over an ongoing composition:
5162 throw a 'delete' into the event queue */
5165 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5166 emacs_event->code = 0xFF08;
5167 EV_TRAILER ((id)nil);
5171 - (NSArray *)validAttributesForMarkedText
5173 static NSArray *arr = nil;
5174 if (arr == nil) arr = [NSArray new];
5175 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
5179 - (NSRange)selectedRange
5182 NSLog (@"selectedRange request");
5183 return NSMakeRange (NSNotFound, 0);
5186 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
5189 NSLog (@"characterIndexForPoint request");
5193 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
5195 static NSAttributedString *str = nil;
5196 if (str == nil) str = [NSAttributedString new];
5198 NSLog (@"attributedSubstringFromRange request");
5202 /* End <NSTextInput> impl. */
5203 /*****************************************************************************/
5206 /* This is what happens when the user presses a mouse button. */
5207 - (void)mouseDown: (NSEvent *)theEvent
5209 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5211 NSTRACE (mouseDown);
5213 [self deleteWorkingText];
5218 last_mouse_frame = emacsframe;
5219 /* appears to be needed to prevent spurious movement events generated on
5221 last_mouse_frame->mouse_moved = 0;
5223 if ([theEvent type] == NSScrollWheel)
5225 float delta = [theEvent deltaY];
5226 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
5229 emacs_event->kind = WHEEL_EVENT;
5230 emacs_event->code = 0;
5231 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
5232 ((delta > 0) ? up_modifier : down_modifier);
5236 emacs_event->kind = MOUSE_CLICK_EVENT;
5237 emacs_event->code = EV_BUTTON (theEvent);
5238 emacs_event->modifiers = EV_MODIFIERS (theEvent)
5239 | EV_UDMODIFIERS (theEvent);
5241 XSETINT (emacs_event->x, lrint (p.x));
5242 XSETINT (emacs_event->y, lrint (p.y));
5243 EV_TRAILER (theEvent);
5247 - (void)rightMouseDown: (NSEvent *)theEvent
5249 NSTRACE (rightMouseDown);
5250 [self mouseDown: theEvent];
5254 - (void)otherMouseDown: (NSEvent *)theEvent
5256 NSTRACE (otherMouseDown);
5257 [self mouseDown: theEvent];
5261 - (void)mouseUp: (NSEvent *)theEvent
5264 [self mouseDown: theEvent];
5268 - (void)rightMouseUp: (NSEvent *)theEvent
5270 NSTRACE (rightMouseUp);
5271 [self mouseDown: theEvent];
5275 - (void)otherMouseUp: (NSEvent *)theEvent
5277 NSTRACE (otherMouseUp);
5278 [self mouseDown: theEvent];
5282 - (void) scrollWheel: (NSEvent *)theEvent
5284 NSTRACE (scrollWheel);
5285 [self mouseDown: theEvent];
5289 /* Tell emacs the mouse has moved. */
5290 - (void)mouseMoved: (NSEvent *)e
5292 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5295 // NSTRACE (mouseMoved);
5297 last_mouse_movement_time = EV_TIMESTAMP (e);
5298 last_mouse_motion_position
5299 = [self convertPoint: [e locationInWindow] fromView: nil];
5301 /* update any mouse face */
5302 if (hlinfo->mouse_face_hidden)
5304 hlinfo->mouse_face_hidden = 0;
5305 clear_mouse_face (hlinfo);
5308 /* tooltip handling */
5309 previous_help_echo_string = help_echo_string;
5310 help_echo_string = Qnil;
5312 if (!note_mouse_movement (emacsframe, last_mouse_motion_position.x,
5313 last_mouse_motion_position.y))
5314 help_echo_string = previous_help_echo_string;
5316 XSETFRAME (frame, emacsframe);
5317 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
5319 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
5320 (note_mouse_highlight), which is called through the
5321 note_mouse_movement () call above */
5322 gen_help_event (help_echo_string, frame, help_echo_window,
5323 help_echo_object, help_echo_pos);
5327 help_echo_string = Qnil;
5328 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
5331 if (emacsframe->mouse_moved && send_appdefined)
5332 ns_send_appdefined (-1);
5336 - (void)mouseDragged: (NSEvent *)e
5338 NSTRACE (mouseDragged);
5339 [self mouseMoved: e];
5343 - (void)rightMouseDragged: (NSEvent *)e
5345 NSTRACE (rightMouseDragged);
5346 [self mouseMoved: e];
5350 - (void)otherMouseDragged: (NSEvent *)e
5352 NSTRACE (otherMouseDragged);
5353 [self mouseMoved: e];
5357 - (BOOL)windowShouldClose: (id)sender
5359 NSEvent *e =[[self window] currentEvent];
5361 NSTRACE (windowShouldClose);
5362 windowClosing = YES;
5365 emacs_event->kind = DELETE_WINDOW_EVENT;
5366 emacs_event->modifiers = 0;
5367 emacs_event->code = 0;
5369 /* Don't close this window, let this be done from lisp code. */
5373 - (void) updateFrameSize: (BOOL) delay;
5375 NSWindow *window = [self window];
5376 NSRect wr = [window frame];
5377 #ifdef NS_IMPL_GNUSTEP
5383 int oldc = cols, oldr = rows;
5384 int oldw = FRAME_PIXEL_WIDTH (emacsframe),
5385 oldh = FRAME_PIXEL_HEIGHT (emacsframe);
5388 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, wr.size.width + extra);
5390 if (cols < MINWIDTH)
5393 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES
5394 (emacsframe, wr.size.height
5395 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe) + extra
5396 - FRAME_TOOLBAR_HEIGHT (emacsframe));
5398 if (rows < MINHEIGHT)
5401 neww = (int)wr.size.width - emacsframe->border_width;
5402 newh = ((int)wr.size.height
5403 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5404 - FRAME_TOOLBAR_HEIGHT (emacsframe));
5406 if (oldr != rows || oldc != cols || neww != oldw || newh != oldh)
5408 NSView *view = FRAME_NS_VIEW (emacsframe);
5409 FRAME_PIXEL_WIDTH (emacsframe) = neww;
5410 FRAME_PIXEL_HEIGHT (emacsframe) = newh;
5411 change_frame_size (emacsframe, rows, cols, 0, delay, 0);
5412 SET_FRAME_GARBAGED (emacsframe);
5413 cancel_mouse_face (emacsframe);
5414 [view setFrame: NSMakeRect (0, 0, neww, newh)];
5415 [self windowDidMove:nil]; // Update top/left.
5419 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
5420 /* normalize frame to gridded text size */
5422 NSTRACE (windowWillResize);
5423 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
5425 if (fs_state == FULLSCREEN_MAXIMIZED
5426 && (maximized_width != (int)frameSize.width
5427 || maximized_height != (int)frameSize.height))
5428 [self setFSValue: FULLSCREEN_NONE];
5429 else if (fs_state == FULLSCREEN_WIDTH
5430 && maximized_width != (int)frameSize.width)
5431 [self setFSValue: FULLSCREEN_NONE];
5432 else if (fs_state == FULLSCREEN_HEIGHT
5433 && maximized_height != (int)frameSize.height)
5434 [self setFSValue: FULLSCREEN_NONE];
5435 if (fs_state == FULLSCREEN_NONE)
5436 maximized_width = maximized_height = -1;
5438 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe,
5439 #ifdef NS_IMPL_GNUSTEP
5440 frameSize.width + 3);
5444 if (cols < MINWIDTH)
5447 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, frameSize.height
5448 #ifdef NS_IMPL_GNUSTEP
5449 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe) + 3
5450 - FRAME_TOOLBAR_HEIGHT (emacsframe));
5452 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5453 - FRAME_TOOLBAR_HEIGHT (emacsframe));
5455 if (rows < MINHEIGHT)
5457 #ifdef NS_IMPL_COCOA
5459 /* this sets window title to have size in it; the wm does this under GS */
5460 NSRect r = [[self window] frame];
5461 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
5472 NSWindow *window = [self window];
5475 const char *t = [[[self window] title] UTF8String];
5476 char *pos = strstr (t, " — ");
5479 old_title = xstrdup (t);
5481 size_title = xmalloc (strlen (old_title) + 40);
5482 esprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
5483 [window setTitle: [NSString stringWithUTF8String: size_title]];
5488 #endif /* NS_IMPL_COCOA */
5489 /*fprintf (stderr," ...size became %.0f x %.0f (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
5495 - (void)windowDidResize: (NSNotification *)notification
5498 #if !defined (NEW_STYLE_FS) && ! defined (NS_IMPL_GNUSTEP)
5499 NSWindow *theWindow = [notification object];
5500 /* We can get notification on the non-FS window when in fullscreen mode. */
5501 if ([self window] != theWindow) return;
5504 #ifdef NS_IMPL_GNUSTEP
5505 NSWindow *theWindow = [notification object];
5507 /* In GNUstep, at least currently, it's possible to get a didResize
5508 without getting a willResize.. therefore we need to act as if we got
5509 the willResize now */
5510 NSSize sz = [theWindow frame].size;
5511 sz = [self windowWillResize: theWindow toSize: sz];
5512 #endif /* NS_IMPL_GNUSTEP */
5514 NSTRACE (windowDidResize);
5515 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
5517 #ifdef NS_IMPL_COCOA
5523 #endif /* NS_IMPL_COCOA */
5525 if (cols > 0 && rows > 0)
5527 [self updateFrameSize: YES];
5530 ns_send_appdefined (-1);
5534 - (void)windowDidBecomeKey: (NSNotification *)notification
5535 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5537 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5538 struct frame *old_focus = dpyinfo->x_focus_frame;
5540 NSTRACE (windowDidBecomeKey);
5542 if (emacsframe != old_focus)
5543 dpyinfo->x_focus_frame = emacsframe;
5545 ns_frame_rehighlight (emacsframe);
5549 emacs_event->kind = FOCUS_IN_EVENT;
5550 EV_TRAILER ((id)nil);
5555 - (void)windowDidResignKey: (NSNotification *)notification
5556 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5558 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5559 NSTRACE (windowDidResignKey);
5561 if (dpyinfo->x_focus_frame == emacsframe)
5562 dpyinfo->x_focus_frame = 0;
5564 ns_frame_rehighlight (emacsframe);
5566 /* FIXME: for some reason needed on second and subsequent clicks away
5567 from sole-frame Emacs to get hollow box to show */
5568 if (!windowClosing && [[self window] isVisible] == YES)
5570 x_update_cursor (emacsframe, 1);
5571 x_set_frame_alpha (emacsframe);
5576 [self deleteWorkingText];
5577 emacs_event->kind = FOCUS_IN_EVENT;
5578 EV_TRAILER ((id)nil);
5583 - (void)windowWillMiniaturize: sender
5585 NSTRACE (windowWillMiniaturize);
5601 - initFrameFromEmacs: (struct frame *)f
5606 NSButton *toggleButton;
5611 NSTRACE (initFrameFromEmacs);
5614 processingCompose = NO;
5615 scrollbarsNeedingUpdate = 0;
5616 fs_state = FULLSCREEN_NONE;
5617 fs_before_fs = next_maximized = -1;
5618 maximized_width = maximized_height = -1;
5621 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
5623 ns_userRect = NSMakeRect (0, 0, 0, 0);
5624 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
5625 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
5626 [self initWithFrame: r];
5627 [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
5629 FRAME_NS_VIEW (f) = self;
5633 win = [[EmacsWindow alloc]
5634 initWithContentRect: r
5635 styleMask: (NSResizableWindowMask |
5636 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
5637 NSTitledWindowMask |
5639 NSMiniaturizableWindowMask |
5640 NSClosableWindowMask)
5641 backing: NSBackingStoreBuffered
5645 [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
5649 bwidth = f->border_width = wr.size.width - r.size.width;
5650 tibar_height = FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
5652 [win setAcceptsMouseMovedEvents: YES];
5653 [win setDelegate: self];
5654 [win useOptimizedDrawing: YES];
5656 sz.width = FRAME_COLUMN_WIDTH (f);
5657 sz.height = FRAME_LINE_HEIGHT (f);
5658 [win setResizeIncrements: sz];
5660 [[win contentView] addSubview: self];
5663 [self registerForDraggedTypes: ns_drag_types];
5666 name = [NSString stringWithUTF8String:
5667 NILP (tem) ? "Emacs" : SSDATA (tem)];
5668 [win setTitle: name];
5670 /* toolbar support */
5671 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
5672 [NSString stringWithFormat: @"Emacs Frame %d",
5674 [win setToolbar: toolbar];
5675 [toolbar setVisible: NO];
5676 #ifdef NS_IMPL_COCOA
5677 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
5678 [toggleButton setTarget: self];
5679 [toggleButton setAction: @selector (toggleToolbar: )];
5681 FRAME_TOOLBAR_HEIGHT (f) = 0;
5685 [win setMiniwindowTitle:
5686 [NSString stringWithUTF8String: SSDATA (tem)]];
5689 NSScreen *screen = [win screen];
5692 [win setFrameTopLeftPoint: NSMakePoint
5693 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
5694 IN_BOUND (-SCREENMAX,
5695 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
5698 [win makeFirstResponder: self];
5700 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5701 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
5702 [win setBackgroundColor: col];
5703 if ([col alphaComponent] != 1.0)
5704 [win setOpaque: NO];
5706 [self allocateGState];
5708 [NSApp registerServicesMenuSendTypes: ns_send_types
5716 - (void)windowDidMove: sender
5718 NSWindow *win = [self window];
5719 NSRect r = [win frame];
5720 NSArray *screens = [NSScreen screens];
5721 NSScreen *screen = [screens objectAtIndex: 0];
5723 NSTRACE (windowDidMove);
5725 if (!emacsframe->output_data.ns)
5729 emacsframe->left_pos = r.origin.x;
5730 emacsframe->top_pos =
5731 [screen frame].size.height - (r.origin.y + r.size.height);
5736 /* Called AFTER method below, but before our windowWillResize call there leads
5737 to windowDidResize -> x_set_window_size. Update emacs' notion of frame
5738 location so set_window_size moves the frame. */
5739 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
5741 emacsframe->output_data.ns->zooming = 1;
5746 /* Override to do something slightly nonstandard, but nice. First click on
5747 zoom button will zoom vertically. Second will zoom completely. Third
5748 returns to original. */
5749 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
5750 defaultFrame:(NSRect)defaultFrame
5752 NSRect result = [sender frame];
5754 NSTRACE (windowWillUseStandardFrame);
5756 if (fs_before_fs != -1) /* Entering fullscreen */
5758 result = defaultFrame;
5760 else if (next_maximized == FULLSCREEN_HEIGHT
5761 || (next_maximized == -1
5762 && abs (defaultFrame.size.height - result.size.height)
5763 > FRAME_LINE_HEIGHT (emacsframe)))
5766 ns_userRect = result;
5767 maximized_height = result.size.height = defaultFrame.size.height;
5768 maximized_width = -1;
5769 result.origin.y = defaultFrame.origin.y;
5770 [self setFSValue: FULLSCREEN_HEIGHT];
5772 else if (next_maximized == FULLSCREEN_WIDTH)
5774 ns_userRect = result;
5775 maximized_width = result.size.width = defaultFrame.size.width;
5776 maximized_height = -1;
5777 result.origin.x = defaultFrame.origin.x;
5778 [self setFSValue: FULLSCREEN_WIDTH];
5780 else if (next_maximized == FULLSCREEN_MAXIMIZED
5781 || (next_maximized == -1
5782 && abs (defaultFrame.size.width - result.size.width)
5783 > FRAME_COLUMN_WIDTH (emacsframe)))
5785 result = defaultFrame; /* second click */
5786 maximized_width = result.size.width;
5787 maximized_height = result.size.height;
5788 [self setFSValue: FULLSCREEN_MAXIMIZED];
5793 result = ns_userRect.size.height ? ns_userRect : result;
5794 ns_userRect = NSMakeRect (0, 0, 0, 0);
5795 [self setFSValue: FULLSCREEN_NONE];
5796 maximized_width = maximized_width = -1;
5799 if (fs_before_fs == -1) next_maximized = -1;
5800 [self windowWillResize: sender toSize: result.size];
5805 - (void)windowDidDeminiaturize: sender
5807 NSTRACE (windowDidDeminiaturize);
5808 if (!emacsframe->output_data.ns)
5810 emacsframe->async_iconified = 0;
5811 emacsframe->async_visible = 1;
5812 windows_or_buffers_changed++;
5816 emacs_event->kind = ICONIFY_EVENT;
5817 EV_TRAILER ((id)nil);
5822 - (void)windowDidExpose: sender
5824 NSTRACE (windowDidExpose);
5825 if (!emacsframe->output_data.ns)
5827 emacsframe->async_visible = 1;
5828 SET_FRAME_GARBAGED (emacsframe);
5830 if (send_appdefined)
5831 ns_send_appdefined (-1);
5835 - (void)windowDidMiniaturize: sender
5837 NSTRACE (windowDidMiniaturize);
5838 if (!emacsframe->output_data.ns)
5841 emacsframe->async_iconified = 1;
5842 emacsframe->async_visible = 0;
5846 emacs_event->kind = ICONIFY_EVENT;
5847 EV_TRAILER ((id)nil);
5851 - (void)windowWillEnterFullScreen:(NSNotification *)notification
5853 fs_before_fs = fs_state;
5856 - (void)windowDidEnterFullScreen:(NSNotification *)notification
5858 [self setFSValue: FULLSCREEN_BOTH];
5860 // Fix bad background.
5861 if ([toolbar isVisible])
5863 [toolbar setVisible:NO];
5864 [toolbar setVisible:YES];
5867 [self windowDidBecomeKey:notification];
5868 [nonfs_window orderOut:self];
5872 - (void)windowWillExitFullScreen:(NSNotification *)notification
5874 if (next_maximized != -1)
5875 fs_before_fs = next_maximized;
5878 - (void)windowDidExitFullScreen:(NSNotification *)notification
5880 [self setFSValue: fs_before_fs];
5882 if (next_maximized != -1)
5883 [[self window] performZoom:self];
5886 - (void)toggleFullScreen: (id)sender
5889 [[self window] toggleFullScreen:sender];
5891 NSWindow *w = [self window], *fw;
5892 BOOL onFirstScreen = [[w screen]
5893 isEqual:[[NSScreen screens] objectAtIndex:0]];
5894 struct frame *f = emacsframe;
5896 NSRect r, wr = [w frame];
5897 NSColor *col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5898 (FRAME_DEFAULT_FACE (f)),
5901 sz.width = FRAME_COLUMN_WIDTH (f);
5902 sz.height = FRAME_LINE_HEIGHT (f);
5904 if (fs_state != FULLSCREEN_BOTH)
5906 /* Hide dock and menubar if we are on the primary screen. */
5909 #if defined (NS_IMPL_COCOA) && \
5910 MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
5911 NSApplicationPresentationOptions options
5912 = NSApplicationPresentationAutoHideDock
5913 | NSApplicationPresentationAutoHideMenuBar;
5915 [NSApp setPresentationOptions: options];
5917 [NSMenu setMenuBarVisible:NO];
5921 fw = [[EmacsFSWindow alloc]
5922 initWithContentRect:[w contentRectForFrameRect:wr]
5923 styleMask:NSBorderlessWindowMask
5924 backing:NSBackingStoreBuffered
5928 [fw setContentView:[w contentView]];
5929 [fw setTitle:[w title]];
5930 [fw setDelegate:self];
5931 [fw setAcceptsMouseMovedEvents: YES];
5932 [fw useOptimizedDrawing: YES];
5933 [fw setResizeIncrements: sz];
5934 [fw setBackgroundColor: col];
5935 if ([col alphaComponent] != 1.0)
5938 f->border_width = 0;
5939 FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
5940 tobar_height = FRAME_TOOLBAR_HEIGHT (f);
5941 FRAME_TOOLBAR_HEIGHT (f) = 0;
5942 FRAME_EXTERNAL_TOOL_BAR (f) = 0;
5946 [self windowWillEnterFullScreen:nil];
5947 [fw makeKeyAndOrderFront:NSApp];
5948 [fw makeFirstResponder:self];
5950 r = [fw frameRectForContentRect:[[fw screen] frame]];
5951 [fw setFrame: r display:YES animate:YES];
5952 [self windowDidEnterFullScreen:nil];
5963 #if defined (NS_IMPL_COCOA) && \
5964 MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
5965 [NSApp setPresentationOptions: NSApplicationPresentationDefault];
5967 [NSMenu setMenuBarVisible:YES];
5971 [w setContentView:[fw contentView]];
5972 [w setResizeIncrements: sz];
5973 [w setBackgroundColor: col];
5974 if ([col alphaComponent] != 1.0)
5977 f->border_width = bwidth;
5978 FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
5979 FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
5981 FRAME_EXTERNAL_TOOL_BAR (f) = 1;
5983 [self windowWillExitFullScreen:nil];
5984 [fw setFrame: [w frame] display:YES animate:YES];
5986 [w makeKeyAndOrderFront:NSApp];
5987 [self windowDidExitFullScreen:nil];
5994 if (fs_state != emacsframe->want_fullscreen)
5996 if (fs_state == FULLSCREEN_BOTH)
5998 [self toggleFullScreen:self];
6001 switch (emacsframe->want_fullscreen)
6003 case FULLSCREEN_BOTH:
6004 [self toggleFullScreen:self];
6006 case FULLSCREEN_WIDTH:
6007 next_maximized = FULLSCREEN_WIDTH;
6008 if (fs_state != FULLSCREEN_BOTH)
6009 [[self window] performZoom:self];
6011 case FULLSCREEN_HEIGHT:
6012 next_maximized = FULLSCREEN_HEIGHT;
6013 if (fs_state != FULLSCREEN_BOTH)
6014 [[self window] performZoom:self];
6016 case FULLSCREEN_MAXIMIZED:
6017 next_maximized = FULLSCREEN_MAXIMIZED;
6018 if (fs_state != FULLSCREEN_BOTH)
6019 [[self window] performZoom:self];
6021 case FULLSCREEN_NONE:
6022 if (fs_state != FULLSCREEN_BOTH)
6024 next_maximized = FULLSCREEN_NONE;
6025 [[self window] performZoom:self];
6030 emacsframe->want_fullscreen = FULLSCREEN_NONE;
6035 - (void) setFSValue: (int)value
6037 Lisp_Object lval = Qnil;
6040 case FULLSCREEN_BOTH:
6043 case FULLSCREEN_WIDTH:
6046 case FULLSCREEN_HEIGHT:
6049 case FULLSCREEN_MAXIMIZED:
6053 store_frame_param (emacsframe, Qfullscreen, lval);
6057 - (void)mouseEntered: (NSEvent *)theEvent
6059 NSTRACE (mouseEntered);
6060 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
6064 - (void)mouseExited: (NSEvent *)theEvent
6066 Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
6068 NSTRACE (mouseExited);
6073 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
6075 if (emacsframe == hlinfo->mouse_face_mouse_frame)
6077 clear_mouse_face (hlinfo);
6078 hlinfo->mouse_face_mouse_frame = 0;
6086 if (context_menu_value == -1)
6087 context_menu_value = [sender tag];
6090 NSInteger tag = [sender tag];
6091 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
6092 emacsframe->menu_bar_vector,
6096 ns_send_appdefined (-1);
6101 - (EmacsToolbar *)toolbar
6107 /* this gets called on toolbar button click */
6108 - toolbarClicked: (id)item
6111 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
6113 NSTRACE (toolbarClicked);
6118 /* send first event (for some reason two needed) */
6119 theEvent = [[self window] currentEvent];
6120 emacs_event->kind = TOOL_BAR_EVENT;
6121 XSETFRAME (emacs_event->arg, emacsframe);
6122 EV_TRAILER (theEvent);
6124 emacs_event->kind = TOOL_BAR_EVENT;
6125 /* XSETINT (emacs_event->code, 0); */
6126 emacs_event->arg = AREF (emacsframe->tool_bar_items,
6127 idx + TOOL_BAR_ITEM_KEY);
6128 emacs_event->modifiers = EV_MODIFIERS (theEvent);
6129 EV_TRAILER (theEvent);
6134 - toggleToolbar: (id)sender
6139 emacs_event->kind = NS_NONKEY_EVENT;
6140 emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
6141 EV_TRAILER ((id)nil);
6146 - (void)drawRect: (NSRect)rect
6148 int x = NSMinX (rect), y = NSMinY (rect);
6149 int width = NSWidth (rect), height = NSHeight (rect);
6153 if (!emacsframe || !emacsframe->output_data.ns)
6156 ns_clear_frame_area (emacsframe, x, y, width, height);
6157 expose_frame (emacsframe, x, y, width, height);
6160 drawRect: may be called (at least in OS X 10.5) for invisible
6161 views as well for some reason. Thus, do not infer visibility
6164 emacsframe->async_visible = 1;
6165 emacsframe->async_iconified = 0;
6170 /* NSDraggingDestination protocol methods. Actually this is not really a
6171 protocol, but a category of Object. O well... */
6173 -(NSUInteger) draggingEntered: (id <NSDraggingInfo>) sender
6175 NSTRACE (draggingEntered);
6176 return NSDragOperationGeneric;
6180 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
6186 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
6191 NSEvent *theEvent = [[self window] currentEvent];
6194 NSTRACE (performDragOperation);
6199 position = [self convertPoint: [sender draggingLocation] fromView: nil];
6200 x = lrint (position.x); y = lrint (position.y);
6202 pb = [sender draggingPasteboard];
6203 type = [pb availableTypeFromArray: ns_drag_types];
6208 else if ([type isEqualToString: NSFilenamesPboardType])
6211 NSEnumerator *fenum;
6214 if (!(files = [pb propertyListForType: type]))
6217 fenum = [files objectEnumerator];
6218 while ( (file = [fenum nextObject]) )
6220 emacs_event->kind = NS_NONKEY_EVENT;
6221 emacs_event->code = KEY_NS_DRAG_FILE;
6222 XSETINT (emacs_event->x, x);
6223 XSETINT (emacs_event->y, y);
6224 ns_input_file = append2 (ns_input_file,
6225 build_string ([file UTF8String]));
6226 emacs_event->modifiers = EV_MODIFIERS (theEvent);
6227 EV_TRAILER (theEvent);
6231 else if ([type isEqualToString: NSURLPboardType])
6236 if (!(fileURL = [NSURL URLFromPasteboard: pb]) ||
6237 [fileURL isFileURL] == NO)
6240 file = [fileURL path];
6241 emacs_event->kind = NS_NONKEY_EVENT;
6242 emacs_event->code = KEY_NS_DRAG_FILE;
6243 XSETINT (emacs_event->x, x);
6244 XSETINT (emacs_event->y, y);
6245 ns_input_file = append2 (ns_input_file, build_string ([file UTF8String]));
6246 emacs_event->modifiers = EV_MODIFIERS (theEvent);
6247 EV_TRAILER (theEvent);
6250 else if ([type isEqualToString: NSStringPboardType]
6251 || [type isEqualToString: NSTabularTextPboardType])
6255 if (! (data = [pb stringForType: type]))
6258 emacs_event->kind = NS_NONKEY_EVENT;
6259 emacs_event->code = KEY_NS_DRAG_TEXT;
6260 XSETINT (emacs_event->x, x);
6261 XSETINT (emacs_event->y, y);
6262 ns_input_text = build_string ([data UTF8String]);
6263 emacs_event->modifiers = EV_MODIFIERS (theEvent);
6264 EV_TRAILER (theEvent);
6267 else if ([type isEqualToString: NSColorPboardType])
6269 NSColor *c = [NSColor colorFromPasteboard: pb];
6270 emacs_event->kind = NS_NONKEY_EVENT;
6271 emacs_event->code = KEY_NS_DRAG_COLOR;
6272 XSETINT (emacs_event->x, x);
6273 XSETINT (emacs_event->y, y);
6274 ns_input_color = ns_color_to_lisp (c);
6275 emacs_event->modifiers = EV_MODIFIERS (theEvent);
6276 EV_TRAILER (theEvent);
6279 else if ([type isEqualToString: NSFontPboardType])
6281 /* impl based on GNUstep NSTextView.m */
6282 NSData *data = [pb dataForType: NSFontPboardType];
6283 NSDictionary *dict = [NSUnarchiver unarchiveObjectWithData: data];
6284 NSFont *font = [dict objectForKey: NSFontAttributeName];
6290 emacs_event->kind = NS_NONKEY_EVENT;
6291 emacs_event->code = KEY_NS_CHANGE_FONT;
6292 XSETINT (emacs_event->x, x);
6293 XSETINT (emacs_event->y, y);
6294 ns_input_font = build_string ([[font fontName] UTF8String]);
6295 snprintf (fontSize, 10, "%f", [font pointSize]);
6296 ns_input_fontsize = build_string (fontSize);
6297 emacs_event->modifiers = EV_MODIFIERS (theEvent);
6298 EV_TRAILER (theEvent);
6303 error ("Invalid data type in dragging pasteboard.");
6309 - (id) validRequestorForSendType: (NSString *)typeSent
6310 returnType: (NSString *)typeReturned
6312 NSTRACE (validRequestorForSendType);
6313 if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
6314 && typeReturned == nil)
6316 if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
6320 return [super validRequestorForSendType: typeSent
6321 returnType: typeReturned];
6325 /* The next two methods are part of NSServicesRequests informal protocol,
6326 supposedly called when a services menu item is chosen from this app.
6327 But this should not happen because we override the services menu with our
6328 own entries which call ns-perform-service.
6329 Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
6330 So let's at least stub them out until further investigation can be done. */
6332 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
6334 /* we could call ns_string_from_pasteboard(pboard) here but then it should
6335 be written into the buffer in place of the existing selection..
6336 ordinary service calls go through functions defined in ns-win.el */
6340 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
6342 NSArray *typesDeclared;
6345 /* We only support NSStringPboardType */
6346 if ([types containsObject:NSStringPboardType] == NO) {
6350 val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
6351 if (CONSP (val) && SYMBOLP (XCAR (val)))
6354 if (CONSP (val) && NILP (XCDR (val)))
6357 if (! STRINGP (val))
6360 typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
6361 [pb declareTypes:typesDeclared owner:nil];
6362 ns_string_to_pasteboard (pb, val);
6367 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
6368 (gives a miniaturized version of the window); currently we use the latter for
6369 frames whose active buffer doesn't correspond to any file
6370 (e.g., '*scratch*') */
6371 - setMiniwindowImage: (BOOL) setMini
6373 id image = [[self window] miniwindowImage];
6374 NSTRACE (setMiniwindowImage);
6376 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
6377 about "AppleDockIconEnabled" notwithstanding, however the set message
6378 below has its effect nonetheless. */
6379 if (image != emacsframe->output_data.ns->miniimage)
6381 if (image && [image isKindOfClass: [EmacsImage class]])
6383 [[self window] setMiniwindowImage:
6384 setMini ? emacsframe->output_data.ns->miniimage : nil];
6391 - (void) setRows: (int) r andColumns: (int) c
6397 @end /* EmacsView */
6401 /* ==========================================================================
6403 EmacsWindow implementation
6405 ========================================================================== */
6407 @implementation EmacsWindow
6409 #ifdef NS_IMPL_COCOA
6410 - (id)accessibilityAttributeValue:(NSString *)attribute
6412 Lisp_Object str = Qnil;
6413 struct frame *f = SELECTED_FRAME ();
6414 struct buffer *curbuf = XBUFFER (XWINDOW (f->selected_window)->buffer);
6416 if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
6417 return NSAccessibilityTextFieldRole;
6419 if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]
6420 && curbuf && ! NILP (BVAR (curbuf, mark_active)))
6422 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
6424 else if (curbuf && [attribute isEqualToString:NSAccessibilityValueAttribute])
6426 if (! NILP (BVAR (curbuf, mark_active)))
6427 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
6431 ptrdiff_t start_byte = BUF_BEGV_BYTE (curbuf);
6432 ptrdiff_t byte_range = BUF_ZV_BYTE (curbuf) - start_byte;
6433 ptrdiff_t range = BUF_ZV (curbuf) - BUF_BEGV (curbuf);
6435 if (! NILP (BVAR (curbuf, enable_multibyte_characters)))
6436 str = make_uninit_multibyte_string (range, byte_range);
6438 str = make_uninit_string (range);
6439 /* To check: This returns emacs-utf-8, which is a superset of utf-8.
6440 Is this a problem? */
6441 memcpy (SDATA (str), BYTE_POS_ADDR (start_byte), byte_range);
6448 if (CONSP (str) && SYMBOLP (XCAR (str)))
6451 if (CONSP (str) && NILP (XCDR (str)))
6456 const char *utfStr = SSDATA (str);
6457 NSString *nsStr = [NSString stringWithUTF8String: utfStr];
6462 return [super accessibilityAttributeValue:attribute];
6464 #endif /* NS_IMPL_COCOA */
6466 /* If we have multiple monitors, one above the other, we don't want to
6467 restrict the height to just one monitor. So we override this. */
6468 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
6470 /* When making the frame visible for the first time or if there is just
6471 one screen, we want to constrain. Other times not. */
6472 NSUInteger nr_screens = [[NSScreen screens] count];
6473 struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
6474 NSTRACE (constrainFrameRect);
6476 if (nr_screens == 1)
6478 NSRect r = [super constrainFrameRect:frameRect toScreen:screen];
6482 if (f->output_data.ns->dont_constrain
6483 || ns_menu_bar_should_be_hidden ())
6486 f->output_data.ns->dont_constrain = 1;
6487 return [super constrainFrameRect:frameRect toScreen:screen];
6490 @end /* EmacsWindow */
6493 @implementation EmacsFSWindow
6495 - (BOOL)canBecomeKeyWindow
6500 - (BOOL)canBecomeMainWindow
6507 /* ==========================================================================
6509 EmacsScroller implementation
6511 ========================================================================== */
6514 @implementation EmacsScroller
6516 /* for repeat button push */
6517 #define SCROLL_BAR_FIRST_DELAY 0.5
6518 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
6520 + (CGFloat) scrollerWidth
6522 /* TODO: if we want to allow variable widths, this is the place to do it,
6523 however neither GNUstep nor Cocoa support it very well */
6524 return [NSScroller scrollerWidth];
6528 - initFrame: (NSRect )r window: (Lisp_Object)nwin
6530 NSTRACE (EmacsScroller_initFrame);
6532 r.size.width = [EmacsScroller scrollerWidth];
6533 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
6534 [self setContinuous: YES];
6535 [self setEnabled: YES];
6537 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
6538 locked against the top and bottom edges, and right edge on OS X, where
6539 scrollers are on right. */
6540 #ifdef NS_IMPL_GNUSTEP
6541 [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
6543 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
6548 pixel_height = NSHeight (r);
6549 if (pixel_height == 0) pixel_height = 1;
6550 min_portion = 20 / pixel_height;
6552 frame = XFRAME (XWINDOW (win)->frame);
6553 if (FRAME_LIVE_P (frame))
6556 EmacsView *view = FRAME_NS_VIEW (frame);
6557 NSView *sview = [[view window] contentView];
6558 NSArray *subs = [sview subviews];
6560 /* disable optimization stopping redraw of other scrollbars */
6561 view->scrollbarsNeedingUpdate = 0;
6562 for (i =[subs count]-1; i >= 0; i--)
6563 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
6564 view->scrollbarsNeedingUpdate++;
6565 [sview addSubview: self];
6568 /* [self setFrame: r]; */
6574 - (void)setFrame: (NSRect)newRect
6576 NSTRACE (EmacsScroller_setFrame);
6577 /* block_input (); */
6578 pixel_height = NSHeight (newRect);
6579 if (pixel_height == 0) pixel_height = 1;
6580 min_portion = 20 / pixel_height;
6581 [super setFrame: newRect];
6583 /* unblock_input (); */
6589 NSTRACE (EmacsScroller_dealloc);
6591 wset_vertical_scroll_bar (XWINDOW (win), Qnil);
6619 /* ensure other scrollbar updates after deletion */
6620 view = (EmacsView *)FRAME_NS_VIEW (frame);
6622 view->scrollbarsNeedingUpdate++;
6623 [self removeFromSuperview];
6631 - (void)resetCursorRects
6633 NSRect visible = [self visibleRect];
6634 NSTRACE (resetCursorRects);
6636 if (!NSIsEmptyRect (visible))
6637 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
6638 [[NSCursor arrowCursor] setOnMouseEntered: YES];
6642 - (int) checkSamePosition: (int) position portion: (int) portion
6645 return em_position ==position && em_portion ==portion && em_whole ==whole
6646 && portion != whole; /* needed for resize empty buf */
6650 - setPosition: (int)position portion: (int)portion whole: (int)whole
6652 NSTRACE (setPosition);
6654 em_position = position;
6655 em_portion = portion;
6658 if (portion >= whole)
6660 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
6661 [self setKnobProportion: 1.0];
6662 [self setDoubleValue: 1.0];
6664 [self setFloatValue: 0.0 knobProportion: 1.0];
6670 portion = max ((float)whole*min_portion/pixel_height, portion);
6671 pos = (float)position / (whole - portion);
6672 por = (float)portion/whole;
6673 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
6674 [self setKnobProportion: por];
6675 [self setDoubleValue: pos];
6677 [self setFloatValue: pos knobProportion: por];
6681 /* Events may come here even if the event loop is not running.
6682 If we don't enter the event loop, the scroll bar will not update.
6683 So send SIGIO to ourselves. */
6684 if (apploopnr == 0) kill (0, SIGIO);
6689 /* FIXME: unused at moment (see ns_mouse_position) at the moment because
6690 drag events will go directly to the EmacsScroller. Leaving in for now. */
6691 -(void)getMouseMotionPart: (int *)part window: (Lisp_Object *)window
6692 x: (Lisp_Object *)x y: ( Lisp_Object *)y
6694 *part = last_hit_part;
6696 XSETINT (*y, pixel_height);
6697 if ([self floatValue] > 0.999)
6698 XSETINT (*x, pixel_height);
6700 XSETINT (*x, pixel_height * [self floatValue]);
6704 /* set up emacs_event */
6705 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
6710 emacs_event->part = last_hit_part;
6711 emacs_event->code = 0;
6712 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
6713 emacs_event->frame_or_window = win;
6714 emacs_event->timestamp = EV_TIMESTAMP (e);
6715 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
6716 emacs_event->arg = Qnil;
6717 XSETINT (emacs_event->x, loc * pixel_height);
6718 XSETINT (emacs_event->y, pixel_height-20);
6722 n_emacs_events_pending++;
6723 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
6726 hold_event (emacs_event);
6727 EVENT_INIT (*emacs_event);
6728 ns_send_appdefined (-1);
6732 /* called manually thru timer to implement repeated button action w/hold-down */
6733 - repeatScroll: (NSTimer *)scrollEntry
6735 NSEvent *e = [[self window] currentEvent];
6736 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
6737 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
6739 /* clear timer if need be */
6740 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
6742 [scroll_repeat_entry invalidate];
6743 [scroll_repeat_entry release];
6744 scroll_repeat_entry = nil;
6750 = [[NSTimer scheduledTimerWithTimeInterval:
6751 SCROLL_BAR_CONTINUOUS_DELAY
6753 selector: @selector (repeatScroll:)
6759 [self sendScrollEventAtLoc: 0 fromEvent: e];
6764 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
6765 mouseDragged events without going into a modal loop. */
6766 - (void)mouseDown: (NSEvent *)e
6769 /* hitPart is only updated AFTER event is passed on */
6770 NSScrollerPart part = [self testPart: [e locationInWindow]];
6771 double inc = 0.0, loc, kloc, pos;
6774 NSTRACE (EmacsScroller_mouseDown);
6778 case NSScrollerDecrementPage:
6779 last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
6780 case NSScrollerIncrementPage:
6781 last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
6782 case NSScrollerDecrementLine:
6783 last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
6784 case NSScrollerIncrementLine:
6785 last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
6786 case NSScrollerKnob:
6787 last_hit_part = scroll_bar_handle; break;
6788 case NSScrollerKnobSlot: /* GNUstep-only */
6789 last_hit_part = scroll_bar_move_ratio; break;
6790 default: /* NSScrollerNoPart? */
6791 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
6798 pos = 0; /* ignored */
6800 /* set a timer to repeat, as we can't let superclass do this modally */
6802 = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
6804 selector: @selector (repeatScroll:)
6811 /* handle, or on GNUstep possibly slot */
6812 NSEvent *fake_event;
6814 /* compute float loc in slot and mouse offset on knob */
6815 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6817 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6823 else if (loc >= NSHeight (sr))
6825 loc = NSHeight (sr);
6833 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
6835 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
6837 last_mouse_offset = kloc;
6839 /* if knob, tell emacs a location offset by knob pos
6840 (to indicate top of handle) */
6841 if (part == NSScrollerKnob)
6842 pos = (loc - last_mouse_offset) / NSHeight (sr);
6844 /* else this is a slot click on GNUstep: go straight there */
6845 pos = loc / NSHeight (sr);
6847 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
6848 fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
6849 location: [e locationInWindow]
6850 modifierFlags: [e modifierFlags]
6851 timestamp: [e timestamp]
6852 windowNumber: [e windowNumber]
6853 context: [e context]
6854 eventNumber: [e eventNumber]
6855 clickCount: [e clickCount]
6856 pressure: [e pressure]];
6857 [super mouseUp: fake_event];
6860 if (part != NSScrollerKnob)
6861 [self sendScrollEventAtLoc: pos fromEvent: e];
6865 /* Called as we manually track scroller drags, rather than superclass. */
6866 - (void)mouseDragged: (NSEvent *)e
6872 NSTRACE (EmacsScroller_mouseDragged);
6874 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6876 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6883 else if (loc >= NSHeight (sr) + last_mouse_offset)
6885 loc = NSHeight (sr) + last_mouse_offset;
6889 pos = /*(edge ? loc :*/ (loc - last_mouse_offset) / NSHeight (sr);
6890 [self sendScrollEventAtLoc: pos fromEvent: e];
6894 - (void)mouseUp: (NSEvent *)e
6896 if (scroll_repeat_entry)
6898 [scroll_repeat_entry invalidate];
6899 [scroll_repeat_entry release];
6900 scroll_repeat_entry = nil;
6906 /* treat scrollwheel events in the bar as though they were in the main window */
6907 - (void) scrollWheel: (NSEvent *)theEvent
6909 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
6910 [view mouseDown: theEvent];
6913 @end /* EmacsScroller */
6918 /* ==========================================================================
6920 Font-related functions; these used to be in nsfaces.m
6922 ========================================================================== */
6926 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
6928 struct font *font = XFONT_OBJECT (font_object);
6931 fontset = fontset_from_font (font_object);
6932 FRAME_FONTSET (f) = fontset;
6934 if (FRAME_FONT (f) == font)
6935 /* This font is already set in frame F. There's nothing more to
6939 FRAME_FONT (f) = font;
6941 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
6942 FRAME_COLUMN_WIDTH (f) = font->average_width;
6943 FRAME_SPACE_WIDTH (f) = font->space_width;
6944 FRAME_LINE_HEIGHT (f) = font->height;
6946 compute_fringe_widths (f, 1);
6948 /* Compute the scroll bar width in character columns. */
6949 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
6951 int wid = FRAME_COLUMN_WIDTH (f);
6952 FRAME_CONFIG_SCROLL_BAR_COLS (f)
6953 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
6957 int wid = FRAME_COLUMN_WIDTH (f);
6958 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
6961 /* Now make the frame display the given font. */
6962 if (FRAME_NS_WINDOW (f) != 0)
6963 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
6969 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
6970 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
6974 ns_xlfd_to_fontname (const char *xlfd)
6975 /* --------------------------------------------------------------------------
6976 Convert an X font name (XLFD) to an NS font name.
6977 Only family is used.
6978 The string returned is temporarily allocated.
6979 -------------------------------------------------------------------------- */
6981 char *name = xmalloc (180);
6985 if (!strncmp (xlfd, "--", 2))
6986 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
6988 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
6990 /* stopgap for malformed XLFD input */
6991 if (strlen (name) == 0)
6992 strcpy (name, "Monaco");
6994 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
6995 also uppercase after '-' or ' ' */
6996 name[0] = c_toupper (name[0]);
6997 for (len =strlen (name), i =0; i<len; i++)
7003 name[i+1] = c_toupper (name[i+1]);
7005 else if (name[i] == '_')
7009 name[i+1] = c_toupper (name[i+1]);
7012 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
7013 ret = [[NSString stringWithUTF8String: name] UTF8String];
7020 syms_of_nsterm (void)
7022 NSTRACE (syms_of_nsterm);
7024 ns_antialias_threshold = 10.0;
7026 /* from 23+ we need to tell emacs what modifiers there are.. */
7027 DEFSYM (Qmodifier_value, "modifier-value");
7028 DEFSYM (Qalt, "alt");
7029 DEFSYM (Qhyper, "hyper");
7030 DEFSYM (Qmeta, "meta");
7031 DEFSYM (Qsuper, "super");
7032 DEFSYM (Qcontrol, "control");
7033 DEFSYM (QUTF8_STRING, "UTF8_STRING");
7035 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
7036 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
7037 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
7038 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
7039 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
7041 DEFVAR_LISP ("ns-input-file", ns_input_file,
7042 "The file specified in the last NS event.");
7043 ns_input_file =Qnil;
7045 DEFVAR_LISP ("ns-input-text", ns_input_text,
7046 "The data received in the last NS text drag event.");
7047 ns_input_text =Qnil;
7049 DEFVAR_LISP ("ns-working-text", ns_working_text,
7050 "String for visualizing working composition sequence.");
7051 ns_working_text =Qnil;
7053 DEFVAR_LISP ("ns-input-font", ns_input_font,
7054 "The font specified in the last NS event.");
7055 ns_input_font =Qnil;
7057 DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
7058 "The fontsize specified in the last NS event.");
7059 ns_input_fontsize =Qnil;
7061 DEFVAR_LISP ("ns-input-line", ns_input_line,
7062 "The line specified in the last NS event.");
7063 ns_input_line =Qnil;
7065 DEFVAR_LISP ("ns-input-color", ns_input_color,
7066 "The color specified in the last NS event.");
7067 ns_input_color =Qnil;
7069 DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
7070 "The service name specified in the last NS event.");
7071 ns_input_spi_name =Qnil;
7073 DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
7074 "The service argument specified in the last NS event.");
7075 ns_input_spi_arg =Qnil;
7077 DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
7078 "This variable describes the behavior of the alternate or option key.\n\
7079 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7080 Set to none means that the alternate / option key is not interpreted by Emacs\n\
7081 at all, allowing it to be used at a lower level for accented character entry.");
7082 ns_alternate_modifier = Qmeta;
7084 DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
7085 "This variable describes the behavior of the right alternate or option key.\n\
7086 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7087 Set to left means be the same key as `ns-alternate-modifier'.\n\
7088 Set to none means that the alternate / option key is not interpreted by Emacs\n\
7089 at all, allowing it to be used at a lower level for accented character entry.");
7090 ns_right_alternate_modifier = Qleft;
7092 DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
7093 "This variable describes the behavior of the command key.\n\
7094 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
7095 ns_command_modifier = Qsuper;
7097 DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
7098 "This variable describes the behavior of the right command key.\n\
7099 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7100 Set to left means be the same key as `ns-command-modifier'.\n\
7101 Set to none means that the command / option key is not interpreted by Emacs\n\
7102 at all, allowing it to be used at a lower level for accented character entry.");
7103 ns_right_command_modifier = Qleft;
7105 DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
7106 "This variable describes the behavior of the control key.\n\
7107 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
7108 ns_control_modifier = Qcontrol;
7110 DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
7111 "This variable describes the behavior of the right control key.\n\
7112 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7113 Set to left means be the same key as `ns-control-modifier'.\n\
7114 Set to none means that the control / option key is not interpreted by Emacs\n\
7115 at all, allowing it to be used at a lower level for accented character entry.");
7116 ns_right_control_modifier = Qleft;
7118 DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
7119 "This variable describes the behavior of the function key (on laptops).\n\
7120 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7121 Set to none means that the function key is not interpreted by Emacs at all,\n\
7122 allowing it to be used at a lower level for accented character entry.");
7123 ns_function_modifier = Qnone;
7125 DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
7126 "Non-nil (the default) means to render text antialiased.");
7127 ns_antialias_text = Qt;
7129 DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
7130 "Whether to confirm application quit using dialog.");
7131 ns_confirm_quit = Qnil;
7133 staticpro (&ns_display_name_list);
7134 ns_display_name_list = Qnil;
7136 staticpro (&last_mouse_motion_frame);
7137 last_mouse_motion_frame = Qnil;
7139 DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
7140 doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
7141 Only works on OSX 10.6 or later. */);
7142 ns_auto_hide_menu_bar = Qnil;
7144 /* TODO: move to common code */
7145 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
7146 doc: /* Which toolkit scroll bars Emacs uses, if any.
7147 A value of nil means Emacs doesn't use toolkit scroll bars.
7148 With the X Window system, the value is a symbol describing the
7149 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
7150 With MS Windows or Nextstep, the value is t. */);
7151 Vx_toolkit_scroll_bars = Qt;
7153 DEFVAR_BOOL ("x-use-underline-position-properties",
7154 x_use_underline_position_properties,
7155 doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
7156 A value of nil means ignore them. If you encounter fonts with bogus
7157 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
7158 to 4.1, set this to nil. */);
7159 x_use_underline_position_properties = 0;
7161 DEFVAR_BOOL ("x-underline-at-descent-line",
7162 x_underline_at_descent_line,
7163 doc: /* Non-nil means to draw the underline at the same place as the descent line.
7164 A value of nil means to draw the underline according to the value of the
7165 variable `x-use-underline-position-properties', which is usually at the
7166 baseline level. The default value is nil. */);
7167 x_underline_at_descent_line = 0;
7169 /* Tell emacs about this window system. */
7170 Fprovide (intern ("ns"), Qnil);