1 /* NeXT/Open/GNUstep / MacOSX communication module.
3 Copyright (C) 1989, 1993-1994, 2005-2006, 2008-2013 Free Software
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 #define NO_APPDEFINED_DATA (-8)
194 static int last_appdefined_event_data = NO_APPDEFINED_DATA;
195 static NSTimer *timed_entry = 0;
196 static NSTimer *scroll_repeat_entry = nil;
197 static fd_set select_readfds, select_writefds;
198 enum { SELECT_HAVE_READ = 1, SELECT_HAVE_WRITE = 2, SELECT_HAVE_TMO = 4 };
199 static int select_nfds = 0, select_valid = 0;
200 static EMACS_TIME select_timeout = { 0, 0 };
201 static int selfds[2] = { -1, -1 };
202 static pthread_mutex_t select_mutex;
203 static int apploopnr = 0;
204 static NSAutoreleasePool *outerpool;
205 static struct input_event *emacs_event = NULL;
206 static struct input_event *q_event_ptr = NULL;
207 static int n_emacs_events_pending = 0;
208 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
209 *ns_pending_service_args;
210 static BOOL ns_do_open_file = NO;
213 struct input_event *q;
219 /* Convert modifiers in a NeXTstep event to emacs style modifiers. */
220 #define NS_FUNCTION_KEY_MASK 0x800000
221 #define NSLeftControlKeyMask (0x000001 | NSControlKeyMask)
222 #define NSRightControlKeyMask (0x002000 | NSControlKeyMask)
223 #define NSLeftCommandKeyMask (0x000008 | NSCommandKeyMask)
224 #define NSRightCommandKeyMask (0x000010 | NSCommandKeyMask)
225 #define NSLeftAlternateKeyMask (0x000020 | NSAlternateKeyMask)
226 #define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
227 #define EV_MODIFIERS(e) \
228 ((([e modifierFlags] & NSHelpKeyMask) ? \
229 hyper_modifier : 0) \
230 | (!EQ (ns_right_alternate_modifier, Qleft) && \
231 (([e modifierFlags] & NSRightAlternateKeyMask) \
232 == NSRightAlternateKeyMask) ? \
233 parse_solitary_modifier (ns_right_alternate_modifier) : 0) \
234 | (([e modifierFlags] & NSAlternateKeyMask) ? \
235 parse_solitary_modifier (ns_alternate_modifier) : 0) \
236 | (([e modifierFlags] & NSShiftKeyMask) ? \
237 shift_modifier : 0) \
238 | (!EQ (ns_right_control_modifier, Qleft) && \
239 (([e modifierFlags] & NSRightControlKeyMask) \
240 == NSRightControlKeyMask) ? \
241 parse_solitary_modifier (ns_right_control_modifier) : 0) \
242 | (([e modifierFlags] & NSControlKeyMask) ? \
243 parse_solitary_modifier (ns_control_modifier) : 0) \
244 | (([e modifierFlags] & NS_FUNCTION_KEY_MASK) ? \
245 parse_solitary_modifier (ns_function_modifier) : 0) \
246 | (!EQ (ns_right_command_modifier, Qleft) && \
247 (([e modifierFlags] & NSRightCommandKeyMask) \
248 == NSRightCommandKeyMask) ? \
249 parse_solitary_modifier (ns_right_command_modifier) : 0) \
250 | (([e modifierFlags] & NSCommandKeyMask) ? \
251 parse_solitary_modifier (ns_command_modifier):0))
253 #define EV_UDMODIFIERS(e) \
254 ((([e type] == NSLeftMouseDown) ? down_modifier : 0) \
255 | (([e type] == NSRightMouseDown) ? down_modifier : 0) \
256 | (([e type] == NSOtherMouseDown) ? down_modifier : 0) \
257 | (([e type] == NSLeftMouseDragged) ? down_modifier : 0) \
258 | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
259 | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
260 | (([e type] == NSLeftMouseUp) ? up_modifier : 0) \
261 | (([e type] == NSRightMouseUp) ? up_modifier : 0) \
262 | (([e type] == NSOtherMouseUp) ? up_modifier : 0))
264 #define EV_BUTTON(e) \
265 ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 : \
266 (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
267 [e buttonNumber] - 1)
269 /* Convert the time field to a timestamp in milliseconds. */
270 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
272 /* This is a piece of code which is common to all the event handling
273 methods. Maybe it should even be a function. */
274 #define EV_TRAILER(e) \
276 XSETFRAME (emacs_event->frame_or_window, emacsframe); \
277 if (e) emacs_event->timestamp = EV_TIMESTAMP (e); \
280 n_emacs_events_pending++; \
281 kbd_buffer_store_event_hold (emacs_event, q_event_ptr); \
284 hold_event (emacs_event); \
285 EVENT_INIT (*emacs_event); \
286 ns_send_appdefined (-1); \
289 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
291 /* TODO: get rid of need for these forward declarations */
292 static void ns_condemn_scroll_bars (struct frame *f);
293 static void ns_judge_scroll_bars (struct frame *f);
294 void x_set_frame_alpha (struct frame *f);
297 /* ==========================================================================
301 ========================================================================== */
304 hold_event (struct input_event *event)
306 if (hold_event_q.nr == hold_event_q.cap)
308 if (hold_event_q.cap == 0) hold_event_q.cap = 10;
309 else hold_event_q.cap *= 2;
310 hold_event_q.q = (struct input_event *)
311 xrealloc (hold_event_q.q, hold_event_q.cap * sizeof (*hold_event_q.q));
314 hold_event_q.q[hold_event_q.nr++] = *event;
315 /* Make sure ns_read_socket is called, i.e. we have input. */
317 send_appdefined = YES;
321 append2 (Lisp_Object list, Lisp_Object item)
322 /* --------------------------------------------------------------------------
323 Utility to append to a list
324 -------------------------------------------------------------------------- */
326 Lisp_Object array[2];
328 array[1] = Fcons (item, Qnil);
329 return Fnconc (2, &array[0]);
334 ns_etc_directory (void)
335 /* If running as a self-contained app bundle, return as a string the
336 filename of the etc directory, if present; else nil. */
338 NSBundle *bundle = [NSBundle mainBundle];
339 NSString *resourceDir = [bundle resourcePath];
340 NSString *resourcePath;
341 NSFileManager *fileManager = [NSFileManager defaultManager];
344 resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
345 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
347 if (isDir) return [resourcePath UTF8String];
355 /* If running as a self-contained app bundle, return as a path string
356 the filenames of the libexec and bin directories, ie libexec:bin.
357 Otherwise, return nil.
358 Normally, Emacs does not add its own bin/ directory to the PATH.
359 However, a self-contained NS build has a different layout, with
360 bin/ and libexec/ subdirectories in the directory that contains
362 We put libexec first, because init_callproc_1 uses the first
363 element to initialize exec-directory. An alternative would be
364 for init_callproc to check for invocation-directory/libexec.
367 NSBundle *bundle = [NSBundle mainBundle];
368 NSString *resourceDir = [bundle resourcePath];
369 NSString *binDir = [bundle bundlePath];
370 NSString *resourcePath, *resourcePaths;
372 NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
373 NSFileManager *fileManager = [NSFileManager defaultManager];
375 NSEnumerator *pathEnum;
378 range = [resourceDir rangeOfString: @"Contents"];
379 if (range.location != NSNotFound)
381 binDir = [binDir stringByAppendingPathComponent: @"Contents"];
383 binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
387 paths = [binDir stringsByAppendingPaths:
388 [NSArray arrayWithObjects: @"libexec", @"bin", nil]];
389 pathEnum = [paths objectEnumerator];
392 while ((resourcePath = [pathEnum nextObject]))
394 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
397 if ([resourcePaths length] > 0)
399 = [resourcePaths stringByAppendingString: pathSeparator];
401 = [resourcePaths stringByAppendingString: resourcePath];
404 if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
412 /* If running as a self-contained app bundle, return as a path string
413 the filenames of the site-lisp, lisp and leim directories.
414 Ie, site-lisp:lisp:leim. Otherwise, return nil. */
416 NSBundle *bundle = [NSBundle mainBundle];
417 NSString *resourceDir = [bundle resourcePath];
418 NSString *resourcePath, *resourcePaths;
419 NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
420 NSFileManager *fileManager = [NSFileManager defaultManager];
422 NSArray *paths = [resourceDir stringsByAppendingPaths:
423 [NSArray arrayWithObjects:
424 @"site-lisp", @"lisp", @"leim", nil]];
425 NSEnumerator *pathEnum = [paths objectEnumerator];
428 /* Hack to skip site-lisp. */
429 if (no_site_lisp) resourcePath = [pathEnum nextObject];
431 while ((resourcePath = [pathEnum nextObject]))
433 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
436 if ([resourcePaths length] > 0)
438 = [resourcePaths stringByAppendingString: pathSeparator];
440 = [resourcePaths stringByAppendingString: resourcePath];
443 if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
449 ns_timeout (int usecs)
450 /* --------------------------------------------------------------------------
451 Blocking timer utility used by ns_ring_bell
452 -------------------------------------------------------------------------- */
454 EMACS_TIME wakeup = add_emacs_time (current_emacs_time (),
455 make_emacs_time (0, usecs * 1000));
457 /* Keep waiting until past the time wakeup. */
460 EMACS_TIME timeout, now = current_emacs_time ();
461 if (EMACS_TIME_LE (wakeup, now))
463 timeout = sub_emacs_time (wakeup, now);
465 /* Try to wait that long--but we might wake up sooner. */
466 pselect (0, NULL, NULL, NULL, &timeout, NULL);
472 ns_release_object (void *obj)
473 /* --------------------------------------------------------------------------
474 Release an object (callable from C)
475 -------------------------------------------------------------------------- */
482 ns_retain_object (void *obj)
483 /* --------------------------------------------------------------------------
484 Retain an object (callable from C)
485 -------------------------------------------------------------------------- */
492 ns_alloc_autorelease_pool (void)
493 /* --------------------------------------------------------------------------
494 Allocate a pool for temporary objects (callable from C)
495 -------------------------------------------------------------------------- */
497 return [[NSAutoreleasePool alloc] init];
502 ns_release_autorelease_pool (void *pool)
503 /* --------------------------------------------------------------------------
504 Free a pool and temporary objects it refers to (callable from C)
505 -------------------------------------------------------------------------- */
507 ns_release_object (pool);
512 /* ==========================================================================
514 Focus (clipping) and screen update
516 ========================================================================== */
519 // Window constraining
520 // -------------------
522 // To ensure that the windows are not placed under the menu bar, they
523 // are typically moved by the call-back constrainFrameRect. However,
524 // by overriding it, it's possible to inhibit this, leaving the window
525 // in it's original position.
527 // It's possible to hide the menu bar. However, technically, it's only
528 // possible to hide it when the application is active. To ensure that
529 // this work properly, the menu bar and window constraining are
530 // deferred until the application becomes active.
532 // Even though it's not possible to manually move a window above the
533 // top of the screen, it is allowed if it's done programmatically,
534 // when the menu is hidden. This allows the editable area to cover the
535 // full screen height.
540 // Use the following extra files:
543 // ;; Hide menu and place frame slightly above the top of the screen.
544 // (setq ns-auto-hide-menu-bar t)
545 // (set-frame-position (selected-frame) 0 -20)
549 // emacs -Q -l init.el
551 // Result: No menu bar, and the title bar should be above the screen.
557 // Result: Menu bar visible, frame placed immediately below the menu.
561 ns_constrain_all_frames (void)
563 Lisp_Object tail, frame;
565 FOR_EACH_FRAME (tail, frame)
567 struct frame *f = XFRAME (frame);
570 NSView *view = FRAME_NS_VIEW (f);
571 /* This no-op will trigger the default window placing
572 * constraint system. */
573 f->output_data.ns->dont_constrain = 0;
574 [[view window] setFrameOrigin:[[view window] frame].origin];
580 /* True, if the menu bar should be hidden. */
583 ns_menu_bar_should_be_hidden (void)
585 return !NILP (ns_auto_hide_menu_bar)
586 && [NSApp respondsToSelector:@selector(setPresentationOptions:)];
590 /* Show or hide the menu bar, based on user setting. */
593 ns_update_auto_hide_menu_bar (void)
596 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
599 NSTRACE (ns_update_auto_hide_menu_bar);
603 && [NSApp respondsToSelector:@selector(setPresentationOptions:)])
605 // Note, "setPresentationOptions" triggers an error unless the
606 // application is active.
607 BOOL menu_bar_should_be_hidden = ns_menu_bar_should_be_hidden ();
609 if (menu_bar_should_be_hidden != ns_menu_bar_is_hidden)
611 NSApplicationPresentationOptions options
612 = NSApplicationPresentationAutoHideDock;
614 if (menu_bar_should_be_hidden)
615 options |= NSApplicationPresentationAutoHideMenuBar;
617 [NSApp setPresentationOptions: options];
619 ns_menu_bar_is_hidden = menu_bar_should_be_hidden;
621 if (!ns_menu_bar_is_hidden)
623 ns_constrain_all_frames ();
635 ns_update_begin (struct frame *f)
636 /* --------------------------------------------------------------------------
637 Prepare for a grouped sequence of drawing calls
638 external (RIF) call; whole frame, called before update_window_begin
639 -------------------------------------------------------------------------- */
641 NSView *view = FRAME_NS_VIEW (f);
642 NSRect r = [view frame];
644 NSTRACE (ns_update_begin);
646 ns_update_auto_hide_menu_bar ();
648 ns_updating_frame = f;
651 /* drawRect may have been called for say the minibuffer, and then clip path
652 is for the minibuffer. But the display engine may draw more because
653 we have set the frame as garbaged. So reset clip path to the whole
655 bp = [[NSBezierPath bezierPathWithRect: r] retain];
659 #ifdef NS_IMPL_GNUSTEP
660 uRect = NSMakeRect (0, 0, 0, 0);
666 ns_update_window_begin (struct window *w)
667 /* --------------------------------------------------------------------------
668 Prepare for a grouped sequence of drawing calls
669 external (RIF) call; for one window, called after update_begin
670 -------------------------------------------------------------------------- */
672 struct frame *f = XFRAME (WINDOW_FRAME (w));
673 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
674 NSTRACE (ns_update_window_begin);
676 set_output_cursor (&w->cursor);
680 if (f == hlinfo->mouse_face_mouse_frame)
682 /* Don't do highlighting for mouse motion during the update. */
683 hlinfo->mouse_face_defer = 1;
685 /* If the frame needs to be redrawn,
686 simply forget about any prior mouse highlighting. */
687 if (FRAME_GARBAGED_P (f))
688 hlinfo->mouse_face_window = Qnil;
690 /* (further code for mouse faces ifdef'd out in other terms elided) */
698 ns_update_window_end (struct window *w, int cursor_on_p,
699 int mouse_face_overwritten_p)
700 /* --------------------------------------------------------------------------
701 Finished a grouped sequence of drawing calls
702 external (RIF) call; for one window called before update_end
703 -------------------------------------------------------------------------- */
705 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (XFRAME (w->frame));
707 /* note: this fn is nearly identical in all terms */
708 if (!w->pseudo_window_p)
713 display_and_set_cursor (w, 1,
714 output_cursor.hpos, output_cursor.vpos,
715 output_cursor.x, output_cursor.y);
717 if (draw_window_fringes (w, 1))
718 x_draw_vertical_border (w);
723 /* If a row with mouse-face was overwritten, arrange for
724 frame_up_to_date to redisplay the mouse highlight. */
725 if (mouse_face_overwritten_p)
727 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
728 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
729 hlinfo->mouse_face_window = Qnil;
732 updated_window = NULL;
733 NSTRACE (update_window_end);
738 ns_update_end (struct frame *f)
739 /* --------------------------------------------------------------------------
740 Finished a grouped sequence of drawing calls
741 external (RIF) call; for whole frame, called after update_window_end
742 -------------------------------------------------------------------------- */
744 NSView *view = FRAME_NS_VIEW (f);
746 /* if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
747 MOUSE_HL_INFO (f)->mouse_face_defer = 0;
751 #ifdef NS_IMPL_GNUSTEP
752 /* trigger flush only in the rectangle we tracked as being drawn */
753 [view unlockFocusNeedsFlush: NO];
754 /*fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", uRect.origin.x, uRect.origin.y, uRect.size.width, uRect.size.height); */
755 [view lockFocusInRect: uRect];
759 [[view window] flushWindow];
762 ns_updating_frame = NULL;
763 NSTRACE (ns_update_end);
768 ns_flush (struct frame *f)
769 /* --------------------------------------------------------------------------
771 NS impl is no-op since currently we flush in ns_update_end and elsewhere
772 -------------------------------------------------------------------------- */
779 ns_focus (struct frame *f, NSRect *r, int n)
780 /* --------------------------------------------------------------------------
781 Internal: Focus on given frame. During small local updates this is used to
782 draw, however during large updates, ns_update_begin and ns_update_end are
783 called to wrap the whole thing, in which case these calls are stubbed out.
784 Except, on GNUstep, we accumulate the rectangle being drawn into, because
785 the back end won't do this automatically, and will just end up flushing
787 -------------------------------------------------------------------------- */
789 // NSTRACE (ns_focus);
790 #ifdef NS_IMPL_GNUSTEP
793 u = NSUnionRect (r[0], r[1]);
798 fprintf (stderr, "focus: %d", c++);
799 if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
800 fprintf (stderr, "\n"); */
802 if (f != ns_updating_frame)
804 NSView *view = FRAME_NS_VIEW (f);
805 if (view != focus_view)
807 if (focus_view != NULL)
809 [focus_view unlockFocus];
810 [[focus_view window] flushWindow];
815 #ifdef NS_IMPL_GNUSTEP
816 r ? [view lockFocusInRect: u] : [view lockFocus];
821 /*if (view) debug_lock++; */
823 #ifdef NS_IMPL_GNUSTEP
826 /* more than one rect being drawn into */
829 [view unlockFocus]; /* add prev rect to redraw list */
830 [view lockFocusInRect: u]; /* focus for draw in new rect */
835 #ifdef NS_IMPL_GNUSTEP
838 /* in batch mode, but in GNUstep must still track rectangles explicitly */
839 uRect = (r ? NSUnionRect (uRect, u) : [FRAME_NS_VIEW (f) visibleRect]);
846 [[NSGraphicsContext currentContext] saveGraphicsState];
848 NSRectClipList (r, 2);
857 ns_unfocus (struct frame *f)
858 /* --------------------------------------------------------------------------
859 Internal: Remove focus on given frame
860 -------------------------------------------------------------------------- */
862 // NSTRACE (ns_unfocus);
866 [[NSGraphicsContext currentContext] restoreGraphicsState];
870 if (f != ns_updating_frame)
872 if (focus_view != NULL)
874 [focus_view unlockFocus];
875 [[focus_view window] flushWindow];
884 ns_clip_to_row (struct window *w, struct glyph_row *row, int area, BOOL gc)
885 /* --------------------------------------------------------------------------
886 Internal (but parallels other terms): Focus drawing on given row
887 -------------------------------------------------------------------------- */
889 struct frame *f = XFRAME (WINDOW_FRAME (w));
891 int window_x, window_y, window_width;
893 window_box (w, area, &window_x, &window_y, &window_width, 0);
895 clip_rect.origin.x = window_x;
896 clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
897 clip_rect.origin.y = max (clip_rect.origin.y, window_y);
898 clip_rect.size.width = window_width;
899 clip_rect.size.height = row->visible_height;
901 ns_focus (f, &clip_rect, 1);
906 ns_ring_bell (struct frame *f)
907 /* --------------------------------------------------------------------------
909 -------------------------------------------------------------------------- */
911 NSTRACE (ns_ring_bell);
914 NSAutoreleasePool *pool;
915 struct frame *frame = SELECTED_FRAME ();
919 pool = [[NSAutoreleasePool alloc] init];
921 view = FRAME_NS_VIEW (frame);
925 NSPoint dim = NSMakePoint (128, 128);
928 r.origin.x += (r.size.width - dim.x) / 2;
929 r.origin.y += (r.size.height - dim.y) / 2;
930 r.size.width = dim.x;
931 r.size.height = dim.y;
932 surr = NSInsetRect (r, -2, -2);
933 ns_focus (frame, &surr, 1);
934 [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
935 [ns_lookup_indexed_color (NS_FACE_FOREGROUND
936 (FRAME_DEFAULT_FACE (frame)), frame) set];
938 [[view window] flushWindow];
940 [[view window] restoreCachedImage];
941 [[view window] flushWindow];
955 ns_reset_terminal_modes (struct terminal *terminal)
956 /* Externally called as hook */
958 NSTRACE (ns_reset_terminal_modes);
963 ns_set_terminal_modes (struct terminal *terminal)
964 /* Externally called as hook */
966 NSTRACE (ns_set_terminal_modes);
971 /* ==========================================================================
973 Frame / window manager related functions
975 ========================================================================== */
979 ns_raise_frame (struct frame *f)
980 /* --------------------------------------------------------------------------
981 Bring window to foreground and make it active
982 -------------------------------------------------------------------------- */
984 NSView *view = FRAME_NS_VIEW (f);
987 FRAME_SAMPLE_VISIBILITY (f);
988 if (FRAME_VISIBLE_P (f))
990 [[view window] makeKeyAndOrderFront: NSApp];
997 ns_lower_frame (struct frame *f)
998 /* --------------------------------------------------------------------------
1000 -------------------------------------------------------------------------- */
1002 NSView *view = FRAME_NS_VIEW (f);
1005 [[view window] orderBack: NSApp];
1011 ns_frame_raise_lower (struct frame *f, int raise)
1012 /* --------------------------------------------------------------------------
1014 -------------------------------------------------------------------------- */
1016 NSTRACE (ns_frame_raise_lower);
1026 ns_frame_rehighlight (struct frame *frame)
1027 /* --------------------------------------------------------------------------
1028 External (hook): called on things like window switching within frame
1029 -------------------------------------------------------------------------- */
1031 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
1032 struct frame *old_highlight = dpyinfo->x_highlight_frame;
1034 NSTRACE (ns_frame_rehighlight);
1035 if (dpyinfo->x_focus_frame)
1037 dpyinfo->x_highlight_frame
1038 = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1039 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1040 : dpyinfo->x_focus_frame);
1041 if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
1043 fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
1044 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
1048 dpyinfo->x_highlight_frame = 0;
1050 if (dpyinfo->x_highlight_frame &&
1051 dpyinfo->x_highlight_frame != old_highlight)
1055 x_update_cursor (old_highlight, 1);
1056 x_set_frame_alpha (old_highlight);
1058 if (dpyinfo->x_highlight_frame)
1060 x_update_cursor (dpyinfo->x_highlight_frame, 1);
1061 x_set_frame_alpha (dpyinfo->x_highlight_frame);
1068 x_make_frame_visible (struct frame *f)
1069 /* --------------------------------------------------------------------------
1070 External: Show the window (X11 semantics)
1071 -------------------------------------------------------------------------- */
1073 NSTRACE (x_make_frame_visible);
1074 /* XXX: at some points in past this was not needed, as the only place that
1075 called this (frame.c:Fraise_frame ()) also called raise_lower;
1076 if this ends up the case again, comment this out again. */
1077 if (!FRAME_VISIBLE_P (f))
1079 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1080 f->async_visible = 1;
1084 /* Making a new frame from a fullscreen frame will make the new frame
1085 fullscreen also. So skip handleFS as this will print an error. */
1086 if (f->want_fullscreen == FULLSCREEN_BOTH
1087 && ([[view window] styleMask] & NSFullScreenWindowMask) != 0)
1090 if (f->want_fullscreen != FULLSCREEN_NONE)
1101 x_make_frame_invisible (struct frame *f)
1102 /* --------------------------------------------------------------------------
1103 External: Hide the window (X11 semantics)
1104 -------------------------------------------------------------------------- */
1106 NSView * view = FRAME_NS_VIEW (f);
1107 NSTRACE (x_make_frame_invisible);
1109 [[view window] orderOut: NSApp];
1110 f->async_visible = 0;
1111 f->async_iconified = 0;
1116 x_iconify_frame (struct frame *f)
1117 /* --------------------------------------------------------------------------
1118 External: Iconify window
1119 -------------------------------------------------------------------------- */
1121 NSView * view = FRAME_NS_VIEW (f);
1122 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1123 NSTRACE (x_iconify_frame);
1126 if (dpyinfo->x_highlight_frame == f)
1127 dpyinfo->x_highlight_frame = 0;
1129 if ([[view window] windowNumber] <= 0)
1131 /* the window is still deferred. Make it very small, bring it
1132 on screen and order it out. */
1133 NSRect s = { { 100, 100}, {0, 0} };
1135 t = [[view window] frame];
1136 [[view window] setFrame: s display: NO];
1137 [[view window] orderBack: NSApp];
1138 [[view window] orderOut: NSApp];
1139 [[view window] setFrame: t display: NO];
1141 [[view window] miniaturize: NSApp];
1144 /* Free X resources of frame F. */
1147 x_free_frame_resources (struct frame *f)
1149 NSView *view = FRAME_NS_VIEW (f);
1150 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1151 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1152 NSTRACE (x_free_frame_resources);
1155 [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1159 free_frame_menubar (f);
1161 if (FRAME_FACE_CACHE (f))
1162 free_frame_faces (f);
1164 if (f == dpyinfo->x_focus_frame)
1165 dpyinfo->x_focus_frame = 0;
1166 if (f == dpyinfo->x_highlight_frame)
1167 dpyinfo->x_highlight_frame = 0;
1168 if (f == hlinfo->mouse_face_mouse_frame)
1170 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
1171 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
1172 hlinfo->mouse_face_window = Qnil;
1173 hlinfo->mouse_face_deferred_gc = 0;
1174 hlinfo->mouse_face_mouse_frame = 0;
1177 if (f->output_data.ns->miniimage != nil)
1178 [f->output_data.ns->miniimage release];
1180 [[view window] close];
1183 xfree (f->output_data.ns);
1189 x_destroy_window (struct frame *f)
1190 /* --------------------------------------------------------------------------
1191 External: Delete the window
1192 -------------------------------------------------------------------------- */
1194 NSTRACE (x_destroy_window);
1196 x_free_frame_resources (f);
1202 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1203 /* --------------------------------------------------------------------------
1204 External: Position the window
1205 -------------------------------------------------------------------------- */
1207 NSView *view = FRAME_NS_VIEW (f);
1208 NSArray *screens = [NSScreen screens];
1209 NSScreen *fscreen = [screens objectAtIndex: 0];
1210 NSScreen *screen = [[view window] screen];
1212 NSTRACE (x_set_offset);
1219 if (view != nil && screen && fscreen)
1221 f->left_pos = f->size_hint_flags & XNegative
1222 ? [screen visibleFrame].size.width + f->left_pos - FRAME_PIXEL_WIDTH (f)
1224 /* We use visibleFrame here to take menu bar into account.
1225 Ideally we should also adjust left/top with visibleFrame.origin. */
1227 f->top_pos = f->size_hint_flags & YNegative
1228 ? ([screen visibleFrame].size.height + f->top_pos
1229 - FRAME_PIXEL_HEIGHT (f) - FRAME_NS_TITLEBAR_HEIGHT (f)
1230 - FRAME_TOOLBAR_HEIGHT (f))
1232 #ifdef NS_IMPL_GNUSTEP
1233 if (f->left_pos < 100)
1234 f->left_pos = 100; /* don't overlap menu */
1236 /* Constrain the setFrameTopLeftPoint so we don't move behind the
1238 f->output_data.ns->dont_constrain = 0;
1239 [[view window] setFrameTopLeftPoint:
1240 NSMakePoint (SCREENMAXBOUND (f->left_pos),
1241 SCREENMAXBOUND ([fscreen frame].size.height
1242 - NS_TOP_POS (f)))];
1243 f->size_hint_flags &= ~(XNegative|YNegative);
1251 x_set_window_size (struct frame *f, int change_grav, int cols, int rows)
1252 /* --------------------------------------------------------------------------
1253 Adjust window pixel size based on given character grid size
1254 Impl is a bit more complex than other terms, need to do some
1256 -------------------------------------------------------------------------- */
1258 EmacsView *view = FRAME_NS_VIEW (f);
1259 NSWindow *window = [view window];
1260 NSRect wr = [window frame];
1261 int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1262 int pixelwidth, pixelheight;
1264 NSTRACE (x_set_window_size);
1269 /*fprintf (stderr, "\tsetWindowSize: %d x %d, font size %d x %d\n", cols, rows, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f)); */
1273 check_frame_size (f, &rows, &cols);
1275 f->scroll_bar_actual_width = NS_SCROLL_BAR_WIDTH (f);
1276 compute_fringe_widths (f, 0);
1278 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols);
1279 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
1281 /* If we have a toolbar, take its height into account. */
1283 /* NOTE: previously this would generate wrong result if toolbar not
1284 yet displayed and fixing toolbar_height=32 helped, but
1285 now (200903) seems no longer needed */
1286 FRAME_TOOLBAR_HEIGHT (f) =
1287 NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1288 - FRAME_NS_TITLEBAR_HEIGHT (f);
1290 FRAME_TOOLBAR_HEIGHT (f) = 0;
1292 wr.size.width = pixelwidth + f->border_width;
1293 wr.size.height = pixelheight + FRAME_NS_TITLEBAR_HEIGHT (f)
1294 + FRAME_TOOLBAR_HEIGHT (f);
1296 /* Do not try to constrain to this screen. We may have multiple
1297 screens, and want Emacs to span those. Constraining to screen
1298 prevents that, and that is not nice to the user. */
1299 if (f->output_data.ns->zooming)
1300 f->output_data.ns->zooming = 0;
1302 wr.origin.y += FRAME_PIXEL_HEIGHT (f) - pixelheight;
1304 [view setRows: rows andColumns: cols];
1305 [window setFrame: wr display: YES];
1307 /*fprintf (stderr, "\tx_set_window_size %d, %d\t%d, %d\n", cols, rows, pixelwidth, pixelheight); */
1309 /* This is a trick to compensate for Emacs' managing the scrollbar area
1310 as a fixed number of standard character columns. Instead of leaving
1311 blank space for the extra, we chopped it off above. Now for
1312 left-hand scrollbars, we shift all rendering to the left by the
1313 difference between the real width and Emacs' imagined one. For
1314 right-hand bars, don't worry about it since the extra is never used.
1315 (Obviously doesn't work for vertically split windows tho..) */
1317 NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1318 ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1319 - NS_SCROLL_BAR_WIDTH (f), 0)
1320 : NSMakePoint (0, 0);
1321 [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1322 [view setBoundsOrigin: origin];
1325 change_frame_size (f, rows, cols, 0, 1, 0); /* pretend, delay, safe */
1326 FRAME_PIXEL_WIDTH (f) = pixelwidth;
1327 FRAME_PIXEL_HEIGHT (f) = pixelheight;
1328 /* SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */
1330 mark_window_cursors_off (XWINDOW (f->root_window));
1331 cancel_mouse_face (f);
1338 ns_fullscreen_hook (FRAME_PTR f)
1340 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1342 if (! f->async_visible) return;
1343 #ifndef NEW_STYLE_FS
1344 if (f->want_fullscreen == FULLSCREEN_BOTH)
1346 /* Old style fs don't initiate correctly if created from
1347 init/default-frame alist, so use a timer (not nice...).
1349 [NSTimer scheduledTimerWithTimeInterval: 0.5 target: view
1350 selector: @selector (handleFS)
1351 userInfo: nil repeats: NO];
1361 /* ==========================================================================
1365 ========================================================================== */
1369 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1371 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1372 if (idx < 1 || idx >= color_table->avail)
1374 return color_table->colors[idx];
1379 ns_index_color (NSColor *color, struct frame *f)
1381 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1385 if (!color_table->colors)
1387 color_table->size = NS_COLOR_CAPACITY;
1388 color_table->avail = 1; /* skip idx=0 as marker */
1389 color_table->colors = xmalloc (color_table->size * sizeof (NSColor *));
1390 color_table->colors[0] = nil;
1391 color_table->empty_indices = [[NSMutableSet alloc] init];
1394 /* do we already have this color ? */
1395 for (i = 1; i < color_table->avail; i++)
1396 if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1399 if ([color_table->empty_indices count] > 0)
1401 NSNumber *index = [color_table->empty_indices anyObject];
1402 [color_table->empty_indices removeObject: index];
1403 idx = [index unsignedLongValue];
1407 if (color_table->avail == color_table->size)
1408 color_table->colors =
1409 xpalloc (color_table->colors, &color_table->size, 1,
1410 min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1411 idx = color_table->avail++;
1414 color_table->colors[idx] = color;
1416 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1422 ns_free_indexed_color (unsigned long idx, struct frame *f)
1424 struct ns_color_table *color_table;
1431 color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1433 if (idx <= 0 || idx >= color_table->size) {
1434 message1 ("ns_free_indexed_color: Color index out of range.\n");
1438 index = [NSNumber numberWithUnsignedInt: idx];
1439 if ([color_table->empty_indices containsObject: index]) {
1440 message1 ("ns_free_indexed_color: attempt to free already freed color.\n");
1444 color = color_table->colors[idx];
1446 color_table->colors[idx] = nil;
1447 [color_table->empty_indices addObject: index];
1448 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1453 ns_get_color (const char *name, NSColor **col)
1454 /* --------------------------------------------------------------------------
1456 -------------------------------------------------------------------------- */
1457 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1458 X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1459 See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1462 static char hex[20];
1464 float r = -1.0, g, b;
1465 NSString *nsname = [NSString stringWithUTF8String: name];
1467 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1470 if ([nsname isEqualToString: @"ns_selection_color"])
1472 nsname = ns_selection_color;
1473 name = [ns_selection_color UTF8String];
1476 /* First, check for some sort of numeric specification. */
1479 if (name[0] == '0' || name[0] == '1' || name[0] == '.') /* RGB decimal */
1481 NSScanner *scanner = [NSScanner scannerWithString: nsname];
1482 [scanner scanFloat: &r];
1483 [scanner scanFloat: &g];
1484 [scanner scanFloat: &b];
1486 else if (!strncmp(name, "rgb:", 4)) /* A newer X11 format -- rgb:r/g/b */
1487 scaling = (snprintf (hex, sizeof hex, "%s", name + 4) - 2) / 3;
1488 else if (name[0] == '#') /* An old X11 format; convert to newer */
1490 int len = (strlen(name) - 1);
1491 int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1493 scaling = strlen(name+start) / 3;
1494 for (i = 0; i < 3; i++)
1495 sprintf (hex + i * (scaling + 1), "%.*s/", scaling,
1496 name + start + i * scaling);
1497 hex[3 * (scaling + 1) - 1] = '\0';
1503 float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1504 if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1514 *col = [NSColor colorWithCalibratedRed: r green: g blue: b alpha: 1.0];
1519 /* Otherwise, color is expected to be from a list */
1521 NSEnumerator *lenum, *cenum;
1525 #ifdef NS_IMPL_GNUSTEP
1526 /* XXX: who is wrong, the requestor or the implementation? */
1527 if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1529 nsname = @"highlightColor";
1532 lenum = [[NSColorList availableColorLists] objectEnumerator];
1533 while ( (clist = [lenum nextObject]) && new == nil)
1535 cenum = [[clist allKeys] objectEnumerator];
1536 while ( (name = [cenum nextObject]) && new == nil )
1538 if ([name compare: nsname
1539 options: NSCaseInsensitiveSearch] == NSOrderedSame )
1540 new = [clist colorWithKey: name];
1546 *col = [new colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1553 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1554 /* --------------------------------------------------------------------------
1555 Convert a Lisp string object to a NS color
1556 -------------------------------------------------------------------------- */
1558 NSTRACE (ns_lisp_to_color);
1559 if (STRINGP (color))
1560 return ns_get_color (SSDATA (color), col);
1561 else if (SYMBOLP (color))
1562 return ns_get_color (SSDATA (SYMBOL_NAME (color)), col);
1568 ns_color_to_lisp (NSColor *col)
1569 /* --------------------------------------------------------------------------
1570 Convert a color to a lisp string with the RGB equivalent
1571 -------------------------------------------------------------------------- */
1573 CGFloat red, green, blue, alpha, gray;
1576 NSTRACE (ns_color_to_lisp);
1579 if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1581 if ((str =[[col colorNameComponent] UTF8String]))
1584 return build_string ((char *)str);
1587 [[col colorUsingColorSpaceName: NSCalibratedRGBColorSpace]
1588 getRed: &red green: &green blue: &blue alpha: &alpha];
1589 if (red ==green && red ==blue)
1591 [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1592 getWhite: &gray alpha: &alpha];
1593 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1594 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1596 return build_string (buf);
1599 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1600 lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1603 return build_string (buf);
1608 ns_query_color(void *col, XColor *color_def, int setPixel)
1609 /* --------------------------------------------------------------------------
1610 Get ARGB values out of NSColor col and put them into color_def.
1611 If setPixel, set the pixel to a concatenated version.
1612 and set color_def pixel to the resulting index.
1613 -------------------------------------------------------------------------- */
1617 [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1618 color_def->red = r * 65535;
1619 color_def->green = g * 65535;
1620 color_def->blue = b * 65535;
1622 if (setPixel == YES)
1624 = ARGB_TO_ULONG((int)(a*255),
1625 (int)(r*255), (int)(g*255), (int)(b*255));
1630 ns_defined_color (struct frame *f,
1635 /* --------------------------------------------------------------------------
1636 Return true if named color found, and set color_def rgb accordingly.
1637 If makeIndex and alloc are nonzero put the color in the color_table,
1638 and set color_def pixel to the resulting index.
1639 If makeIndex is zero, set color_def pixel to ARGB.
1640 Return false if not found
1641 -------------------------------------------------------------------------- */
1644 NSTRACE (ns_defined_color);
1647 if (ns_get_color (name, &col) != 0) /* Color not found */
1652 if (makeIndex && alloc)
1653 color_def->pixel = ns_index_color (col, f);
1654 ns_query_color (col, color_def, !makeIndex);
1661 ns_get_rgb_color (struct frame *f, float r, float g, float b, float a)
1662 /* --------------------------------------------------------------------------
1663 return an autoreleased RGB color
1664 -------------------------------------------------------------------------- */
1666 /*static int c = 1; fprintf (stderr, "color request %d\n", c++); */
1667 if (r < 0.0) r = 0.0;
1668 else if (r > 1.0) r = 1.0;
1669 if (g < 0.0) g = 0.0;
1670 else if (g > 1.0) g = 1.0;
1671 if (b < 0.0) b = 0.0;
1672 else if (b > 1.0) b = 1.0;
1673 if (a < 0.0) a = 0.0;
1674 else if (a > 1.0) a = 1.0;
1675 return (unsigned long) ns_index_color(
1676 [NSColor colorWithCalibratedRed: r green: g blue: b alpha: a], f);
1681 x_set_frame_alpha (struct frame *f)
1682 /* --------------------------------------------------------------------------
1683 change the entire-frame transparency
1684 -------------------------------------------------------------------------- */
1686 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1687 EmacsView *view = FRAME_NS_VIEW (f);
1689 double alpha_min = 1.0;
1691 if (dpyinfo->x_highlight_frame == f)
1692 alpha = f->alpha[0];
1694 alpha = f->alpha[1];
1696 if (FLOATP (Vframe_alpha_lower_limit))
1697 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1698 else if (INTEGERP (Vframe_alpha_lower_limit))
1699 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1703 else if (1.0 < alpha)
1705 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1708 #ifdef NS_IMPL_COCOA
1709 [[view window] setAlphaValue: alpha];
1714 /* ==========================================================================
1718 ========================================================================== */
1722 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1723 /* --------------------------------------------------------------------------
1724 Programmatically reposition mouse pointer in pixel coordinates
1725 -------------------------------------------------------------------------- */
1727 NSTRACE (x_set_mouse_pixel_position);
1730 /* FIXME: this does not work, and what about GNUstep? */
1731 #ifdef NS_IMPL_COCOA
1732 [FRAME_NS_VIEW (f) lockFocus];
1733 PSsetmouse ((float)pix_x, (float)pix_y);
1734 [FRAME_NS_VIEW (f) unlockFocus];
1741 x_set_mouse_position (struct frame *f, int h, int v)
1742 /* --------------------------------------------------------------------------
1743 Programmatically reposition mouse pointer in character coordinates
1744 -------------------------------------------------------------------------- */
1748 pix_x = FRAME_COL_TO_PIXEL_X (f, h) + FRAME_COLUMN_WIDTH (f) / 2;
1749 pix_y = FRAME_LINE_TO_PIXEL_Y (f, v) + FRAME_LINE_HEIGHT (f) / 2;
1751 if (pix_x < 0) pix_x = 0;
1752 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
1754 if (pix_y < 0) pix_y = 0;
1755 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
1757 x_set_mouse_pixel_position (f, pix_x, pix_y);
1762 note_mouse_movement (struct frame *frame, float x, float y)
1763 /* ------------------------------------------------------------------------
1764 Called by EmacsView on mouseMovement events. Passes on
1765 to emacs mainstream code if we moved off of a rect of interest
1766 known as last_mouse_glyph.
1767 ------------------------------------------------------------------------ */
1769 // NSTRACE (note_mouse_movement);
1771 XSETFRAME (last_mouse_motion_frame, frame);
1773 /* Note, this doesn't get called for enter/leave, since we don't have a
1774 position. Those are taken care of in the corresponding NSView methods. */
1776 /* has movement gone beyond last rect we were tracking? */
1777 if (x < last_mouse_glyph.origin.x ||
1778 x >= (last_mouse_glyph.origin.x + last_mouse_glyph.size.width) ||
1779 y < last_mouse_glyph.origin.y ||
1780 y >= (last_mouse_glyph.origin.y + last_mouse_glyph.size.height))
1782 ns_update_begin(frame);
1783 frame->mouse_moved = 1;
1784 note_mouse_highlight (frame, x, y);
1785 remember_mouse_glyph (frame, x, y, &last_mouse_glyph);
1786 ns_update_end(frame);
1795 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1796 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1798 /* --------------------------------------------------------------------------
1799 External (hook): inform emacs about mouse position and hit parts.
1800 If a scrollbar is being dragged, set bar_window, part, x, y, time.
1801 x & y should be position in the scrollbar (the whole bar, not the handle)
1802 and length of scrollbar respectively
1803 -------------------------------------------------------------------------- */
1807 Lisp_Object frame, tail;
1809 struct ns_display_info *dpyinfo;
1811 NSTRACE (ns_mouse_position);
1815 fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1819 dpyinfo = FRAME_NS_DISPLAY_INFO (*fp);
1823 if (last_mouse_scroll_bar != nil && insist == 0)
1825 /* TODO: we do not use this path at the moment because drag events will
1826 go directly to the EmacsScroller. Leaving code in for now. */
1827 [last_mouse_scroll_bar getMouseMotionPart: (int *)part window: bar_window
1829 if (time) *time = last_mouse_movement_time;
1830 last_mouse_scroll_bar = nil;
1834 /* Clear the mouse-moved flag for every frame on this display. */
1835 FOR_EACH_FRAME (tail, frame)
1836 if (FRAME_NS_P (XFRAME (frame))
1837 && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1838 XFRAME (frame)->mouse_moved = 0;
1840 last_mouse_scroll_bar = nil;
1841 if (last_mouse_frame && FRAME_LIVE_P (last_mouse_frame))
1842 f = last_mouse_frame;
1844 f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame
1845 : SELECTED_FRAME ();
1847 if (f && f->output_data.ns) /* TODO: 2nd check no longer needed? */
1849 view = FRAME_NS_VIEW (*fp);
1851 position = [[view window] mouseLocationOutsideOfEventStream];
1852 position = [view convertPoint: position fromView: nil];
1853 remember_mouse_glyph (f, position.x, position.y, &last_mouse_glyph);
1854 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1856 if (bar_window) *bar_window = Qnil;
1857 if (part) *part = 0; /*scroll_bar_handle; */
1859 if (x) XSETINT (*x, lrint (position.x));
1860 if (y) XSETINT (*y, lrint (position.y));
1861 if (time) *time = last_mouse_movement_time;
1871 ns_frame_up_to_date (struct frame *f)
1872 /* --------------------------------------------------------------------------
1873 External (hook): Fix up mouse highlighting right after a full update.
1874 Some highlighting was deferred if GC was happening during
1875 note_mouse_highlight (), while other highlighting was deferred for update.
1876 -------------------------------------------------------------------------- */
1878 NSTRACE (ns_frame_up_to_date);
1882 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1883 if ((hlinfo->mouse_face_deferred_gc || f ==hlinfo->mouse_face_mouse_frame)
1884 /*&& hlinfo->mouse_face_mouse_frame*/)
1888 if (hlinfo->mouse_face_mouse_frame)
1889 note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
1890 hlinfo->mouse_face_mouse_x,
1891 hlinfo->mouse_face_mouse_y);
1892 hlinfo->mouse_face_deferred_gc = 0;
1901 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1902 /* --------------------------------------------------------------------------
1903 External (RIF): set frame mouse pointer type.
1904 -------------------------------------------------------------------------- */
1906 NSTRACE (ns_define_frame_cursor);
1907 if (FRAME_POINTER_TYPE (f) != cursor)
1909 EmacsView *view = FRAME_NS_VIEW (f);
1910 FRAME_POINTER_TYPE (f) = cursor;
1911 [[view window] invalidateCursorRectsForView: view];
1912 /* Redisplay assumes this function also draws the changed frame
1913 cursor, but this function doesn't, so do it explicitly. */
1914 x_update_cursor (f, 1);
1920 /* ==========================================================================
1924 ========================================================================== */
1928 ns_convert_key (unsigned code)
1929 /* --------------------------------------------------------------------------
1930 Internal call used by NSView-keyDown.
1931 -------------------------------------------------------------------------- */
1933 const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym)
1934 / sizeof (convert_ns_to_X_keysym[0]));
1936 /* An array would be faster, but less easy to read. */
1937 for (keysym = 0; keysym < last_keysym; keysym += 2)
1938 if (code == convert_ns_to_X_keysym[keysym])
1939 return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
1941 /* if decide to use keyCode and Carbon table, use this line:
1942 return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
1947 x_get_keysym_name (int keysym)
1948 /* --------------------------------------------------------------------------
1949 Called by keyboard.c. Not sure if the return val is important, except
1951 -------------------------------------------------------------------------- */
1953 static char value[16];
1954 NSTRACE (x_get_keysym_name);
1955 sprintf (value, "%d", keysym);
1961 /* ==========================================================================
1963 Block drawing operations
1965 ========================================================================== */
1969 ns_redraw_scroll_bars (struct frame *f)
1973 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
1974 NSTRACE (ns_redraw_scroll_bars);
1975 for (i =[subviews count]-1; i >= 0; i--)
1977 view = [subviews objectAtIndex: i];
1978 if (![view isKindOfClass: [EmacsScroller class]]) continue;
1985 ns_clear_frame (struct frame *f)
1986 /* --------------------------------------------------------------------------
1987 External (hook): Erase the entire frame
1988 -------------------------------------------------------------------------- */
1990 NSView *view = FRAME_NS_VIEW (f);
1993 NSTRACE (ns_clear_frame);
1995 /* comes on initial frame because we have
1996 after-make-frame-functions = select-frame */
1997 if (!FRAME_DEFAULT_FACE (f))
2000 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2002 output_cursor.hpos = output_cursor.vpos = 0;
2003 output_cursor.x = -1;
2008 ns_focus (f, &r, 1);
2009 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
2013 /* as of 2006/11 or so this is now needed */
2014 ns_redraw_scroll_bars (f);
2020 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2021 /* --------------------------------------------------------------------------
2022 External (RIF): Clear section of frame
2023 -------------------------------------------------------------------------- */
2025 NSRect r = NSMakeRect (x, y, width, height);
2026 NSView *view = FRAME_NS_VIEW (f);
2027 struct face *face = FRAME_DEFAULT_FACE (f);
2032 NSTRACE (ns_clear_frame_area);
2034 r = NSIntersectionRect (r, [view frame]);
2035 ns_focus (f, &r, 1);
2036 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2046 ns_scroll_run (struct window *w, struct run *run)
2047 /* --------------------------------------------------------------------------
2048 External (RIF): Insert or delete n lines at line vpos
2049 -------------------------------------------------------------------------- */
2051 struct frame *f = XFRAME (w->frame);
2052 int x, y, width, height, from_y, to_y, bottom_y;
2054 NSTRACE (ns_scroll_run);
2056 /* begin copy from other terms */
2057 /* Get frame-relative bounding box of the text display area of W,
2058 without mode lines. Include in this box the left and right
2060 window_box (w, -1, &x, &y, &width, &height);
2062 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2063 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2064 bottom_y = y + height;
2068 /* Scrolling up. Make sure we don't copy part of the mode
2069 line at the bottom. */
2070 if (from_y + run->height > bottom_y)
2071 height = bottom_y - from_y;
2073 height = run->height;
2077 /* Scrolling down. Make sure we don't copy over the mode line.
2079 if (to_y + run->height > bottom_y)
2080 height = bottom_y - to_y;
2082 height = run->height;
2084 /* end copy from other terms */
2095 NSRect srcRect = NSMakeRect (x, from_y, width, height);
2096 NSRect dstRect = NSMakeRect (x, to_y, width, height);
2097 NSPoint dstOrigin = NSMakePoint (x, to_y);
2099 ns_focus (f, &dstRect, 1);
2100 NSCopyBits (0, srcRect , dstOrigin);
2109 ns_after_update_window_line (struct glyph_row *desired_row)
2110 /* --------------------------------------------------------------------------
2111 External (RIF): preparatory to fringe update after text was updated
2112 -------------------------------------------------------------------------- */
2114 struct window *w = updated_window;
2118 NSTRACE (ns_after_update_window_line);
2120 /* begin copy from other terms */
2123 if (!desired_row->mode_line_p && !w->pseudo_window_p)
2124 desired_row->redraw_fringe_bitmaps_p = 1;
2126 /* When a window has disappeared, make sure that no rest of
2127 full-width rows stays visible in the internal border. */
2128 if (windows_or_buffers_changed
2129 && desired_row->full_width_p
2130 && (f = XFRAME (w->frame),
2131 width = FRAME_INTERNAL_BORDER_WIDTH (f),
2133 && (height = desired_row->visible_height,
2136 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2139 ns_clear_frame_area (f, 0, y, width, height);
2140 ns_clear_frame_area (f,
2141 FRAME_PIXEL_WIDTH (f) - width,
2149 ns_shift_glyphs_for_insert (struct frame *f,
2150 int x, int y, int width, int height,
2152 /* --------------------------------------------------------------------------
2153 External (RIF): copy an area horizontally, don't worry about clearing src
2154 -------------------------------------------------------------------------- */
2156 NSRect srcRect = NSMakeRect (x, y, width, height);
2157 NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2158 NSPoint dstOrigin = dstRect.origin;
2160 NSTRACE (ns_shift_glyphs_for_insert);
2162 ns_focus (f, &dstRect, 1);
2163 NSCopyBits (0, srcRect, dstOrigin);
2169 /* ==========================================================================
2171 Character encoding and metrics
2173 ========================================================================== */
2177 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2178 /* --------------------------------------------------------------------------
2179 External (RIF); compute left/right overhang of whole string and set in s
2180 -------------------------------------------------------------------------- */
2182 struct font *font = s->font;
2186 struct font_metrics metrics;
2187 unsigned int codes[2];
2188 codes[0] = *(s->char2b);
2189 codes[1] = *(s->char2b + s->nchars - 1);
2191 font->driver->text_extents (font, codes, 2, &metrics);
2192 s->left_overhang = -metrics.lbearing;
2194 = metrics.rbearing > metrics.width
2195 ? metrics.rbearing - metrics.width : 0;
2199 s->left_overhang = 0;
2200 s->right_overhang = ((struct nsfont_info *)font)->ital ?
2201 FONT_HEIGHT (font) * 0.2 : 0;
2207 /* ==========================================================================
2209 Fringe and cursor drawing
2211 ========================================================================== */
2214 extern int max_used_fringe_bitmap;
2216 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2217 struct draw_fringe_bitmap_params *p)
2218 /* --------------------------------------------------------------------------
2219 External (RIF); fringe-related
2220 -------------------------------------------------------------------------- */
2222 struct frame *f = XFRAME (WINDOW_FRAME (w));
2223 struct face *face = p->face;
2225 static EmacsImage **bimgs = NULL;
2226 static int nBimgs = 0;
2228 /* grow bimgs if needed */
2229 if (nBimgs < max_used_fringe_bitmap)
2231 bimgs = xrealloc (bimgs, max_used_fringe_bitmap * sizeof *bimgs);
2232 memset (bimgs + nBimgs, 0,
2233 (max_used_fringe_bitmap - nBimgs) * sizeof *bimgs);
2234 nBimgs = max_used_fringe_bitmap;
2237 /* Must clip because of partially visible lines. */
2238 rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
2239 ns_clip_to_row (w, row, -1, YES);
2243 int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
2245 /* If the fringe is adjacent to the left (right) scroll bar of a
2246 leftmost (rightmost, respectively) window, then extend its
2247 background to the gap between the fringe and the bar. */
2248 if ((WINDOW_LEFTMOST_P (w)
2249 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
2250 || (WINDOW_RIGHTMOST_P (w)
2251 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w)))
2253 int sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
2257 int bar_area_x = WINDOW_SCROLL_BAR_AREA_X (w);
2258 int bar_area_width = (WINDOW_CONFIG_SCROLL_BAR_COLS (w)
2259 * FRAME_COLUMN_WIDTH (f));
2263 /* Bitmap fills the fringe. */
2264 if (bar_area_x + bar_area_width == p->x)
2265 bx = bar_area_x + sb_width;
2266 else if (p->x + p->wd == bar_area_x)
2270 int header_line_height = WINDOW_HEADER_LINE_HEIGHT (w);
2272 nx = bar_area_width - sb_width;
2273 by = WINDOW_TO_FRAME_PIXEL_Y (w, max (header_line_height,
2275 ny = row->visible_height;
2280 if (bar_area_x + bar_area_width == bx)
2282 bx = bar_area_x + sb_width;
2283 nx += bar_area_width - sb_width;
2285 else if (bx + nx == bar_area_x)
2286 nx += bar_area_width - sb_width;
2291 if (bx >= 0 && nx > 0)
2293 NSRect r = NSMakeRect (bx, by, nx, ny);
2295 [ns_lookup_indexed_color (face->background, f) set];
2302 NSRect r = NSMakeRect (p->x, p->y, p->wd, p->h);
2303 EmacsImage *img = bimgs[p->which - 1];
2307 unsigned short *bits = p->bits + p->dh;
2310 unsigned char *cbits = xmalloc (len);
2312 for (i = 0; i < len; i++)
2313 cbits[i] = ~(bits[i] & 0xff);
2314 img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2316 bimgs[p->which - 1] = img;
2321 /* Since we composite the bitmap instead of just blitting it, we need
2322 to erase the whole background. */
2323 [ns_lookup_indexed_color(face->background, f) set];
2325 [img setXBMColor: ns_lookup_indexed_color(face->foreground, f)];
2326 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
2328 fromRect: NSZeroRect
2329 operation: NSCompositeSourceOver
2335 NSPoint pt = r.origin;
2337 [img compositeToPoint: pt operation: NSCompositeSourceOver];
2346 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2347 int x, int y, int cursor_type, int cursor_width,
2348 int on_p, int active_p)
2349 /* --------------------------------------------------------------------------
2350 External call (RIF): draw cursor.
2351 Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2352 -------------------------------------------------------------------------- */
2355 int fx, fy, h, cursor_height;
2356 struct frame *f = WINDOW_XFRAME (w);
2357 struct glyph *phys_cursor_glyph;
2359 struct glyph *cursor_glyph;
2361 NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2363 /* If cursor is out of bounds, don't draw garbage. This can happen
2364 in mini-buffer windows when switching between echo area glyphs
2367 NSTRACE (dumpcursor);
2372 w->phys_cursor_type = cursor_type;
2373 w->phys_cursor_on_p = on_p;
2375 if (cursor_type == NO_CURSOR)
2377 w->phys_cursor_width = 0;
2381 if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2383 if (glyph_row->exact_window_width_line_p
2384 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2386 glyph_row->cursor_in_fringe_p = 1;
2387 draw_fringe_bitmap (w, glyph_row, 0);
2392 /* We draw the cursor (with NSRectFill), then draw the glyph on top
2393 (other terminals do it the other way round). We must set
2394 w->phys_cursor_width to the cursor width. For bar cursors, that
2395 is CURSOR_WIDTH; for box cursors, it is the glyph width. */
2396 get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2398 /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2399 to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2400 if (cursor_type == BAR_CURSOR)
2402 if (cursor_width < 1)
2403 cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2404 w->phys_cursor_width = cursor_width;
2406 /* If we have an HBAR, "cursor_width" MAY specify height. */
2407 else if (cursor_type == HBAR_CURSOR)
2409 cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2410 fy += h - cursor_height;
2414 r.origin.x = fx, r.origin.y = fy;
2416 r.size.width = w->phys_cursor_width;
2418 /* TODO: only needed in rare cases with last-resort font in HELLO..
2419 should we do this more efficiently? */
2420 ns_clip_to_row (w, glyph_row, -1, NO); /* do ns_focus(f, &r, 1); if remove */
2423 face = FACE_FROM_ID (f, phys_cursor_glyph->face_id);
2424 if (face && NS_FACE_BACKGROUND (face)
2425 == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2427 [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2428 hollow_color = FRAME_CURSOR_COLOR (f);
2431 [FRAME_CURSOR_COLOR (f) set];
2433 #ifdef NS_IMPL_COCOA
2434 /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2435 atomic. Cleaner ways of doing this should be investigated.
2436 One way would be to set a global variable DRAWING_CURSOR
2437 when making the call to draw_phys..(), don't focus in that
2438 case, then move the ns_unfocus() here after that call. */
2439 NSDisableScreenUpdates ();
2442 switch (cursor_type)
2446 case FILLED_BOX_CURSOR:
2449 case HOLLOW_BOX_CURSOR:
2452 NSRectFill (NSInsetRect (r, 1, 1));
2453 [FRAME_CURSOR_COLOR (f) set];
2460 /* If the character under cursor is R2L, draw the bar cursor
2461 on the right of its glyph, rather than on the left. */
2462 cursor_glyph = get_phys_cursor_glyph (w);
2463 if ((cursor_glyph->resolved_level & 1) != 0)
2464 s.origin.x += cursor_glyph->pixel_width - s.size.width;
2471 /* draw the character under the cursor */
2472 if (cursor_type != NO_CURSOR)
2473 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2475 #ifdef NS_IMPL_COCOA
2476 NSEnableScreenUpdates ();
2483 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2484 /* --------------------------------------------------------------------------
2485 External (RIF): Draw a vertical line.
2486 -------------------------------------------------------------------------- */
2488 struct frame *f = XFRAME (WINDOW_FRAME (w));
2490 NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2492 NSTRACE (ns_draw_vertical_window_border);
2494 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2496 [ns_lookup_indexed_color(face->foreground, f) set];
2498 ns_focus (f, &r, 1);
2505 show_hourglass (struct atimer *timer)
2507 if (hourglass_shown_p)
2512 /* TODO: add NSProgressIndicator to selected frame (see macfns.c) */
2514 hourglass_shown_p = 1;
2520 hide_hourglass (void)
2522 if (!hourglass_shown_p)
2527 /* TODO: remove NSProgressIndicator from all frames */
2529 hourglass_shown_p = 0;
2535 /* ==========================================================================
2537 Glyph drawing operations
2539 ========================================================================== */
2542 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2543 /* --------------------------------------------------------------------------
2544 Wrapper utility to account for internal border width on full-width lines,
2545 and allow top full-width rows to hit the frame top. nr should be pointer
2546 to two successive NSRects. Number of rects actually used is returned.
2547 -------------------------------------------------------------------------- */
2549 int n = get_glyph_string_clip_rects (s, nr, 2);
2553 /* --------------------------------------------------------------------
2554 Draw a wavy line under glyph string s. The wave fills wave_height
2561 wave_height = 3 | * * * *
2562 --------------------------------------------------------------------- */
2565 ns_draw_underwave (struct glyph_string *s, CGFloat width, CGFloat x)
2567 int wave_height = 3, wave_length = 2;
2568 int y, dx, dy, odd, xmax;
2573 dy = wave_height - 1;
2574 y = s->ybase - wave_height + 3;
2577 /* Find and set clipping rectangle */
2578 waveClip = NSMakeRect (x, y, width, wave_height);
2579 [[NSGraphicsContext currentContext] saveGraphicsState];
2580 NSRectClip (waveClip);
2582 /* Draw the waves */
2583 a.x = x - ((int)(x) % dx) + 0.5;
2585 odd = (int)(a.x/dx) % 2;
2586 a.y = b.y = y + 0.5;
2595 [NSBezierPath strokeLineFromPoint:a toPoint:b];
2596 a.x = b.x, a.y = b.y;
2597 b.x += dx, b.y = y + 0.5 + odd*dy;
2601 /* Restore previous clipping rectangle(s) */
2602 [[NSGraphicsContext currentContext] restoreGraphicsState];
2608 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
2609 NSColor *defaultCol, CGFloat width, CGFloat x)
2610 /* --------------------------------------------------------------------------
2611 Draw underline, overline, and strike-through on glyph string s.
2612 -------------------------------------------------------------------------- */
2614 if (s->for_overlaps)
2618 if (face->underline_p)
2620 if (s->face->underline_type == FACE_UNDER_WAVE)
2622 if (face->underline_defaulted_p)
2625 [ns_lookup_indexed_color (face->underline_color, s->f) set];
2627 ns_draw_underwave (s, width, x);
2629 else if (s->face->underline_type == FACE_UNDER_LINE)
2633 unsigned long thickness, position;
2635 /* If the prev was underlined, match its appearance. */
2636 if (s->prev && s->prev->face->underline_p
2637 && s->prev->face->underline_type == FACE_UNDER_LINE
2638 && s->prev->underline_thickness > 0)
2640 thickness = s->prev->underline_thickness;
2641 position = s->prev->underline_position;
2646 unsigned long descent;
2649 descent = s->y + s->height - s->ybase;
2651 /* Use underline thickness of font, defaulting to 1. */
2652 thickness = (font && font->underline_thickness > 0)
2653 ? font->underline_thickness : 1;
2655 /* Determine the offset of underlining from the baseline. */
2656 if (x_underline_at_descent_line)
2657 position = descent - thickness;
2658 else if (x_use_underline_position_properties
2659 && font && font->underline_position >= 0)
2660 position = font->underline_position;
2662 position = lround (font->descent / 2);
2664 position = underline_minimum_offset;
2666 position = max (position, underline_minimum_offset);
2668 /* Ensure underlining is not cropped. */
2669 if (descent <= position)
2671 position = descent - 1;
2674 else if (descent < position + thickness)
2678 s->underline_thickness = thickness;
2679 s->underline_position = position;
2681 r = NSMakeRect (x, s->ybase + position, width, thickness);
2683 if (face->underline_defaulted_p)
2686 [ns_lookup_indexed_color (face->underline_color, s->f) set];
2690 /* Do overline. We follow other terms in using a thickness of 1
2691 and ignoring overline_margin. */
2692 if (face->overline_p)
2695 r = NSMakeRect (x, s->y, width, 1);
2697 if (face->overline_color_defaulted_p)
2700 [ns_lookup_indexed_color (face->overline_color, s->f) set];
2704 /* Do strike-through. We follow other terms for thickness and
2705 vertical position.*/
2706 if (face->strike_through_p)
2711 dy = lrint ((s->height - 1) / 2);
2712 r = NSMakeRect (x, s->y + dy, width, 1);
2714 if (face->strike_through_color_defaulted_p)
2717 [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
2723 ns_draw_box (NSRect r, float thickness, NSColor *col, char left_p, char right_p)
2724 /* --------------------------------------------------------------------------
2725 Draw an unfilled rect inside r, optionally leaving left and/or right open.
2726 Note we can't just use an NSDrawRect command, because of the possibility
2727 of some sides not being drawn, and because the rect will be filled.
2728 -------------------------------------------------------------------------- */
2734 s.size.height = thickness;
2736 s.origin.y += r.size.height - thickness;
2739 s.size.height = r.size.height;
2740 s.origin.y = r.origin.y;
2742 /* left, right (optional) */
2743 s.size.width = thickness;
2748 s.origin.x += r.size.width - thickness;
2755 ns_draw_relief (NSRect r, int thickness, char raised_p,
2756 char top_p, char bottom_p, char left_p, char right_p,
2757 struct glyph_string *s)
2758 /* --------------------------------------------------------------------------
2759 Draw a relief rect inside r, optionally leaving some sides open.
2760 Note we can't just use an NSDrawBezel command, because of the possibility
2761 of some sides not being drawn, and because the rect will be filled.
2762 -------------------------------------------------------------------------- */
2764 static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2765 NSColor *newBaseCol = nil;
2768 NSTRACE (ns_draw_relief);
2772 if (s->face->use_box_color_for_shadows_p)
2774 newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2776 /* else if (s->first_glyph->type == IMAGE_GLYPH
2778 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2780 newBaseCol = IMAGE_BACKGROUND (s->img, s->f, 0);
2784 newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2787 if (newBaseCol == nil)
2788 newBaseCol = [NSColor grayColor];
2790 if (newBaseCol != baseCol) /* TODO: better check */
2793 baseCol = [newBaseCol retain];
2795 lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2797 darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2800 [(raised_p ? lightCol : darkCol) set];
2802 /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2805 sr.size.height = thickness;
2806 if (top_p) NSRectFill (sr);
2809 sr.size.height = r.size.height;
2810 sr.size.width = thickness;
2811 if (left_p) NSRectFill (sr);
2813 [(raised_p ? darkCol : lightCol) set];
2816 sr.size.width = r.size.width;
2817 sr.size.height = thickness;
2818 sr.origin.y += r.size.height - thickness;
2819 if (bottom_p) NSRectFill (sr);
2822 sr.size.height = r.size.height;
2823 sr.origin.y = r.origin.y;
2824 sr.size.width = thickness;
2825 sr.origin.x += r.size.width - thickness;
2826 if (right_p) NSRectFill (sr);
2831 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2832 /* --------------------------------------------------------------------------
2833 Function modeled after x_draw_glyph_string_box ().
2834 Sets up parameters for drawing.
2835 -------------------------------------------------------------------------- */
2837 int right_x, last_x;
2838 char left_p, right_p;
2839 struct glyph *last_glyph;
2844 if (s->hl == DRAW_MOUSE_FACE)
2846 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2848 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2853 thickness = face->box_line_width;
2855 NSTRACE (ns_dumpglyphs_box_or_relief);
2857 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2858 ? WINDOW_RIGHT_EDGE_X (s->w)
2859 : window_box_right (s->w, s->area));
2860 last_glyph = (s->cmp || s->img
2861 ? s->first_glyph : s->first_glyph + s->nchars-1);
2863 right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2864 ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2866 left_p = (s->first_glyph->left_box_line_p
2867 || (s->hl == DRAW_MOUSE_FACE
2868 && (s->prev == NULL || s->prev->hl != s->hl)));
2869 right_p = (last_glyph->right_box_line_p
2870 || (s->hl == DRAW_MOUSE_FACE
2871 && (s->next == NULL || s->next->hl != s->hl)));
2873 r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2875 /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
2876 if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
2878 ns_draw_box (r, abs (thickness),
2879 ns_lookup_indexed_color (face->box_color, s->f),
2884 ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2885 1, 1, left_p, right_p, s);
2891 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2892 /* --------------------------------------------------------------------------
2893 Modeled after x_draw_glyph_string_background, which draws BG in
2894 certain cases. Others are left to the text rendering routine.
2895 -------------------------------------------------------------------------- */
2897 NSTRACE (ns_maybe_dumpglyphs_background);
2899 if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2901 int box_line_width = max (s->face->box_line_width, 0);
2902 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2903 || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2906 if (s->hl == DRAW_MOUSE_FACE)
2908 face = FACE_FROM_ID (s->f,
2909 MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2911 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2914 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2916 [(NS_FACE_BACKGROUND (face) != 0
2917 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2918 : FRAME_BACKGROUND_COLOR (s->f)) set];
2921 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (s->f);
2922 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2925 if (s->hl != DRAW_CURSOR)
2927 NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2928 s->background_width,
2929 s->height-2*box_line_width);
2933 s->background_filled_p = 1;
2940 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2941 /* --------------------------------------------------------------------------
2942 Renders an image and associated borders.
2943 -------------------------------------------------------------------------- */
2945 EmacsImage *img = s->img->pixmap;
2946 int box_line_vwidth = max (s->face->box_line_width, 0);
2947 int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2948 int bg_x, bg_y, bg_height;
2955 NSTRACE (ns_dumpglyphs_image);
2957 if (s->face->box != FACE_NO_BOX
2958 && s->first_glyph->left_box_line_p && s->slice.x == 0)
2959 x += abs (s->face->box_line_width);
2962 bg_y = s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2963 bg_height = s->height;
2964 /* other terms have this, but was causing problems w/tabbar mode */
2965 /* - 2 * box_line_vwidth; */
2967 if (s->slice.x == 0) x += s->img->hmargin;
2968 if (s->slice.y == 0) y += s->img->vmargin;
2970 /* Draw BG: if we need larger area than image itself cleared, do that,
2971 otherwise, since we composite the image under NS (instead of mucking
2972 with its background color), we must clear just the image area. */
2973 if (s->hl == DRAW_MOUSE_FACE)
2975 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2977 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2980 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2982 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
2984 if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
2985 || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
2987 br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
2988 s->background_filled_p = 1;
2992 br = NSMakeRect (x, y, s->slice.width, s->slice.height);
2997 /* Draw the image.. do we need to draw placeholder if img ==nil? */
3000 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
3001 NSRect dr = NSMakeRect (x, y, s->slice.width, s->slice.height);
3002 NSRect ir = NSMakeRect (s->slice.x, s->slice.y,
3003 s->slice.width, s->slice.height);
3006 operation: NSCompositeSourceOver
3011 [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3012 operation: NSCompositeSourceOver];
3016 if (s->hl == DRAW_CURSOR)
3018 [FRAME_CURSOR_COLOR (s->f) set];
3019 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3020 tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3022 /* Currently on NS img->mask is always 0. Since
3023 get_window_cursor_type specifies a hollow box cursor when on
3024 a non-masked image we never reach this clause. But we put it
3025 in in anticipation of better support for image masks on
3027 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3031 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3034 /* Draw underline, overline, strike-through. */
3035 ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3037 /* Draw relief, if requested */
3038 if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3040 if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3042 th = tool_bar_button_relief >= 0 ?
3043 tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3044 raised_p = (s->hl == DRAW_IMAGE_RAISED);
3048 th = abs (s->img->relief);
3049 raised_p = (s->img->relief > 0);
3052 r.origin.x = x - th;
3053 r.origin.y = y - th;
3054 r.size.width = s->slice.width + 2*th-1;
3055 r.size.height = s->slice.height + 2*th-1;
3056 ns_draw_relief (r, th, raised_p,
3058 s->slice.y + s->slice.height == s->img->height,
3060 s->slice.x + s->slice.width == s->img->width, s);
3063 /* If there is no mask, the background won't be seen,
3064 so draw a rectangle on the image for the cursor.
3065 Do this for all images, getting transparency right is not reliable. */
3066 if (s->hl == DRAW_CURSOR)
3068 int thickness = abs (s->img->relief);
3069 if (thickness == 0) thickness = 1;
3070 ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3076 ns_dumpglyphs_stretch (struct glyph_string *s)
3081 NSColor *fgCol, *bgCol;
3083 if (!s->background_filled_p)
3085 n = ns_get_glyph_string_clip_rect (s, r);
3086 *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3088 ns_focus (s->f, r, n);
3090 if (s->hl == DRAW_MOUSE_FACE)
3092 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3094 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3097 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3099 bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3100 fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3102 for (i = 0; i < n; ++i)
3104 if (!s->row->full_width_p)
3106 int overrun, leftoverrun;
3108 /* truncate to avoid overwriting fringe and/or scrollbar */
3109 overrun = max (0, (s->x + s->background_width)
3110 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3111 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3112 r[i].size.width -= overrun;
3114 /* truncate to avoid overwriting to left of the window box */
3115 leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3116 + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3118 if (leftoverrun > 0)
3120 r[i].origin.x += leftoverrun;
3121 r[i].size.width -= leftoverrun;
3124 /* XXX: Try to work between problem where a stretch glyph on
3125 a partially-visible bottom row will clear part of the
3126 modeline, and another where list-buffers headers and similar
3127 rows erroneously have visible_height set to 0. Not sure
3128 where this is coming from as other terms seem not to show. */
3129 r[i].size.height = min (s->height, s->row->visible_height);
3134 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3135 overwriting cursor (usually when cursor on a tab) */
3136 if (s->hl == DRAW_CURSOR)
3141 width = s->w->phys_cursor_width;
3142 r[i].size.width -= width;
3143 r[i].origin.x += width;
3147 /* Draw overlining, etc. on the cursor. */
3148 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3149 ns_draw_text_decoration (s, face, bgCol, width, x);
3151 ns_draw_text_decoration (s, face, fgCol, width, x);
3158 /* Draw overlining, etc. on the stretch glyph (or the part
3159 of the stretch glyph after the cursor). */
3160 ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3164 s->background_filled_p = 1;
3170 ns_draw_glyph_string (struct glyph_string *s)
3171 /* --------------------------------------------------------------------------
3172 External (RIF): Main draw-text call.
3173 -------------------------------------------------------------------------- */
3175 /* TODO (optimize): focus for box and contents draw */
3178 char box_drawn_p = 0;
3180 NSTRACE (ns_draw_glyph_string);
3182 if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3185 struct glyph_string *next;
3187 for (width = 0, next = s->next;
3188 next && width < s->right_overhang;
3189 width += next->width, next = next->next)
3190 if (next->first_glyph->type != IMAGE_GLYPH)
3192 if (next->first_glyph->type != STRETCH_GLYPH)
3194 n = ns_get_glyph_string_clip_rect (s->next, r);
3195 ns_focus (s->f, r, n);
3196 ns_maybe_dumpglyphs_background (s->next, 1);
3201 ns_dumpglyphs_stretch (s->next);
3203 next->num_clips = 0;
3207 if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3208 && (s->first_glyph->type == CHAR_GLYPH
3209 || s->first_glyph->type == COMPOSITE_GLYPH))
3211 n = ns_get_glyph_string_clip_rect (s, r);
3212 ns_focus (s->f, r, n);
3213 ns_maybe_dumpglyphs_background (s, 1);
3214 ns_dumpglyphs_box_or_relief (s);
3219 switch (s->first_glyph->type)
3223 n = ns_get_glyph_string_clip_rect (s, r);
3224 ns_focus (s->f, r, n);
3225 ns_dumpglyphs_image (s, r[0]);
3230 ns_dumpglyphs_stretch (s);
3234 case COMPOSITE_GLYPH:
3235 n = ns_get_glyph_string_clip_rect (s, r);
3236 ns_focus (s->f, r, n);
3238 if (s->for_overlaps || (s->cmp_from > 0
3239 && ! s->first_glyph->u.cmp.automatic))
3240 s->background_filled_p = 1;
3242 ns_maybe_dumpglyphs_background
3243 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3245 ns_tmp_flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3246 (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3247 (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3248 NS_DUMPGLYPH_NORMAL));
3249 ns_tmp_font = (struct nsfont_info *)s->face->font;
3250 if (ns_tmp_font == NULL)
3251 ns_tmp_font = (struct nsfont_info *)FRAME_FONT (s->f);
3253 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3255 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3256 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3257 NS_FACE_FOREGROUND (s->face) = tmp;
3260 ns_tmp_font->font.driver->draw
3261 (s, 0, s->nchars, s->x, s->y,
3262 (ns_tmp_flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3263 || ns_tmp_flags == NS_DUMPGLYPH_MOUSEFACE);
3265 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3267 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3268 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3269 NS_FACE_FOREGROUND (s->face) = tmp;
3275 case GLYPHLESS_GLYPH:
3276 n = ns_get_glyph_string_clip_rect (s, r);
3277 ns_focus (s->f, r, n);
3279 if (s->for_overlaps || (s->cmp_from > 0
3280 && ! s->first_glyph->u.cmp.automatic))
3281 s->background_filled_p = 1;
3283 ns_maybe_dumpglyphs_background
3284 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3286 /* Not yet implemented. */
3295 /* Draw box if not done already. */
3296 if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3298 n = ns_get_glyph_string_clip_rect (s, r);
3299 ns_focus (s->f, r, n);
3300 ns_dumpglyphs_box_or_relief (s);
3309 /* ==========================================================================
3313 ========================================================================== */
3317 ns_send_appdefined (int value)
3318 /* --------------------------------------------------------------------------
3319 Internal: post an appdefined event which EmacsApp-sendEvent will
3320 recognize and take as a command to halt the event loop.
3321 -------------------------------------------------------------------------- */
3323 /*NSTRACE (ns_send_appdefined); */
3325 /* Only post this event if we haven't already posted one. This will end
3326 the [NXApp run] main loop after having processed all events queued at
3328 if (send_appdefined)
3332 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
3333 send_appdefined = NO;
3335 /* Don't need wakeup timer any more */
3338 [timed_entry invalidate];
3339 [timed_entry release];
3343 nxev = [NSEvent otherEventWithType: NSApplicationDefined
3344 location: NSMakePoint (0, 0)
3347 windowNumber: [[NSApp mainWindow] windowNumber]
3348 context: [NSApp context]
3353 /* Post an application defined event on the event queue. When this is
3354 received the [NXApp run] will return, thus having processed all
3355 events which are currently queued. */
3356 [NSApp postEvent: nxev atStart: NO];
3361 ns_read_socket (struct terminal *terminal, struct input_event *hold_quit)
3362 /* --------------------------------------------------------------------------
3363 External (hook): Post an event to ourself and keep reading events until
3364 we read it back again. In effect process all events which were waiting.
3365 From 21+ we have to manage the event buffer ourselves.
3366 -------------------------------------------------------------------------- */
3368 struct input_event ev;
3371 /* NSTRACE (ns_read_socket); */
3373 if ([NSApp modalWindow] != nil)
3376 if (hold_event_q.nr > 0)
3379 for (i = 0; i < hold_event_q.nr; ++i)
3380 kbd_buffer_store_event_hold (&hold_event_q.q[i], hold_quit);
3381 hold_event_q.nr = 0;
3386 n_emacs_events_pending = 0;
3389 q_event_ptr = hold_quit;
3391 /* we manage autorelease pools by allocate/reallocate each time around
3392 the loop; strict nesting is occasionally violated but seems not to
3393 matter.. earlier methods using full nesting caused major memory leaks */
3394 [outerpool release];
3395 outerpool = [[NSAutoreleasePool alloc] init];
3397 /* If have pending open-file requests, attend to the next one of those. */
3398 if (ns_pending_files && [ns_pending_files count] != 0
3399 && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3401 [ns_pending_files removeObjectAtIndex: 0];
3403 /* Deal with pending service requests. */
3404 else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3406 NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3407 withArg: [ns_pending_service_args objectAtIndex: 0]])
3409 [ns_pending_service_names removeObjectAtIndex: 0];
3410 [ns_pending_service_args removeObjectAtIndex: 0];
3414 /* Run and wait for events. We must always send one NX_APPDEFINED event
3415 to ourself, otherwise [NXApp run] will never exit. */
3416 send_appdefined = YES;
3417 ns_send_appdefined (-1);
3419 if (++apploopnr != 1)
3427 nevents = n_emacs_events_pending;
3428 n_emacs_events_pending = 0;
3429 emacs_event = q_event_ptr = NULL;
3437 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3438 fd_set *exceptfds, EMACS_TIME *timeout, sigset_t *sigmask)
3439 /* --------------------------------------------------------------------------
3440 Replacement for select, checking for events
3441 -------------------------------------------------------------------------- */
3445 struct input_event event;
3448 /* NSTRACE (ns_select); */
3450 if (hold_event_q.nr > 0)
3452 /* We already have events pending. */
3458 for (k = 0; k < nfds+1; k++)
3460 if (readfds && FD_ISSET(k, readfds)) ++nr;
3461 if (writefds && FD_ISSET(k, writefds)) ++nr;
3465 || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0))
3466 return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
3468 [outerpool release];
3469 outerpool = [[NSAutoreleasePool alloc] init];
3472 send_appdefined = YES;
3475 pthread_mutex_lock (&select_mutex);
3480 select_readfds = *readfds;
3481 select_valid += SELECT_HAVE_READ;
3485 select_writefds = *writefds;
3486 select_valid += SELECT_HAVE_WRITE;
3491 select_timeout = *timeout;
3492 select_valid += SELECT_HAVE_TMO;
3495 pthread_mutex_unlock (&select_mutex);
3497 /* Inform fd_handler that select should be called */
3499 write (selfds[1], &c, 1);
3501 else if (nr == 0 && timeout)
3503 /* No file descriptor, just a timeout, no need to wake fd_handler */
3504 double time = EMACS_TIME_TO_DOUBLE (*timeout);
3505 timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3508 @selector (timeout_handler:)
3513 else /* No timeout and no file descriptors, can this happen? */
3515 /* Send appdefined so we exit from the loop */
3516 ns_send_appdefined (-1);
3521 emacs_event = &event;
3522 if (++apploopnr != 1)
3529 if (nr > 0 && readfds)
3532 write (selfds[1], &c, 1);
3536 t = last_appdefined_event_data;
3538 if (t != NO_APPDEFINED_DATA)
3540 last_appdefined_event_data = NO_APPDEFINED_DATA;
3544 /* The NX_APPDEFINED event we received was a timeout. */
3549 /* The NX_APPDEFINED event we received was the result of
3550 at least one real input event arriving. */
3556 /* Received back from select () in fd_handler; copy the results */
3557 pthread_mutex_lock (&select_mutex);
3558 if (readfds) *readfds = select_readfds;
3559 if (writefds) *writefds = select_writefds;
3560 if (timeout) *timeout = select_timeout;
3561 pthread_mutex_unlock (&select_mutex);
3571 /* ==========================================================================
3575 ========================================================================== */
3579 ns_set_vertical_scroll_bar (struct window *window,
3580 int portion, int whole, int position)
3581 /* --------------------------------------------------------------------------
3582 External (hook): Update or add scrollbar
3583 -------------------------------------------------------------------------- */
3587 struct frame *f = XFRAME (WINDOW_FRAME (window));
3588 EmacsView *view = FRAME_NS_VIEW (f);
3589 int window_y, window_height;
3590 int top, left, height, width, sb_width, sb_left;
3592 BOOL fringe_extended_p;
3594 /* optimization; display engine sends WAY too many of these.. */
3595 if (!NILP (window->vertical_scroll_bar))
3597 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3598 if ([bar checkSamePosition: position portion: portion whole: whole])
3600 if (view->scrollbarsNeedingUpdate == 0)
3602 if (!windows_or_buffers_changed)
3606 view->scrollbarsNeedingUpdate--;
3610 NSTRACE (ns_set_vertical_scroll_bar);
3612 /* Get dimensions. */
3613 window_box (window, -1, 0, &window_y, 0, &window_height);
3615 height = window_height;
3616 width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3617 left = WINDOW_SCROLL_BAR_AREA_X (window);
3619 /* allow for displaying a skinnier scrollbar than char area allotted */
3620 sb_width = (WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) > 0) ?
3621 WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) : width;
3624 r = NSMakeRect (sb_left, top, sb_width, height);
3625 /* the parent view is flipped, so we need to flip y value */
3627 r.origin.y = (v.size.height - r.size.height - r.origin.y);
3629 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (window))
3630 fringe_extended_p = (WINDOW_LEFTMOST_P (window)
3631 && WINDOW_LEFT_FRINGE_WIDTH (window)
3632 && (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (window)
3633 || WINDOW_LEFT_MARGIN_COLS (window) == 0));
3635 fringe_extended_p = (WINDOW_RIGHTMOST_P (window)
3636 && WINDOW_RIGHT_FRINGE_WIDTH (window)
3637 && (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (window)
3638 || WINDOW_RIGHT_MARGIN_COLS (window) == 0));
3640 XSETWINDOW (win, window);
3643 /* we want at least 5 lines to display a scrollbar */
3644 if (WINDOW_TOTAL_LINES (window) < 5)
3646 if (!NILP (window->vertical_scroll_bar))
3648 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3649 [bar removeFromSuperview];
3650 wset_vertical_scroll_bar (window, Qnil);
3652 ns_clear_frame_area (f, sb_left, top, width, height);
3657 if (NILP (window->vertical_scroll_bar))
3659 if (width > 0 && height > 0)
3661 if (fringe_extended_p)
3662 ns_clear_frame_area (f, sb_left, top, sb_width, height);
3664 ns_clear_frame_area (f, left, top, width, height);
3667 bar = [[EmacsScroller alloc] initFrame: r window: win];
3668 wset_vertical_scroll_bar (window, make_save_value (bar, 0));
3673 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3674 oldRect = [bar frame];
3675 r.size.width = oldRect.size.width;
3676 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3678 if (oldRect.origin.x != r.origin.x)
3679 ns_clear_frame_area (f, sb_left, top, width, height);
3684 [bar setPosition: position portion: portion whole: whole];
3690 ns_condemn_scroll_bars (struct frame *f)
3691 /* --------------------------------------------------------------------------
3692 External (hook): arrange for all frame's scrollbars to be removed
3693 at next call to judge_scroll_bars, except for those redeemed.
3694 -------------------------------------------------------------------------- */
3698 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3700 NSTRACE (ns_condemn_scroll_bars);
3702 for (i =[subviews count]-1; i >= 0; i--)
3704 view = [subviews objectAtIndex: i];
3705 if ([view isKindOfClass: [EmacsScroller class]])
3712 ns_redeem_scroll_bar (struct window *window)
3713 /* --------------------------------------------------------------------------
3714 External (hook): arrange to spare this window's scrollbar
3715 at next call to judge_scroll_bars.
3716 -------------------------------------------------------------------------- */
3719 NSTRACE (ns_redeem_scroll_bar);
3720 if (!NILP (window->vertical_scroll_bar))
3722 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3729 ns_judge_scroll_bars (struct frame *f)
3730 /* --------------------------------------------------------------------------
3731 External (hook): destroy all scrollbars on frame that weren't
3732 redeemed after call to condemn_scroll_bars.
3733 -------------------------------------------------------------------------- */
3737 EmacsView *eview = FRAME_NS_VIEW (f);
3738 NSArray *subviews = [[eview superview] subviews];
3741 NSTRACE (ns_judge_scroll_bars);
3742 for (i = [subviews count]-1; i >= 0; --i)
3744 view = [subviews objectAtIndex: i];
3745 if (![view isKindOfClass: [EmacsScroller class]]) continue;
3751 [eview updateFrameSize: NO];
3756 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
3758 /* XXX irrelevant under NS */
3763 /* ==========================================================================
3767 ========================================================================== */
3770 x_display_pixel_height (struct ns_display_info *dpyinfo)
3772 NSScreen *screen = [NSScreen mainScreen];
3773 return [screen frame].size.height;
3777 x_display_pixel_width (struct ns_display_info *dpyinfo)
3779 NSScreen *screen = [NSScreen mainScreen];
3780 return [screen frame].size.width;
3784 static Lisp_Object ns_string_to_lispmod (const char *s)
3785 /* --------------------------------------------------------------------------
3786 Convert modifier name to lisp symbol
3787 -------------------------------------------------------------------------- */
3789 if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
3791 else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
3793 else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
3795 else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
3797 else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
3799 else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
3807 ns_default (const char *parameter, Lisp_Object *result,
3808 Lisp_Object yesval, Lisp_Object noval,
3809 BOOL is_float, BOOL is_modstring)
3810 /* --------------------------------------------------------------------------
3811 Check a parameter value in user's preferences
3812 -------------------------------------------------------------------------- */
3814 const char *value = ns_get_defaults_value (parameter);
3820 if (c_strcasecmp (value, "YES") == 0)
3822 else if (c_strcasecmp (value, "NO") == 0)
3824 else if (is_float && (f = strtod (value, &pos), pos != value))
3825 *result = make_float (f);
3826 else if (is_modstring && value)
3827 *result = ns_string_to_lispmod (value);
3828 else fprintf (stderr,
3829 "Bad value for default \"%s\": \"%s\"\n", parameter, value);
3835 ns_initialize_display_info (struct ns_display_info *dpyinfo)
3836 /* --------------------------------------------------------------------------
3837 Initialize global info and storage for display.
3838 -------------------------------------------------------------------------- */
3840 NSScreen *screen = [NSScreen mainScreen];
3841 NSWindowDepth depth = [screen depth];
3842 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
3844 dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
3845 dpyinfo->resy = 72.27;
3846 dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
3847 NSColorSpaceFromDepth (depth)]
3848 && ![NSCalibratedWhiteColorSpace isEqualToString:
3849 NSColorSpaceFromDepth (depth)];
3850 dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
3851 dpyinfo->image_cache = make_image_cache ();
3852 dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
3853 dpyinfo->color_table->colors = NULL;
3854 dpyinfo->root_window = 42; /* a placeholder.. */
3856 hlinfo->mouse_face_mouse_frame = NULL;
3857 hlinfo->mouse_face_deferred_gc = 0;
3858 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
3859 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
3860 hlinfo->mouse_face_face_id = DEFAULT_FACE_ID;
3861 hlinfo->mouse_face_window = hlinfo->mouse_face_overlay = Qnil;
3862 hlinfo->mouse_face_hidden = 0;
3864 hlinfo->mouse_face_mouse_x = hlinfo->mouse_face_mouse_y = 0;
3865 hlinfo->mouse_face_defer = 0;
3867 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
3869 dpyinfo->n_fonts = 0;
3870 dpyinfo->smallest_font_height = 1;
3871 dpyinfo->smallest_char_width = 1;
3875 /* This and next define (many of the) public functions in this file. */
3876 /* x_... are generic versions in xdisp.c that we, and other terms, get away
3877 with using despite presence in the "system dependent" redisplay
3878 interface. In addition, many of the ns_ methods have code that is
3879 shared with all terms, indicating need for further refactoring. */
3880 extern frame_parm_handler ns_frame_parm_handlers[];
3881 static struct redisplay_interface ns_redisplay_interface =
3883 ns_frame_parm_handlers,
3887 x_clear_end_of_line,
3889 ns_after_update_window_line,
3890 ns_update_window_begin,
3891 ns_update_window_end,
3894 0, /* flush_display_optional */
3895 x_clear_window_mouse_face,
3896 x_get_glyph_overhangs,
3897 x_fix_overlapping_area,
3898 ns_draw_fringe_bitmap,
3899 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
3900 0, /* destroy_fringe_bitmap */
3901 ns_compute_glyph_string_overhangs,
3902 ns_draw_glyph_string, /* interface to nsfont.m */
3903 ns_define_frame_cursor,
3904 ns_clear_frame_area,
3905 ns_draw_window_cursor,
3906 ns_draw_vertical_window_border,
3907 ns_shift_glyphs_for_insert
3912 ns_delete_display (struct ns_display_info *dpyinfo)
3918 /* This function is called when the last frame on a display is deleted. */
3920 ns_delete_terminal (struct terminal *terminal)
3922 struct ns_display_info *dpyinfo = terminal->display_info.ns;
3924 /* Protect against recursive calls. delete_frame in
3925 delete_terminal calls us back when it deletes our last frame. */
3926 if (!terminal->name)
3931 x_destroy_all_bitmaps (dpyinfo);
3932 ns_delete_display (dpyinfo);
3937 static struct terminal *
3938 ns_create_terminal (struct ns_display_info *dpyinfo)
3939 /* --------------------------------------------------------------------------
3940 Set up use of NS before we make the first connection.
3941 -------------------------------------------------------------------------- */
3943 struct terminal *terminal;
3945 NSTRACE (ns_create_terminal);
3947 terminal = create_terminal ();
3949 terminal->type = output_ns;
3950 terminal->display_info.ns = dpyinfo;
3951 dpyinfo->terminal = terminal;
3953 terminal->rif = &ns_redisplay_interface;
3955 terminal->clear_frame_hook = ns_clear_frame;
3956 terminal->ins_del_lines_hook = 0; /* XXX vestigial? */
3957 terminal->delete_glyphs_hook = 0; /* XXX vestigial? */
3958 terminal->ring_bell_hook = ns_ring_bell;
3959 terminal->reset_terminal_modes_hook = ns_reset_terminal_modes;
3960 terminal->set_terminal_modes_hook = ns_set_terminal_modes;
3961 terminal->update_begin_hook = ns_update_begin;
3962 terminal->update_end_hook = ns_update_end;
3963 terminal->set_terminal_window_hook = NULL; /* XXX vestigial? */
3964 terminal->read_socket_hook = ns_read_socket;
3965 terminal->frame_up_to_date_hook = ns_frame_up_to_date;
3966 terminal->mouse_position_hook = ns_mouse_position;
3967 terminal->frame_rehighlight_hook = ns_frame_rehighlight;
3968 terminal->frame_raise_lower_hook = ns_frame_raise_lower;
3970 terminal->fullscreen_hook = ns_fullscreen_hook;
3972 terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
3973 terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
3974 terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
3975 terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
3977 terminal->delete_frame_hook = x_destroy_window;
3978 terminal->delete_terminal_hook = ns_delete_terminal;
3980 terminal->scroll_region_ok = 1;
3981 terminal->char_ins_del_ok = 1;
3982 terminal->line_ins_del_ok = 1;
3983 terminal->fast_clear_end_of_line = 1;
3984 terminal->memory_below_frame = 0;
3990 struct ns_display_info *
3991 ns_term_init (Lisp_Object display_name)
3992 /* --------------------------------------------------------------------------
3993 Start the Application and get things rolling.
3994 -------------------------------------------------------------------------- */
3996 struct terminal *terminal;
3997 struct ns_display_info *dpyinfo;
3998 static int ns_initialized = 0;
4001 if (ns_initialized) return x_display_list;
4004 NSTRACE (ns_term_init);
4006 [outerpool release];
4007 outerpool = [[NSAutoreleasePool alloc] init];
4009 /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4010 /*GSDebugAllocationActive (YES); */
4014 Fset_input_interrupt_mode (Qnil);
4016 if (selfds[0] == -1)
4018 if (pipe (selfds) == -1)
4020 fprintf (stderr, "Failed to create pipe: %s\n",
4021 emacs_strerror (errno));
4025 fcntl (selfds[0], F_SETFL, O_NONBLOCK|fcntl (selfds[0], F_GETFL));
4026 FD_ZERO (&select_readfds);
4027 FD_ZERO (&select_writefds);
4028 pthread_mutex_init (&select_mutex, NULL);
4031 ns_pending_files = [[NSMutableArray alloc] init];
4032 ns_pending_service_names = [[NSMutableArray alloc] init];
4033 ns_pending_service_args = [[NSMutableArray alloc] init];
4035 /* Start app and create the main menu, window, view.
4036 Needs to be here because ns_initialize_display_info () uses AppKit classes.
4037 The view will then ask the NSApp to stop and return to Emacs. */
4038 [EmacsApp sharedApplication];
4041 [NSApp setDelegate: NSApp];
4043 /* Start the select thread. */
4044 [NSThread detachNewThreadSelector:@selector (fd_handler:)
4048 /* debugging: log all notifications */
4049 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
4050 selector: @selector (logNotification:)
4051 name: nil object: nil]; */
4053 dpyinfo = xzalloc (sizeof *dpyinfo);
4055 ns_initialize_display_info (dpyinfo);
4056 terminal = ns_create_terminal (dpyinfo);
4058 terminal->kboard = xmalloc (sizeof *terminal->kboard);
4059 init_kboard (terminal->kboard);
4060 kset_window_system (terminal->kboard, Qns);
4061 terminal->kboard->next_kboard = all_kboards;
4062 all_kboards = terminal->kboard;
4063 /* Don't let the initial kboard remain current longer than necessary.
4064 That would cause problems if a file loaded on startup tries to
4065 prompt in the mini-buffer. */
4066 if (current_kboard == initial_kboard)
4067 current_kboard = terminal->kboard;
4068 terminal->kboard->reference_count++;
4070 dpyinfo->next = x_display_list;
4071 x_display_list = dpyinfo;
4073 /* Put it on ns_display_name_list */
4074 ns_display_name_list = Fcons (Fcons (display_name, Qnil),
4075 ns_display_name_list);
4076 dpyinfo->name_list_element = XCAR (ns_display_name_list);
4078 terminal->name = xstrdup (SSDATA (display_name));
4082 if (!inhibit_x_resources)
4084 ns_default ("GSFontAntiAlias", &ns_antialias_text,
4087 /* this is a standard variable */
4088 ns_default ("AppleAntiAliasingThreshold", &tmp,
4089 make_float (10.0), make_float (6.0), YES, NO);
4090 ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4093 ns_selection_color = [[NSUserDefaults standardUserDefaults]
4094 stringForKey: @"AppleHighlightColor"];
4095 if (ns_selection_color == nil)
4096 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
4099 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4103 Lisp_Object color_file, color_map, color;
4107 color_file = Fexpand_file_name (build_string ("rgb.txt"),
4108 Fsymbol_value (intern ("data-directory")));
4109 if (NILP (Ffile_readable_p (color_file)))
4110 fatal ("Could not find %s.\n", SDATA (color_file));
4112 color_map = Fx_load_color_file (color_file);
4113 if (NILP (color_map))
4114 fatal ("Could not read %s.\n", SDATA (color_file));
4116 cl = [[NSColorList alloc] initWithName: @"Emacs"];
4117 for ( ; CONSP (color_map); color_map = XCDR (color_map))
4119 color = XCAR (color_map);
4120 name = SSDATA (XCAR (color));
4121 c = XINT (XCDR (color));
4123 [NSColor colorWithCalibratedRed: RED_FROM_ULONG (c) / 255.0
4124 green: GREEN_FROM_ULONG (c) / 255.0
4125 blue: BLUE_FROM_ULONG (c) / 255.0
4127 forKey: [NSString stringWithUTF8String: name]];
4129 [cl writeToFile: nil];
4134 #ifdef NS_IMPL_GNUSTEP
4135 Vwindow_system_version = build_string (gnustep_base_version);
4137 /*PSnextrelease (128, c); */
4138 char c[DBL_BUFSIZE_BOUND];
4139 int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4140 Vwindow_system_version = make_unibyte_string (c, len);
4144 delete_keyboard_wait_descriptor (0);
4146 ns_app_name = [[NSProcessInfo processInfo] processName];
4148 /* Set up OS X app menu */
4149 #ifdef NS_IMPL_COCOA
4153 /* set up the application menu */
4154 svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4155 [svcsMenu setAutoenablesItems: NO];
4156 appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4157 [appMenu setAutoenablesItems: NO];
4158 mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4159 dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4161 [appMenu insertItemWithTitle: @"About Emacs"
4162 action: @selector (orderFrontStandardAboutPanel:)
4165 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4166 [appMenu insertItemWithTitle: @"Preferences..."
4167 action: @selector (showPreferencesWindow:)
4170 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4171 item = [appMenu insertItemWithTitle: @"Services"
4172 action: @selector (menuDown:)
4175 [appMenu setSubmenu: svcsMenu forItem: item];
4176 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4177 [appMenu insertItemWithTitle: @"Hide Emacs"
4178 action: @selector (hide:)
4181 item = [appMenu insertItemWithTitle: @"Hide Others"
4182 action: @selector (hideOtherApplications:)
4185 [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4186 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4187 [appMenu insertItemWithTitle: @"Quit Emacs"
4188 action: @selector (terminate:)
4192 item = [mainMenu insertItemWithTitle: ns_app_name
4193 action: @selector (menuDown:)
4196 [mainMenu setSubmenu: appMenu forItem: item];
4197 [dockMenu insertItemWithTitle: @"New Frame"
4198 action: @selector (newFrame:)
4202 [NSApp setMainMenu: mainMenu];
4203 [NSApp setAppleMenu: appMenu];
4204 [NSApp setServicesMenu: svcsMenu];
4205 /* Needed at least on Cocoa, to get dock menu to show windows */
4206 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4208 [[NSNotificationCenter defaultCenter]
4209 addObserver: mainMenu
4210 selector: @selector (trackingNotification:)
4211 name: NSMenuDidBeginTrackingNotification object: mainMenu];
4212 [[NSNotificationCenter defaultCenter]
4213 addObserver: mainMenu
4214 selector: @selector (trackingNotification:)
4215 name: NSMenuDidEndTrackingNotification object: mainMenu];
4217 #endif /* MAC OS X menu setup */
4219 /* Register our external input/output types, used for determining
4220 applicable services and also drag/drop eligibility. */
4221 ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
4222 ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
4224 ns_drag_types = [[NSArray arrayWithObjects:
4226 NSTabularTextPboardType,
4227 NSFilenamesPboardType,
4230 NSFontPboardType, nil] retain];
4232 #ifndef NEW_STYLE_FS
4233 /* If fullscreen is in init/default-frame-alist, focus isn't set
4234 right for fullscreen windows, so set this. */
4235 [NSApp activateIgnoringOtherApps:YES];
4239 ns_do_open_file = YES;
4245 ns_term_shutdown (int sig)
4247 [[NSUserDefaults standardUserDefaults] synchronize];
4249 /* code not reached in emacs.c after this is called by shut_down_emacs: */
4250 if (STRINGP (Vauto_save_list_file_name))
4251 unlink (SSDATA (Vauto_save_list_file_name));
4253 if (sig == 0 || sig == SIGTERM)
4255 [NSApp terminate: NSApp];
4257 else // force a stack trace to happen
4264 /* ==========================================================================
4266 EmacsApp implementation
4268 ========================================================================== */
4271 @implementation EmacsApp
4273 - (void)logNotification: (NSNotification *)notification
4275 const char *name = [[notification name] UTF8String];
4276 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4277 && !strstr (name, "WindowNumber"))
4278 NSLog (@"notification: '%@'", [notification name]);
4282 - (void)sendEvent: (NSEvent *)theEvent
4283 /* --------------------------------------------------------------------------
4284 Called when NSApp is running for each event received. Used to stop
4285 the loop when we choose, since there's no way to just run one iteration.
4286 -------------------------------------------------------------------------- */
4288 int type = [theEvent type];
4289 NSWindow *window = [theEvent window];
4290 /* NSTRACE (sendEvent); */
4291 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4293 #ifdef NS_IMPL_COCOA
4294 if (type == NSApplicationDefined
4295 && [theEvent data2] == NSAPP_DATA2_RUNASSCRIPT)
4303 if (type == NSCursorUpdate && window == nil)
4305 fprintf (stderr, "Dropping external cursor update event.\n");
4309 if (type == NSApplicationDefined)
4311 /* Events posted by ns_send_appdefined interrupt the run loop here.
4312 But, if a modal window is up, an appdefined can still come through,
4313 (e.g., from a makeKeyWindow event) but stopping self also stops the
4314 modal loop. Just defer it until later. */
4315 if ([NSApp modalWindow] == nil)
4317 last_appdefined_event_data = [theEvent data1];
4322 send_appdefined = YES;
4326 [super sendEvent: theEvent];
4330 - (void)showPreferencesWindow: (id)sender
4332 struct frame *emacsframe = SELECTED_FRAME ();
4333 NSEvent *theEvent = [NSApp currentEvent];
4337 emacs_event->kind = NS_NONKEY_EVENT;
4338 emacs_event->code = KEY_NS_SHOW_PREFS;
4339 emacs_event->modifiers = 0;
4340 EV_TRAILER (theEvent);
4344 - (void)newFrame: (id)sender
4346 struct frame *emacsframe = SELECTED_FRAME ();
4347 NSEvent *theEvent = [NSApp currentEvent];
4351 emacs_event->kind = NS_NONKEY_EVENT;
4352 emacs_event->code = KEY_NS_NEW_FRAME;
4353 emacs_event->modifiers = 0;
4354 EV_TRAILER (theEvent);
4358 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4359 - (BOOL) openFile: (NSString *)fileName
4361 struct frame *emacsframe = SELECTED_FRAME ();
4362 NSEvent *theEvent = [NSApp currentEvent];
4367 emacs_event->kind = NS_NONKEY_EVENT;
4368 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4369 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4370 ns_input_line = Qnil; /* can be start or cons start,end */
4371 emacs_event->modifiers =0;
4372 EV_TRAILER (theEvent);
4378 /* **************************************************************************
4380 EmacsApp delegate implementation
4382 ************************************************************************** */
4384 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4385 /* --------------------------------------------------------------------------
4386 When application is loaded, terminate event loop in ns_term_init
4387 -------------------------------------------------------------------------- */
4389 NSTRACE (applicationDidFinishLaunching);
4390 [NSApp setServicesProvider: NSApp];
4391 ns_send_appdefined (-2);
4395 /* Termination sequences:
4398 MenuBar | File | Exit:
4399 Select Quit from App menubar:
4401 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4404 Select Quit from Dock menu:
4407 Cancel -> Nothing else
4411 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4416 - (void) terminate: (id)sender
4418 struct frame *emacsframe = SELECTED_FRAME ();
4423 emacs_event->kind = NS_NONKEY_EVENT;
4424 emacs_event->code = KEY_NS_POWER_OFF;
4425 emacs_event->arg = Qt; /* mark as non-key event */
4426 EV_TRAILER ((id)nil);
4430 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4434 if (NILP (ns_confirm_quit)) // || ns_shutdown_properly --> TO DO
4435 return NSTerminateNow;
4437 ret = NSRunAlertPanel(ns_app_name,
4438 @"Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?",
4439 @"Save Buffers and Exit", @"Cancel", nil);
4441 if (ret == NSAlertDefaultReturn)
4442 return NSTerminateNow;
4443 else if (ret == NSAlertAlternateReturn)
4444 return NSTerminateCancel;
4445 return NSTerminateNow; /* just in case */
4449 not_in_argv (NSString *arg)
4452 const char *a = [arg UTF8String];
4453 for (k = 1; k < initial_argc; ++k)
4454 if (strcmp (a, initial_argv[k]) == 0) return 0;
4458 /* Notification from the Workspace to open a file */
4459 - (BOOL)application: sender openFile: (NSString *)file
4461 if (ns_do_open_file || not_in_argv (file))
4462 [ns_pending_files addObject: file];
4467 /* Open a file as a temporary file */
4468 - (BOOL)application: sender openTempFile: (NSString *)file
4470 if (ns_do_open_file || not_in_argv (file))
4471 [ns_pending_files addObject: file];
4476 /* Notification from the Workspace to open a file noninteractively (?) */
4477 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4479 if (ns_do_open_file || not_in_argv (file))
4480 [ns_pending_files addObject: file];
4484 /* Notification from the Workspace to open multiple files */
4485 - (void)application: sender openFiles: (NSArray *)fileList
4487 NSEnumerator *files = [fileList objectEnumerator];
4489 /* Don't open files from the command line unconditionally,
4490 Cocoa parses the command line wrong, --option value tries to open value
4491 if --option is the last option. */
4492 while ((file = [files nextObject]) != nil)
4493 if (ns_do_open_file || not_in_argv (file))
4494 [ns_pending_files addObject: file];
4496 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4501 /* Handle dock menu requests. */
4502 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4508 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4509 - (void)applicationWillBecomeActive: (NSNotification *)notification
4511 //ns_app_active=YES;
4513 - (void)applicationDidBecomeActive: (NSNotification *)notification
4515 NSTRACE (applicationDidBecomeActive);
4517 //ns_app_active=YES;
4519 ns_update_auto_hide_menu_bar ();
4520 // No constraining takes place when the application is not active.
4521 ns_constrain_all_frames ();
4523 - (void)applicationDidResignActive: (NSNotification *)notification
4526 ns_send_appdefined (-1);
4531 /* ==========================================================================
4533 EmacsApp aux handlers for managing event loop
4535 ========================================================================== */
4538 - (void)timeout_handler: (NSTimer *)timedEntry
4539 /* --------------------------------------------------------------------------
4540 The timeout specified to ns_select has passed.
4541 -------------------------------------------------------------------------- */
4543 /*NSTRACE (timeout_handler); */
4544 ns_send_appdefined (-2);
4547 - (void)fd_handler:(id)unused
4548 /* --------------------------------------------------------------------------
4549 Check data waiting on file descriptors and terminate if so
4550 -------------------------------------------------------------------------- */
4553 int waiting = 1, nfds;
4556 SELECT_TYPE readfds, writefds, *wfds;
4557 EMACS_TIME timeout, *tmo;
4558 NSAutoreleasePool *pool = nil;
4560 /* NSTRACE (fd_handler); */
4565 pool = [[NSAutoreleasePool alloc] init];
4571 FD_SET (selfds[0], &fds);
4572 result = select (selfds[0]+1, &fds, NULL, NULL, NULL);
4575 read (selfds[0], &c, 1);
4576 if (c == 'g') waiting = 0;
4581 pthread_mutex_lock (&select_mutex);
4584 if (select_valid & SELECT_HAVE_READ)
4585 readfds = select_readfds;
4589 if (select_valid & SELECT_HAVE_WRITE)
4591 writefds = select_writefds;
4596 if (select_valid & SELECT_HAVE_TMO)
4598 timeout = select_timeout;
4604 pthread_mutex_unlock (&select_mutex);
4606 FD_SET (selfds[0], &readfds);
4607 if (selfds[0] >= nfds) nfds = selfds[0]+1;
4609 result = pselect (nfds, &readfds, wfds, NULL, tmo, NULL);
4612 ns_send_appdefined (-2);
4613 else if (result > 0)
4615 if (FD_ISSET (selfds[0], &readfds))
4617 read (selfds[0], &c, 1);
4618 if (c == 's') waiting = 1;
4622 pthread_mutex_lock (&select_mutex);
4623 if (select_valid & SELECT_HAVE_READ)
4624 select_readfds = readfds;
4625 if (select_valid & SELECT_HAVE_WRITE)
4626 select_writefds = writefds;
4627 if (select_valid & SELECT_HAVE_TMO)
4628 select_timeout = timeout;
4629 pthread_mutex_unlock (&select_mutex);
4631 ns_send_appdefined (result);
4641 /* ==========================================================================
4645 ========================================================================== */
4647 /* called from system: queue for next pass through event loop */
4648 - (void)requestService: (NSPasteboard *)pboard
4649 userData: (NSString *)userData
4650 error: (NSString **)error
4652 [ns_pending_service_names addObject: userData];
4653 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
4654 SSDATA (ns_string_from_pasteboard (pboard))]];
4658 /* called from ns_read_socket to clear queue */
4659 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
4661 struct frame *emacsframe = SELECTED_FRAME ();
4662 NSEvent *theEvent = [NSApp currentEvent];
4667 emacs_event->kind = NS_NONKEY_EVENT;
4668 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
4669 ns_input_spi_name = build_string ([name UTF8String]);
4670 ns_input_spi_arg = build_string ([arg UTF8String]);
4671 emacs_event->modifiers = EV_MODIFIERS (theEvent);
4672 EV_TRAILER (theEvent);
4682 /* ==========================================================================
4684 EmacsView implementation
4686 ========================================================================== */
4689 @implementation EmacsView
4691 /* needed to inform when window closed from LISP */
4692 - (void) setWindowClosing: (BOOL)closing
4694 windowClosing = closing;
4700 NSTRACE (EmacsView_dealloc);
4702 if (fs_state == FULLSCREEN_BOTH)
4703 [nonfs_window release];
4708 /* called on font panel selection */
4709 - (void)changeFont: (id)sender
4711 NSEvent *e =[[self window] currentEvent];
4712 struct face *face =FRAME_DEFAULT_FACE (emacsframe);
4716 NSTRACE (changeFont);
4720 if ((newFont = [sender convertFont:
4721 ((struct nsfont_info *)face->font)->nsfont]))
4723 SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
4725 emacs_event->kind = NS_NONKEY_EVENT;
4726 emacs_event->modifiers = 0;
4727 emacs_event->code = KEY_NS_CHANGE_FONT;
4729 size = [newFont pointSize];
4730 ns_input_fontsize = make_number (lrint (size));
4731 ns_input_font = build_string ([[newFont familyName] UTF8String]);
4737 - (BOOL)acceptsFirstResponder
4739 NSTRACE (acceptsFirstResponder);
4744 - (void)resetCursorRects
4746 NSRect visible = [self visibleRect];
4747 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
4748 NSTRACE (resetCursorRects);
4750 if (currentCursor == nil)
4751 currentCursor = [NSCursor arrowCursor];
4753 if (!NSIsEmptyRect (visible))
4754 [self addCursorRect: visible cursor: currentCursor];
4755 [currentCursor setOnMouseEntered: YES];
4760 /*****************************************************************************/
4761 /* Keyboard handling. */
4764 - (void)keyDown: (NSEvent *)theEvent
4766 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
4768 unsigned fnKeysym = 0;
4770 static NSMutableArray *nsEvArray;
4771 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
4772 static BOOL firstTime = YES;
4778 /* Rhapsody and OS X give up and down events for the arrow keys */
4779 if (ns_fake_keydown == YES)
4780 ns_fake_keydown = NO;
4781 else if ([theEvent type] != NSKeyDown)
4787 if (![[self window] isKeyWindow]
4788 && [[theEvent window] isKindOfClass: [EmacsWindow class]]
4789 /* we must avoid an infinite loop here. */
4790 && (EmacsView *)[[theEvent window] delegate] != self)
4792 /* XXX: There is an occasional condition in which, when Emacs display
4793 updates a different frame from the current one, and temporarily
4794 selects it, then processes some interrupt-driven input
4795 (dispnew.c:3878), OS will send the event to the correct NSWindow, but
4796 for some reason that window has its first responder set to the NSView
4797 most recently updated (I guess), which is not the correct one. */
4798 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
4802 if (nsEvArray == nil)
4803 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
4805 [NSCursor setHiddenUntilMouseMoves: YES];
4807 if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
4809 clear_mouse_face (hlinfo);
4810 hlinfo->mouse_face_hidden = 1;
4813 if (!processingCompose)
4815 /* When using screen sharing, no left or right information is sent,
4816 so use Left key in those cases. */
4817 int is_left_key, is_right_key;
4819 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
4820 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
4822 /* (Carbon way: [theEvent keyCode]) */
4824 /* is it a "function key"? */
4825 fnKeysym = ns_convert_key (code);
4828 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
4829 because Emacs treats Delete and KP-Delete same (in simple.el). */
4830 if (fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
4831 code = 0xFF08; /* backspace */
4836 /* are there modifiers? */
4837 emacs_event->modifiers = 0;
4838 flags = [theEvent modifierFlags];
4840 if (flags & NSHelpKeyMask)
4841 emacs_event->modifiers |= hyper_modifier;
4843 if (flags & NSShiftKeyMask)
4844 emacs_event->modifiers |= shift_modifier;
4846 is_right_key = (flags & NSRightCommandKeyMask) == NSRightCommandKeyMask;
4847 is_left_key = (flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask
4848 || (! is_right_key && (flags & NSCommandKeyMask) == NSCommandKeyMask);
4851 emacs_event->modifiers |= parse_solitary_modifier
4852 (EQ (ns_right_command_modifier, Qleft)
4853 ? ns_command_modifier
4854 : ns_right_command_modifier);
4858 emacs_event->modifiers |= parse_solitary_modifier
4859 (ns_command_modifier);
4861 /* if super (default), take input manager's word so things like
4862 dvorak / qwerty layout work */
4863 if (EQ (ns_command_modifier, Qsuper)
4865 && [[theEvent characters] length] != 0)
4867 /* XXX: the code we get will be unshifted, so if we have
4868 a shift modifier, must convert ourselves */
4869 if (!(flags & NSShiftKeyMask))
4870 code = [[theEvent characters] characterAtIndex: 0];
4872 /* this is ugly and also requires linking w/Carbon framework
4873 (for LMGetKbdType) so for now leave this rare (?) case
4874 undealt with.. in future look into CGEvent methods */
4877 long smv = GetScriptManagerVariable (smKeyScript);
4878 Handle uchrHandle = GetResource
4879 ('uchr', GetScriptVariable (smv, smScriptKeys));
4881 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
4882 [[theEvent characters] characterAtIndex: 0],
4883 kUCKeyActionDisplay,
4884 (flags & ~NSCommandKeyMask) >> 8,
4885 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
4886 &dummy, 1, &dummy, &code);
4893 is_right_key = (flags & NSRightControlKeyMask) == NSRightControlKeyMask;
4894 is_left_key = (flags & NSLeftControlKeyMask) == NSLeftControlKeyMask
4895 || (! is_right_key && (flags & NSControlKeyMask) == NSControlKeyMask);
4898 emacs_event->modifiers |= parse_solitary_modifier
4899 (EQ (ns_right_control_modifier, Qleft)
4900 ? ns_control_modifier
4901 : ns_right_control_modifier);
4904 emacs_event->modifiers |= parse_solitary_modifier
4905 (ns_control_modifier);
4907 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
4908 emacs_event->modifiers |=
4909 parse_solitary_modifier (ns_function_modifier);
4911 left_is_none = NILP (ns_alternate_modifier)
4912 || EQ (ns_alternate_modifier, Qnone);
4914 is_right_key = (flags & NSRightAlternateKeyMask)
4915 == NSRightAlternateKeyMask;
4916 is_left_key = (flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask
4918 && (flags & NSAlternateKeyMask) == NSAlternateKeyMask);
4922 if ((NILP (ns_right_alternate_modifier)
4923 || EQ (ns_right_alternate_modifier, Qnone)
4924 || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
4926 { /* accept pre-interp alt comb */
4927 if ([[theEvent characters] length] > 0)
4928 code = [[theEvent characters] characterAtIndex: 0];
4929 /*HACK: clear lone shift modifier to stop next if from firing */
4930 if (emacs_event->modifiers == shift_modifier)
4931 emacs_event->modifiers = 0;
4934 emacs_event->modifiers |= parse_solitary_modifier
4935 (EQ (ns_right_alternate_modifier, Qleft)
4936 ? ns_alternate_modifier
4937 : ns_right_alternate_modifier);
4940 if (is_left_key) /* default = meta */
4942 if (left_is_none && !fnKeysym)
4943 { /* accept pre-interp alt comb */
4944 if ([[theEvent characters] length] > 0)
4945 code = [[theEvent characters] characterAtIndex: 0];
4946 /*HACK: clear lone shift modifier to stop next if from firing */
4947 if (emacs_event->modifiers == shift_modifier)
4948 emacs_event->modifiers = 0;
4951 emacs_event->modifiers |=
4952 parse_solitary_modifier (ns_alternate_modifier);
4956 fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
4957 code, fnKeysym, flags, emacs_event->modifiers);
4959 /* if it was a function key or had modifiers, pass it directly to emacs */
4960 if (fnKeysym || (emacs_event->modifiers
4961 && (emacs_event->modifiers != shift_modifier)
4962 && [[theEvent charactersIgnoringModifiers] length] > 0))
4963 /*[[theEvent characters] length] */
4965 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4967 code |= (1<<28)|(3<<16);
4968 else if (code == 0x7f)
4969 code |= (1<<28)|(3<<16);
4971 emacs_event->kind = code > 0xFF
4972 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4974 emacs_event->code = code;
4975 EV_TRAILER (theEvent);
4981 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
4982 /* if we get here we should send the key for input manager processing */
4983 if (firstTime && [[NSInputManager currentInputManager]
4984 wantsToDelayTextChangeNotifications] == NO)
4986 "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
4989 if (NS_KEYLOG && !processingCompose)
4990 fprintf (stderr, "keyDown: Begin compose sequence.\n");
4992 processingCompose = YES;
4993 [nsEvArray addObject: theEvent];
4994 [self interpretKeyEvents: nsEvArray];
4995 [nsEvArray removeObject: theEvent];
4999 #ifdef NS_IMPL_COCOA
5000 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
5001 decided not to send key-down for.
5002 See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
5003 This only applies on Tiger and earlier.
5004 If it matches one of these, send it on to keyDown. */
5005 -(void)keyUp: (NSEvent *)theEvent
5007 int flags = [theEvent modifierFlags];
5008 int code = [theEvent keyCode];
5009 if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
5010 code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
5013 fprintf (stderr, "keyUp: passed test");
5014 ns_fake_keydown = YES;
5015 [self keyDown: theEvent];
5021 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
5024 /* <NSTextInput>: called when done composing;
5025 NOTE: also called when we delete over working text, followed immed.
5026 by doCommandBySelector: deleteBackward: */
5027 - (void)insertText: (id)aString
5030 int len = [(NSString *)aString length];
5034 NSLog (@"insertText '%@'\tlen = %d", aString, len);
5035 processingCompose = NO;
5040 /* first, clear any working text */
5041 if (workingText != nil)
5042 [self deleteWorkingText];
5044 /* now insert the string as keystrokes */
5045 for (i =0; i<len; i++)
5047 code = [aString characterAtIndex: i];
5048 /* TODO: still need this? */
5050 code = '~'; /* 0x7E */
5051 if (code != 32) /* Space */
5052 emacs_event->modifiers = 0;
5054 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5055 emacs_event->code = code;
5056 EV_TRAILER ((id)nil);
5061 /* <NSTextInput>: inserts display of composing characters */
5062 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
5064 NSString *str = [aString respondsToSelector: @selector (string)] ?
5065 [aString string] : aString;
5067 NSLog (@"setMarkedText '%@' len =%d range %d from %d", str, [str length],
5068 selRange.length, selRange.location);
5070 if (workingText != nil)
5071 [self deleteWorkingText];
5072 if ([str length] == 0)
5078 processingCompose = YES;
5079 workingText = [str copy];
5080 ns_working_text = build_string ([workingText UTF8String]);
5082 emacs_event->kind = NS_TEXT_EVENT;
5083 emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
5084 EV_TRAILER ((id)nil);
5088 /* delete display of composing characters [not in <NSTextInput>] */
5089 - (void)deleteWorkingText
5091 if (workingText == nil)
5094 NSLog(@"deleteWorkingText len =%d\n", [workingText length]);
5095 [workingText release];
5097 processingCompose = NO;
5102 emacs_event->kind = NS_TEXT_EVENT;
5103 emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
5104 EV_TRAILER ((id)nil);
5108 - (BOOL)hasMarkedText
5110 return workingText != nil;
5114 - (NSRange)markedRange
5116 NSRange rng = workingText != nil
5117 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
5119 NSLog (@"markedRange request");
5127 NSLog (@"unmark (accept) text");
5128 [self deleteWorkingText];
5129 processingCompose = NO;
5133 /* used to position char selection windows, etc. */
5134 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
5138 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
5140 NSLog (@"firstRectForCharRange request");
5142 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
5143 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
5144 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
5145 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
5146 +FRAME_LINE_HEIGHT (emacsframe));
5148 pt = [self convertPoint: pt toView: nil];
5149 pt = [[self window] convertBaseToScreen: pt];
5155 - (NSInteger)conversationIdentifier
5157 return (NSInteger)self;
5161 - (void)doCommandBySelector: (SEL)aSelector
5164 NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
5166 if (aSelector == @selector (deleteBackward:))
5168 /* happens when user backspaces over an ongoing composition:
5169 throw a 'delete' into the event queue */
5172 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5173 emacs_event->code = 0xFF08;
5174 EV_TRAILER ((id)nil);
5178 - (NSArray *)validAttributesForMarkedText
5180 static NSArray *arr = nil;
5181 if (arr == nil) arr = [NSArray new];
5182 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
5186 - (NSRange)selectedRange
5189 NSLog (@"selectedRange request");
5190 return NSMakeRange (NSNotFound, 0);
5193 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
5196 NSLog (@"characterIndexForPoint request");
5200 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
5202 static NSAttributedString *str = nil;
5203 if (str == nil) str = [NSAttributedString new];
5205 NSLog (@"attributedSubstringFromRange request");
5209 /* End <NSTextInput> impl. */
5210 /*****************************************************************************/
5213 /* This is what happens when the user presses a mouse button. */
5214 - (void)mouseDown: (NSEvent *)theEvent
5216 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5218 NSTRACE (mouseDown);
5220 [self deleteWorkingText];
5225 last_mouse_frame = emacsframe;
5226 /* appears to be needed to prevent spurious movement events generated on
5228 last_mouse_frame->mouse_moved = 0;
5230 if ([theEvent type] == NSScrollWheel)
5232 float delta = [theEvent deltaY];
5233 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
5236 emacs_event->kind = WHEEL_EVENT;
5237 emacs_event->code = 0;
5238 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
5239 ((delta > 0) ? up_modifier : down_modifier);
5243 emacs_event->kind = MOUSE_CLICK_EVENT;
5244 emacs_event->code = EV_BUTTON (theEvent);
5245 emacs_event->modifiers = EV_MODIFIERS (theEvent)
5246 | EV_UDMODIFIERS (theEvent);
5248 XSETINT (emacs_event->x, lrint (p.x));
5249 XSETINT (emacs_event->y, lrint (p.y));
5250 EV_TRAILER (theEvent);
5254 - (void)rightMouseDown: (NSEvent *)theEvent
5256 NSTRACE (rightMouseDown);
5257 [self mouseDown: theEvent];
5261 - (void)otherMouseDown: (NSEvent *)theEvent
5263 NSTRACE (otherMouseDown);
5264 [self mouseDown: theEvent];
5268 - (void)mouseUp: (NSEvent *)theEvent
5271 [self mouseDown: theEvent];
5275 - (void)rightMouseUp: (NSEvent *)theEvent
5277 NSTRACE (rightMouseUp);
5278 [self mouseDown: theEvent];
5282 - (void)otherMouseUp: (NSEvent *)theEvent
5284 NSTRACE (otherMouseUp);
5285 [self mouseDown: theEvent];
5289 - (void) scrollWheel: (NSEvent *)theEvent
5291 NSTRACE (scrollWheel);
5292 [self mouseDown: theEvent];
5296 /* Tell emacs the mouse has moved. */
5297 - (void)mouseMoved: (NSEvent *)e
5299 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5302 // NSTRACE (mouseMoved);
5304 last_mouse_movement_time = EV_TIMESTAMP (e);
5305 last_mouse_motion_position
5306 = [self convertPoint: [e locationInWindow] fromView: nil];
5308 /* update any mouse face */
5309 if (hlinfo->mouse_face_hidden)
5311 hlinfo->mouse_face_hidden = 0;
5312 clear_mouse_face (hlinfo);
5315 /* tooltip handling */
5316 previous_help_echo_string = help_echo_string;
5317 help_echo_string = Qnil;
5319 if (!note_mouse_movement (emacsframe, last_mouse_motion_position.x,
5320 last_mouse_motion_position.y))
5321 help_echo_string = previous_help_echo_string;
5323 XSETFRAME (frame, emacsframe);
5324 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
5326 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
5327 (note_mouse_highlight), which is called through the
5328 note_mouse_movement () call above */
5329 gen_help_event (help_echo_string, frame, help_echo_window,
5330 help_echo_object, help_echo_pos);
5334 help_echo_string = Qnil;
5335 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
5338 if (emacsframe->mouse_moved && send_appdefined)
5339 ns_send_appdefined (-1);
5343 - (void)mouseDragged: (NSEvent *)e
5345 NSTRACE (mouseDragged);
5346 [self mouseMoved: e];
5350 - (void)rightMouseDragged: (NSEvent *)e
5352 NSTRACE (rightMouseDragged);
5353 [self mouseMoved: e];
5357 - (void)otherMouseDragged: (NSEvent *)e
5359 NSTRACE (otherMouseDragged);
5360 [self mouseMoved: e];
5364 - (BOOL)windowShouldClose: (id)sender
5366 NSEvent *e =[[self window] currentEvent];
5368 NSTRACE (windowShouldClose);
5369 windowClosing = YES;
5372 emacs_event->kind = DELETE_WINDOW_EVENT;
5373 emacs_event->modifiers = 0;
5374 emacs_event->code = 0;
5376 /* Don't close this window, let this be done from lisp code. */
5380 - (void) updateFrameSize: (BOOL) delay;
5382 NSWindow *window = [self window];
5383 NSRect wr = [window frame];
5384 #ifdef NS_IMPL_GNUSTEP
5390 int oldc = cols, oldr = rows;
5391 int oldw = FRAME_PIXEL_WIDTH (emacsframe),
5392 oldh = FRAME_PIXEL_HEIGHT (emacsframe);
5395 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, wr.size.width + extra);
5397 if (cols < MINWIDTH)
5400 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES
5401 (emacsframe, wr.size.height
5402 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe) + extra
5403 - FRAME_TOOLBAR_HEIGHT (emacsframe));
5405 if (rows < MINHEIGHT)
5408 neww = (int)wr.size.width - emacsframe->border_width;
5409 newh = ((int)wr.size.height
5410 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5411 - FRAME_TOOLBAR_HEIGHT (emacsframe));
5413 if (oldr != rows || oldc != cols || neww != oldw || newh != oldh)
5415 NSView *view = FRAME_NS_VIEW (emacsframe);
5416 FRAME_PIXEL_WIDTH (emacsframe) = neww;
5417 FRAME_PIXEL_HEIGHT (emacsframe) = newh;
5418 change_frame_size (emacsframe, rows, cols, 0, delay, 0);
5419 SET_FRAME_GARBAGED (emacsframe);
5420 cancel_mouse_face (emacsframe);
5421 [view setFrame: NSMakeRect (0, 0, neww, newh)];
5422 [self windowDidMove:nil]; // Update top/left.
5426 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
5427 /* normalize frame to gridded text size */
5429 NSTRACE (windowWillResize);
5430 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
5432 if (fs_state == FULLSCREEN_MAXIMIZED
5433 && (maximized_width != (int)frameSize.width
5434 || maximized_height != (int)frameSize.height))
5435 [self setFSValue: FULLSCREEN_NONE];
5436 else if (fs_state == FULLSCREEN_WIDTH
5437 && maximized_width != (int)frameSize.width)
5438 [self setFSValue: FULLSCREEN_NONE];
5439 else if (fs_state == FULLSCREEN_HEIGHT
5440 && maximized_height != (int)frameSize.height)
5441 [self setFSValue: FULLSCREEN_NONE];
5442 if (fs_state == FULLSCREEN_NONE)
5443 maximized_width = maximized_height = -1;
5445 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe,
5446 #ifdef NS_IMPL_GNUSTEP
5447 frameSize.width + 3);
5451 if (cols < MINWIDTH)
5454 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, frameSize.height
5455 #ifdef NS_IMPL_GNUSTEP
5456 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe) + 3
5457 - FRAME_TOOLBAR_HEIGHT (emacsframe));
5459 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5460 - FRAME_TOOLBAR_HEIGHT (emacsframe));
5462 if (rows < MINHEIGHT)
5464 #ifdef NS_IMPL_COCOA
5466 /* this sets window title to have size in it; the wm does this under GS */
5467 NSRect r = [[self window] frame];
5468 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
5479 NSWindow *window = [self window];
5482 const char *t = [[[self window] title] UTF8String];
5483 char *pos = strstr (t, " — ");
5486 old_title = xstrdup (t);
5488 size_title = xmalloc (strlen (old_title) + 40);
5489 esprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
5490 [window setTitle: [NSString stringWithUTF8String: size_title]];
5495 #endif /* NS_IMPL_COCOA */
5496 /*fprintf (stderr," ...size became %.0f x %.0f (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
5502 - (void)windowDidResize: (NSNotification *)notification
5505 #if !defined (NEW_STYLE_FS) && ! defined (NS_IMPL_GNUSTEP)
5506 NSWindow *theWindow = [notification object];
5507 /* We can get notification on the non-FS window when in fullscreen mode. */
5508 if ([self window] != theWindow) return;
5511 #ifdef NS_IMPL_GNUSTEP
5512 NSWindow *theWindow = [notification object];
5514 /* In GNUstep, at least currently, it's possible to get a didResize
5515 without getting a willResize.. therefore we need to act as if we got
5516 the willResize now */
5517 NSSize sz = [theWindow frame].size;
5518 sz = [self windowWillResize: theWindow toSize: sz];
5519 #endif /* NS_IMPL_GNUSTEP */
5521 NSTRACE (windowDidResize);
5522 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
5524 #ifdef NS_IMPL_COCOA
5530 #endif /* NS_IMPL_COCOA */
5532 if (cols > 0 && rows > 0)
5534 [self updateFrameSize: YES];
5537 ns_send_appdefined (-1);
5541 - (void)windowDidBecomeKey: (NSNotification *)notification
5542 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5544 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5545 struct frame *old_focus = dpyinfo->x_focus_frame;
5547 NSTRACE (windowDidBecomeKey);
5549 if (emacsframe != old_focus)
5550 dpyinfo->x_focus_frame = emacsframe;
5552 ns_frame_rehighlight (emacsframe);
5556 emacs_event->kind = FOCUS_IN_EVENT;
5557 EV_TRAILER ((id)nil);
5562 - (void)windowDidResignKey: (NSNotification *)notification
5563 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5565 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5566 NSTRACE (windowDidResignKey);
5568 if (dpyinfo->x_focus_frame == emacsframe)
5569 dpyinfo->x_focus_frame = 0;
5571 ns_frame_rehighlight (emacsframe);
5573 /* FIXME: for some reason needed on second and subsequent clicks away
5574 from sole-frame Emacs to get hollow box to show */
5575 if (!windowClosing && [[self window] isVisible] == YES)
5577 x_update_cursor (emacsframe, 1);
5578 x_set_frame_alpha (emacsframe);
5583 [self deleteWorkingText];
5584 emacs_event->kind = FOCUS_IN_EVENT;
5585 EV_TRAILER ((id)nil);
5590 - (void)windowWillMiniaturize: sender
5592 NSTRACE (windowWillMiniaturize);
5608 - initFrameFromEmacs: (struct frame *)f
5613 NSButton *toggleButton;
5618 NSTRACE (initFrameFromEmacs);
5621 processingCompose = NO;
5622 scrollbarsNeedingUpdate = 0;
5623 fs_state = FULLSCREEN_NONE;
5624 fs_before_fs = next_maximized = -1;
5625 maximized_width = maximized_height = -1;
5628 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
5630 ns_userRect = NSMakeRect (0, 0, 0, 0);
5631 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
5632 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
5633 [self initWithFrame: r];
5634 [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
5636 FRAME_NS_VIEW (f) = self;
5640 win = [[EmacsWindow alloc]
5641 initWithContentRect: r
5642 styleMask: (NSResizableWindowMask |
5643 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
5644 NSTitledWindowMask |
5646 NSMiniaturizableWindowMask |
5647 NSClosableWindowMask)
5648 backing: NSBackingStoreBuffered
5652 [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
5656 bwidth = f->border_width = wr.size.width - r.size.width;
5657 tibar_height = FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
5659 [win setAcceptsMouseMovedEvents: YES];
5660 [win setDelegate: self];
5661 [win useOptimizedDrawing: YES];
5663 sz.width = FRAME_COLUMN_WIDTH (f);
5664 sz.height = FRAME_LINE_HEIGHT (f);
5665 [win setResizeIncrements: sz];
5667 [[win contentView] addSubview: self];
5670 [self registerForDraggedTypes: ns_drag_types];
5673 name = [NSString stringWithUTF8String:
5674 NILP (tem) ? "Emacs" : SSDATA (tem)];
5675 [win setTitle: name];
5677 /* toolbar support */
5678 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
5679 [NSString stringWithFormat: @"Emacs Frame %d",
5681 [win setToolbar: toolbar];
5682 [toolbar setVisible: NO];
5683 #ifdef NS_IMPL_COCOA
5684 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
5685 [toggleButton setTarget: self];
5686 [toggleButton setAction: @selector (toggleToolbar: )];
5688 FRAME_TOOLBAR_HEIGHT (f) = 0;
5692 [win setMiniwindowTitle:
5693 [NSString stringWithUTF8String: SSDATA (tem)]];
5696 NSScreen *screen = [win screen];
5699 [win setFrameTopLeftPoint: NSMakePoint
5700 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
5701 IN_BOUND (-SCREENMAX,
5702 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
5705 [win makeFirstResponder: self];
5707 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5708 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
5709 [win setBackgroundColor: col];
5710 if ([col alphaComponent] != 1.0)
5711 [win setOpaque: NO];
5713 [self allocateGState];
5715 [NSApp registerServicesMenuSendTypes: ns_send_types
5723 - (void)windowDidMove: sender
5725 NSWindow *win = [self window];
5726 NSRect r = [win frame];
5727 NSArray *screens = [NSScreen screens];
5728 NSScreen *screen = [screens objectAtIndex: 0];
5730 NSTRACE (windowDidMove);
5732 if (!emacsframe->output_data.ns)
5736 emacsframe->left_pos = r.origin.x;
5737 emacsframe->top_pos =
5738 [screen frame].size.height - (r.origin.y + r.size.height);
5743 /* Called AFTER method below, but before our windowWillResize call there leads
5744 to windowDidResize -> x_set_window_size. Update emacs' notion of frame
5745 location so set_window_size moves the frame. */
5746 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
5748 emacsframe->output_data.ns->zooming = 1;
5753 /* Override to do something slightly nonstandard, but nice. First click on
5754 zoom button will zoom vertically. Second will zoom completely. Third
5755 returns to original. */
5756 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
5757 defaultFrame:(NSRect)defaultFrame
5759 NSRect result = [sender frame];
5761 NSTRACE (windowWillUseStandardFrame);
5763 if (fs_before_fs != -1) /* Entering fullscreen */
5765 result = defaultFrame;
5767 else if (next_maximized == FULLSCREEN_HEIGHT
5768 || (next_maximized == -1
5769 && abs (defaultFrame.size.height - result.size.height)
5770 > FRAME_LINE_HEIGHT (emacsframe)))
5773 ns_userRect = result;
5774 maximized_height = result.size.height = defaultFrame.size.height;
5775 maximized_width = -1;
5776 result.origin.y = defaultFrame.origin.y;
5777 [self setFSValue: FULLSCREEN_HEIGHT];
5779 else if (next_maximized == FULLSCREEN_WIDTH)
5781 ns_userRect = result;
5782 maximized_width = result.size.width = defaultFrame.size.width;
5783 maximized_height = -1;
5784 result.origin.x = defaultFrame.origin.x;
5785 [self setFSValue: FULLSCREEN_WIDTH];
5787 else if (next_maximized == FULLSCREEN_MAXIMIZED
5788 || (next_maximized == -1
5789 && abs (defaultFrame.size.width - result.size.width)
5790 > FRAME_COLUMN_WIDTH (emacsframe)))
5792 result = defaultFrame; /* second click */
5793 maximized_width = result.size.width;
5794 maximized_height = result.size.height;
5795 [self setFSValue: FULLSCREEN_MAXIMIZED];
5800 result = ns_userRect.size.height ? ns_userRect : result;
5801 ns_userRect = NSMakeRect (0, 0, 0, 0);
5802 [self setFSValue: FULLSCREEN_NONE];
5803 maximized_width = maximized_width = -1;
5806 if (fs_before_fs == -1) next_maximized = -1;
5807 [self windowWillResize: sender toSize: result.size];
5812 - (void)windowDidDeminiaturize: sender
5814 NSTRACE (windowDidDeminiaturize);
5815 if (!emacsframe->output_data.ns)
5817 emacsframe->async_iconified = 0;
5818 emacsframe->async_visible = 1;
5819 windows_or_buffers_changed++;
5823 emacs_event->kind = ICONIFY_EVENT;
5824 EV_TRAILER ((id)nil);
5829 - (void)windowDidExpose: sender
5831 NSTRACE (windowDidExpose);
5832 if (!emacsframe->output_data.ns)
5834 emacsframe->async_visible = 1;
5835 SET_FRAME_GARBAGED (emacsframe);
5837 if (send_appdefined)
5838 ns_send_appdefined (-1);
5842 - (void)windowDidMiniaturize: sender
5844 NSTRACE (windowDidMiniaturize);
5845 if (!emacsframe->output_data.ns)
5848 emacsframe->async_iconified = 1;
5849 emacsframe->async_visible = 0;
5853 emacs_event->kind = ICONIFY_EVENT;
5854 EV_TRAILER ((id)nil);
5858 - (void)windowWillEnterFullScreen:(NSNotification *)notification
5860 fs_before_fs = fs_state;
5863 - (void)windowDidEnterFullScreen:(NSNotification *)notification
5865 [self setFSValue: FULLSCREEN_BOTH];
5867 // Fix bad background.
5868 if ([toolbar isVisible])
5870 [toolbar setVisible:NO];
5871 [toolbar setVisible:YES];
5874 [self windowDidBecomeKey:notification];
5875 [nonfs_window orderOut:self];
5879 - (void)windowWillExitFullScreen:(NSNotification *)notification
5881 if (next_maximized != -1)
5882 fs_before_fs = next_maximized;
5885 - (void)windowDidExitFullScreen:(NSNotification *)notification
5887 [self setFSValue: fs_before_fs];
5889 if (next_maximized != -1)
5890 [[self window] performZoom:self];
5893 - (void)toggleFullScreen: (id)sender
5896 [[self window] toggleFullScreen:sender];
5898 NSWindow *w = [self window], *fw;
5899 BOOL onFirstScreen = [[w screen]
5900 isEqual:[[NSScreen screens] objectAtIndex:0]];
5901 struct frame *f = emacsframe;
5903 NSRect r, wr = [w frame];
5904 NSColor *col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5905 (FRAME_DEFAULT_FACE (f)),
5908 sz.width = FRAME_COLUMN_WIDTH (f);
5909 sz.height = FRAME_LINE_HEIGHT (f);
5911 if (fs_state != FULLSCREEN_BOTH)
5913 /* Hide dock and menubar if we are on the primary screen. */
5916 #if defined (NS_IMPL_COCOA) && \
5917 MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
5918 NSApplicationPresentationOptions options
5919 = NSApplicationPresentationAutoHideDock
5920 | NSApplicationPresentationAutoHideMenuBar;
5922 [NSApp setPresentationOptions: options];
5924 [NSMenu setMenuBarVisible:NO];
5928 fw = [[EmacsFSWindow alloc]
5929 initWithContentRect:[w contentRectForFrameRect:wr]
5930 styleMask:NSBorderlessWindowMask
5931 backing:NSBackingStoreBuffered
5935 [fw setContentView:[w contentView]];
5936 [fw setTitle:[w title]];
5937 [fw setDelegate:self];
5938 [fw setAcceptsMouseMovedEvents: YES];
5939 [fw useOptimizedDrawing: YES];
5940 [fw setResizeIncrements: sz];
5941 [fw setBackgroundColor: col];
5942 if ([col alphaComponent] != 1.0)
5945 f->border_width = 0;
5946 FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
5947 tobar_height = FRAME_TOOLBAR_HEIGHT (f);
5948 FRAME_TOOLBAR_HEIGHT (f) = 0;
5949 FRAME_EXTERNAL_TOOL_BAR (f) = 0;
5953 [self windowWillEnterFullScreen:nil];
5954 [fw makeKeyAndOrderFront:NSApp];
5955 [fw makeFirstResponder:self];
5957 r = [fw frameRectForContentRect:[[fw screen] frame]];
5958 [fw setFrame: r display:YES animate:YES];
5959 [self windowDidEnterFullScreen:nil];
5970 #if defined (NS_IMPL_COCOA) && \
5971 MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
5972 [NSApp setPresentationOptions: NSApplicationPresentationDefault];
5974 [NSMenu setMenuBarVisible:YES];
5978 [w setContentView:[fw contentView]];
5979 [w setResizeIncrements: sz];
5980 [w setBackgroundColor: col];
5981 if ([col alphaComponent] != 1.0)
5984 f->border_width = bwidth;
5985 FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
5986 FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
5988 FRAME_EXTERNAL_TOOL_BAR (f) = 1;
5990 [self windowWillExitFullScreen:nil];
5991 [fw setFrame: [w frame] display:YES animate:YES];
5993 [w makeKeyAndOrderFront:NSApp];
5994 [self windowDidExitFullScreen:nil];
6001 if (fs_state != emacsframe->want_fullscreen)
6003 if (fs_state == FULLSCREEN_BOTH)
6005 [self toggleFullScreen:self];
6008 switch (emacsframe->want_fullscreen)
6010 case FULLSCREEN_BOTH:
6011 [self toggleFullScreen:self];
6013 case FULLSCREEN_WIDTH:
6014 next_maximized = FULLSCREEN_WIDTH;
6015 if (fs_state != FULLSCREEN_BOTH)
6016 [[self window] performZoom:self];
6018 case FULLSCREEN_HEIGHT:
6019 next_maximized = FULLSCREEN_HEIGHT;
6020 if (fs_state != FULLSCREEN_BOTH)
6021 [[self window] performZoom:self];
6023 case FULLSCREEN_MAXIMIZED:
6024 next_maximized = FULLSCREEN_MAXIMIZED;
6025 if (fs_state != FULLSCREEN_BOTH)
6026 [[self window] performZoom:self];
6028 case FULLSCREEN_NONE:
6029 if (fs_state != FULLSCREEN_BOTH)
6031 next_maximized = FULLSCREEN_NONE;
6032 [[self window] performZoom:self];
6037 emacsframe->want_fullscreen = FULLSCREEN_NONE;
6042 - (void) setFSValue: (int)value
6044 Lisp_Object lval = Qnil;
6047 case FULLSCREEN_BOTH:
6050 case FULLSCREEN_WIDTH:
6053 case FULLSCREEN_HEIGHT:
6056 case FULLSCREEN_MAXIMIZED:
6060 store_frame_param (emacsframe, Qfullscreen, lval);
6064 - (void)mouseEntered: (NSEvent *)theEvent
6066 NSTRACE (mouseEntered);
6067 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
6071 - (void)mouseExited: (NSEvent *)theEvent
6073 Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
6075 NSTRACE (mouseExited);
6080 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
6082 if (emacsframe == hlinfo->mouse_face_mouse_frame)
6084 clear_mouse_face (hlinfo);
6085 hlinfo->mouse_face_mouse_frame = 0;
6093 if (context_menu_value == -1)
6094 context_menu_value = [sender tag];
6097 NSInteger tag = [sender tag];
6098 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
6099 emacsframe->menu_bar_vector,
6103 ns_send_appdefined (-1);
6108 - (EmacsToolbar *)toolbar
6114 /* this gets called on toolbar button click */
6115 - toolbarClicked: (id)item
6118 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
6120 NSTRACE (toolbarClicked);
6125 /* send first event (for some reason two needed) */
6126 theEvent = [[self window] currentEvent];
6127 emacs_event->kind = TOOL_BAR_EVENT;
6128 XSETFRAME (emacs_event->arg, emacsframe);
6129 EV_TRAILER (theEvent);
6131 emacs_event->kind = TOOL_BAR_EVENT;
6132 /* XSETINT (emacs_event->code, 0); */
6133 emacs_event->arg = AREF (emacsframe->tool_bar_items,
6134 idx + TOOL_BAR_ITEM_KEY);
6135 emacs_event->modifiers = EV_MODIFIERS (theEvent);
6136 EV_TRAILER (theEvent);
6141 - toggleToolbar: (id)sender
6146 emacs_event->kind = NS_NONKEY_EVENT;
6147 emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
6148 EV_TRAILER ((id)nil);
6153 - (void)drawRect: (NSRect)rect
6155 int x = NSMinX (rect), y = NSMinY (rect);
6156 int width = NSWidth (rect), height = NSHeight (rect);
6160 if (!emacsframe || !emacsframe->output_data.ns)
6163 ns_clear_frame_area (emacsframe, x, y, width, height);
6164 expose_frame (emacsframe, x, y, width, height);
6167 drawRect: may be called (at least in OS X 10.5) for invisible
6168 views as well for some reason. Thus, do not infer visibility
6171 emacsframe->async_visible = 1;
6172 emacsframe->async_iconified = 0;
6177 /* NSDraggingDestination protocol methods. Actually this is not really a
6178 protocol, but a category of Object. O well... */
6180 -(NSUInteger) draggingEntered: (id <NSDraggingInfo>) sender
6182 NSTRACE (draggingEntered);
6183 return NSDragOperationGeneric;
6187 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
6193 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
6198 NSEvent *theEvent = [[self window] currentEvent];
6201 NSTRACE (performDragOperation);
6206 position = [self convertPoint: [sender draggingLocation] fromView: nil];
6207 x = lrint (position.x); y = lrint (position.y);
6209 pb = [sender draggingPasteboard];
6210 type = [pb availableTypeFromArray: ns_drag_types];
6215 else if ([type isEqualToString: NSFilenamesPboardType])
6218 NSEnumerator *fenum;
6221 if (!(files = [pb propertyListForType: type]))
6224 fenum = [files objectEnumerator];
6225 while ( (file = [fenum nextObject]) )
6227 emacs_event->kind = NS_NONKEY_EVENT;
6228 emacs_event->code = KEY_NS_DRAG_FILE;
6229 XSETINT (emacs_event->x, x);
6230 XSETINT (emacs_event->y, y);
6231 ns_input_file = append2 (ns_input_file,
6232 build_string ([file UTF8String]));
6233 emacs_event->modifiers = EV_MODIFIERS (theEvent);
6234 EV_TRAILER (theEvent);
6238 else if ([type isEqualToString: NSURLPboardType])
6243 if (!(fileURL = [NSURL URLFromPasteboard: pb]) ||
6244 [fileURL isFileURL] == NO)
6247 file = [fileURL path];
6248 emacs_event->kind = NS_NONKEY_EVENT;
6249 emacs_event->code = KEY_NS_DRAG_FILE;
6250 XSETINT (emacs_event->x, x);
6251 XSETINT (emacs_event->y, y);
6252 ns_input_file = append2 (ns_input_file, build_string ([file UTF8String]));
6253 emacs_event->modifiers = EV_MODIFIERS (theEvent);
6254 EV_TRAILER (theEvent);
6257 else if ([type isEqualToString: NSStringPboardType]
6258 || [type isEqualToString: NSTabularTextPboardType])
6262 if (! (data = [pb stringForType: type]))
6265 emacs_event->kind = NS_NONKEY_EVENT;
6266 emacs_event->code = KEY_NS_DRAG_TEXT;
6267 XSETINT (emacs_event->x, x);
6268 XSETINT (emacs_event->y, y);
6269 ns_input_text = build_string ([data UTF8String]);
6270 emacs_event->modifiers = EV_MODIFIERS (theEvent);
6271 EV_TRAILER (theEvent);
6274 else if ([type isEqualToString: NSColorPboardType])
6276 NSColor *c = [NSColor colorFromPasteboard: pb];
6277 emacs_event->kind = NS_NONKEY_EVENT;
6278 emacs_event->code = KEY_NS_DRAG_COLOR;
6279 XSETINT (emacs_event->x, x);
6280 XSETINT (emacs_event->y, y);
6281 ns_input_color = ns_color_to_lisp (c);
6282 emacs_event->modifiers = EV_MODIFIERS (theEvent);
6283 EV_TRAILER (theEvent);
6286 else if ([type isEqualToString: NSFontPboardType])
6288 /* impl based on GNUstep NSTextView.m */
6289 NSData *data = [pb dataForType: NSFontPboardType];
6290 NSDictionary *dict = [NSUnarchiver unarchiveObjectWithData: data];
6291 NSFont *font = [dict objectForKey: NSFontAttributeName];
6297 emacs_event->kind = NS_NONKEY_EVENT;
6298 emacs_event->code = KEY_NS_CHANGE_FONT;
6299 XSETINT (emacs_event->x, x);
6300 XSETINT (emacs_event->y, y);
6301 ns_input_font = build_string ([[font fontName] UTF8String]);
6302 snprintf (fontSize, 10, "%f", [font pointSize]);
6303 ns_input_fontsize = build_string (fontSize);
6304 emacs_event->modifiers = EV_MODIFIERS (theEvent);
6305 EV_TRAILER (theEvent);
6310 error ("Invalid data type in dragging pasteboard.");
6316 - (id) validRequestorForSendType: (NSString *)typeSent
6317 returnType: (NSString *)typeReturned
6319 NSTRACE (validRequestorForSendType);
6320 if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
6321 && typeReturned == nil)
6323 if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
6327 return [super validRequestorForSendType: typeSent
6328 returnType: typeReturned];
6332 /* The next two methods are part of NSServicesRequests informal protocol,
6333 supposedly called when a services menu item is chosen from this app.
6334 But this should not happen because we override the services menu with our
6335 own entries which call ns-perform-service.
6336 Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
6337 So let's at least stub them out until further investigation can be done. */
6339 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
6341 /* we could call ns_string_from_pasteboard(pboard) here but then it should
6342 be written into the buffer in place of the existing selection..
6343 ordinary service calls go through functions defined in ns-win.el */
6347 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
6349 NSArray *typesDeclared;
6352 /* We only support NSStringPboardType */
6353 if ([types containsObject:NSStringPboardType] == NO) {
6357 val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
6358 if (CONSP (val) && SYMBOLP (XCAR (val)))
6361 if (CONSP (val) && NILP (XCDR (val)))
6364 if (! STRINGP (val))
6367 typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
6368 [pb declareTypes:typesDeclared owner:nil];
6369 ns_string_to_pasteboard (pb, val);
6374 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
6375 (gives a miniaturized version of the window); currently we use the latter for
6376 frames whose active buffer doesn't correspond to any file
6377 (e.g., '*scratch*') */
6378 - setMiniwindowImage: (BOOL) setMini
6380 id image = [[self window] miniwindowImage];
6381 NSTRACE (setMiniwindowImage);
6383 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
6384 about "AppleDockIconEnabled" notwithstanding, however the set message
6385 below has its effect nonetheless. */
6386 if (image != emacsframe->output_data.ns->miniimage)
6388 if (image && [image isKindOfClass: [EmacsImage class]])
6390 [[self window] setMiniwindowImage:
6391 setMini ? emacsframe->output_data.ns->miniimage : nil];
6398 - (void) setRows: (int) r andColumns: (int) c
6404 @end /* EmacsView */
6408 /* ==========================================================================
6410 EmacsWindow implementation
6412 ========================================================================== */
6414 @implementation EmacsWindow
6416 #ifdef NS_IMPL_COCOA
6417 - (id)accessibilityAttributeValue:(NSString *)attribute
6419 Lisp_Object str = Qnil;
6420 struct frame *f = SELECTED_FRAME ();
6421 struct buffer *curbuf = XBUFFER (XWINDOW (f->selected_window)->buffer);
6423 if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
6424 return NSAccessibilityTextFieldRole;
6426 if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]
6427 && curbuf && ! NILP (BVAR (curbuf, mark_active)))
6429 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
6431 else if (curbuf && [attribute isEqualToString:NSAccessibilityValueAttribute])
6433 if (! NILP (BVAR (curbuf, mark_active)))
6434 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
6438 ptrdiff_t start_byte = BUF_BEGV_BYTE (curbuf);
6439 ptrdiff_t byte_range = BUF_ZV_BYTE (curbuf) - start_byte;
6440 ptrdiff_t range = BUF_ZV (curbuf) - BUF_BEGV (curbuf);
6442 if (! NILP (BVAR (curbuf, enable_multibyte_characters)))
6443 str = make_uninit_multibyte_string (range, byte_range);
6445 str = make_uninit_string (range);
6446 /* To check: This returns emacs-utf-8, which is a superset of utf-8.
6447 Is this a problem? */
6448 memcpy (SDATA (str), BYTE_POS_ADDR (start_byte), byte_range);
6455 if (CONSP (str) && SYMBOLP (XCAR (str)))
6458 if (CONSP (str) && NILP (XCDR (str)))
6463 const char *utfStr = SSDATA (str);
6464 NSString *nsStr = [NSString stringWithUTF8String: utfStr];
6469 return [super accessibilityAttributeValue:attribute];
6471 #endif /* NS_IMPL_COCOA */
6473 /* If we have multiple monitors, one above the other, we don't want to
6474 restrict the height to just one monitor. So we override this. */
6475 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
6477 /* When making the frame visible for the first time or if there is just
6478 one screen, we want to constrain. Other times not. */
6479 NSUInteger nr_screens = [[NSScreen screens] count];
6480 struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
6481 NSTRACE (constrainFrameRect);
6483 if (nr_screens == 1)
6485 NSRect r = [super constrainFrameRect:frameRect toScreen:screen];
6489 if (f->output_data.ns->dont_constrain
6490 || ns_menu_bar_should_be_hidden ())
6493 f->output_data.ns->dont_constrain = 1;
6494 return [super constrainFrameRect:frameRect toScreen:screen];
6497 @end /* EmacsWindow */
6500 @implementation EmacsFSWindow
6502 - (BOOL)canBecomeKeyWindow
6507 - (BOOL)canBecomeMainWindow
6514 /* ==========================================================================
6516 EmacsScroller implementation
6518 ========================================================================== */
6521 @implementation EmacsScroller
6523 /* for repeat button push */
6524 #define SCROLL_BAR_FIRST_DELAY 0.5
6525 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
6527 + (CGFloat) scrollerWidth
6529 /* TODO: if we want to allow variable widths, this is the place to do it,
6530 however neither GNUstep nor Cocoa support it very well */
6531 return [NSScroller scrollerWidth];
6535 - initFrame: (NSRect )r window: (Lisp_Object)nwin
6537 NSTRACE (EmacsScroller_initFrame);
6539 r.size.width = [EmacsScroller scrollerWidth];
6540 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
6541 [self setContinuous: YES];
6542 [self setEnabled: YES];
6544 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
6545 locked against the top and bottom edges, and right edge on OS X, where
6546 scrollers are on right. */
6547 #ifdef NS_IMPL_GNUSTEP
6548 [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
6550 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
6555 pixel_height = NSHeight (r);
6556 if (pixel_height == 0) pixel_height = 1;
6557 min_portion = 20 / pixel_height;
6559 frame = XFRAME (XWINDOW (win)->frame);
6560 if (FRAME_LIVE_P (frame))
6563 EmacsView *view = FRAME_NS_VIEW (frame);
6564 NSView *sview = [[view window] contentView];
6565 NSArray *subs = [sview subviews];
6567 /* disable optimization stopping redraw of other scrollbars */
6568 view->scrollbarsNeedingUpdate = 0;
6569 for (i =[subs count]-1; i >= 0; i--)
6570 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
6571 view->scrollbarsNeedingUpdate++;
6572 [sview addSubview: self];
6575 /* [self setFrame: r]; */
6581 - (void)setFrame: (NSRect)newRect
6583 NSTRACE (EmacsScroller_setFrame);
6584 /* block_input (); */
6585 pixel_height = NSHeight (newRect);
6586 if (pixel_height == 0) pixel_height = 1;
6587 min_portion = 20 / pixel_height;
6588 [super setFrame: newRect];
6590 /* unblock_input (); */
6596 NSTRACE (EmacsScroller_dealloc);
6598 wset_vertical_scroll_bar (XWINDOW (win), Qnil);
6626 /* ensure other scrollbar updates after deletion */
6627 view = (EmacsView *)FRAME_NS_VIEW (frame);
6629 view->scrollbarsNeedingUpdate++;
6630 [self removeFromSuperview];
6638 - (void)resetCursorRects
6640 NSRect visible = [self visibleRect];
6641 NSTRACE (resetCursorRects);
6643 if (!NSIsEmptyRect (visible))
6644 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
6645 [[NSCursor arrowCursor] setOnMouseEntered: YES];
6649 - (int) checkSamePosition: (int) position portion: (int) portion
6652 return em_position ==position && em_portion ==portion && em_whole ==whole
6653 && portion != whole; /* needed for resize empty buf */
6657 - setPosition: (int)position portion: (int)portion whole: (int)whole
6659 NSTRACE (setPosition);
6661 em_position = position;
6662 em_portion = portion;
6665 if (portion >= whole)
6667 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
6668 [self setKnobProportion: 1.0];
6669 [self setDoubleValue: 1.0];
6671 [self setFloatValue: 0.0 knobProportion: 1.0];
6677 portion = max ((float)whole*min_portion/pixel_height, portion);
6678 pos = (float)position / (whole - portion);
6679 por = (float)portion/whole;
6680 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
6681 [self setKnobProportion: por];
6682 [self setDoubleValue: pos];
6684 [self setFloatValue: pos knobProportion: por];
6688 /* Events may come here even if the event loop is not running.
6689 If we don't enter the event loop, the scroll bar will not update.
6690 So send SIGIO to ourselves. */
6691 if (apploopnr == 0) kill (0, SIGIO);
6696 /* FIXME: unused at moment (see ns_mouse_position) at the moment because
6697 drag events will go directly to the EmacsScroller. Leaving in for now. */
6698 -(void)getMouseMotionPart: (int *)part window: (Lisp_Object *)window
6699 x: (Lisp_Object *)x y: ( Lisp_Object *)y
6701 *part = last_hit_part;
6703 XSETINT (*y, pixel_height);
6704 if ([self floatValue] > 0.999)
6705 XSETINT (*x, pixel_height);
6707 XSETINT (*x, pixel_height * [self floatValue]);
6711 /* set up emacs_event */
6712 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
6717 emacs_event->part = last_hit_part;
6718 emacs_event->code = 0;
6719 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
6720 emacs_event->frame_or_window = win;
6721 emacs_event->timestamp = EV_TIMESTAMP (e);
6722 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
6723 emacs_event->arg = Qnil;
6724 XSETINT (emacs_event->x, loc * pixel_height);
6725 XSETINT (emacs_event->y, pixel_height-20);
6729 n_emacs_events_pending++;
6730 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
6733 hold_event (emacs_event);
6734 EVENT_INIT (*emacs_event);
6735 ns_send_appdefined (-1);
6739 /* called manually thru timer to implement repeated button action w/hold-down */
6740 - repeatScroll: (NSTimer *)scrollEntry
6742 NSEvent *e = [[self window] currentEvent];
6743 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
6744 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
6746 /* clear timer if need be */
6747 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
6749 [scroll_repeat_entry invalidate];
6750 [scroll_repeat_entry release];
6751 scroll_repeat_entry = nil;
6757 = [[NSTimer scheduledTimerWithTimeInterval:
6758 SCROLL_BAR_CONTINUOUS_DELAY
6760 selector: @selector (repeatScroll:)
6766 [self sendScrollEventAtLoc: 0 fromEvent: e];
6771 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
6772 mouseDragged events without going into a modal loop. */
6773 - (void)mouseDown: (NSEvent *)e
6776 /* hitPart is only updated AFTER event is passed on */
6777 NSScrollerPart part = [self testPart: [e locationInWindow]];
6778 double inc = 0.0, loc, kloc, pos;
6781 NSTRACE (EmacsScroller_mouseDown);
6785 case NSScrollerDecrementPage:
6786 last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
6787 case NSScrollerIncrementPage:
6788 last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
6789 case NSScrollerDecrementLine:
6790 last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
6791 case NSScrollerIncrementLine:
6792 last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
6793 case NSScrollerKnob:
6794 last_hit_part = scroll_bar_handle; break;
6795 case NSScrollerKnobSlot: /* GNUstep-only */
6796 last_hit_part = scroll_bar_move_ratio; break;
6797 default: /* NSScrollerNoPart? */
6798 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
6805 pos = 0; /* ignored */
6807 /* set a timer to repeat, as we can't let superclass do this modally */
6809 = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
6811 selector: @selector (repeatScroll:)
6818 /* handle, or on GNUstep possibly slot */
6819 NSEvent *fake_event;
6821 /* compute float loc in slot and mouse offset on knob */
6822 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6824 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6830 else if (loc >= NSHeight (sr))
6832 loc = NSHeight (sr);
6840 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
6842 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
6844 last_mouse_offset = kloc;
6846 /* if knob, tell emacs a location offset by knob pos
6847 (to indicate top of handle) */
6848 if (part == NSScrollerKnob)
6849 pos = (loc - last_mouse_offset) / NSHeight (sr);
6851 /* else this is a slot click on GNUstep: go straight there */
6852 pos = loc / NSHeight (sr);
6854 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
6855 fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
6856 location: [e locationInWindow]
6857 modifierFlags: [e modifierFlags]
6858 timestamp: [e timestamp]
6859 windowNumber: [e windowNumber]
6860 context: [e context]
6861 eventNumber: [e eventNumber]
6862 clickCount: [e clickCount]
6863 pressure: [e pressure]];
6864 [super mouseUp: fake_event];
6867 if (part != NSScrollerKnob)
6868 [self sendScrollEventAtLoc: pos fromEvent: e];
6872 /* Called as we manually track scroller drags, rather than superclass. */
6873 - (void)mouseDragged: (NSEvent *)e
6879 NSTRACE (EmacsScroller_mouseDragged);
6881 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6883 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6890 else if (loc >= NSHeight (sr) + last_mouse_offset)
6892 loc = NSHeight (sr) + last_mouse_offset;
6896 pos = /*(edge ? loc :*/ (loc - last_mouse_offset) / NSHeight (sr);
6897 [self sendScrollEventAtLoc: pos fromEvent: e];
6901 - (void)mouseUp: (NSEvent *)e
6903 if (scroll_repeat_entry)
6905 [scroll_repeat_entry invalidate];
6906 [scroll_repeat_entry release];
6907 scroll_repeat_entry = nil;
6913 /* treat scrollwheel events in the bar as though they were in the main window */
6914 - (void) scrollWheel: (NSEvent *)theEvent
6916 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
6917 [view mouseDown: theEvent];
6920 @end /* EmacsScroller */
6925 /* ==========================================================================
6927 Font-related functions; these used to be in nsfaces.m
6929 ========================================================================== */
6933 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
6935 struct font *font = XFONT_OBJECT (font_object);
6938 fontset = fontset_from_font (font_object);
6939 FRAME_FONTSET (f) = fontset;
6941 if (FRAME_FONT (f) == font)
6942 /* This font is already set in frame F. There's nothing more to
6946 FRAME_FONT (f) = font;
6948 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
6949 FRAME_COLUMN_WIDTH (f) = font->average_width;
6950 FRAME_SPACE_WIDTH (f) = font->space_width;
6951 FRAME_LINE_HEIGHT (f) = font->height;
6953 compute_fringe_widths (f, 1);
6955 /* Compute the scroll bar width in character columns. */
6956 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
6958 int wid = FRAME_COLUMN_WIDTH (f);
6959 FRAME_CONFIG_SCROLL_BAR_COLS (f)
6960 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
6964 int wid = FRAME_COLUMN_WIDTH (f);
6965 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
6968 /* Now make the frame display the given font. */
6969 if (FRAME_NS_WINDOW (f) != 0)
6970 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
6976 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
6977 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
6981 ns_xlfd_to_fontname (const char *xlfd)
6982 /* --------------------------------------------------------------------------
6983 Convert an X font name (XLFD) to an NS font name.
6984 Only family is used.
6985 The string returned is temporarily allocated.
6986 -------------------------------------------------------------------------- */
6988 char *name = xmalloc (180);
6992 if (!strncmp (xlfd, "--", 2))
6993 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
6995 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
6997 /* stopgap for malformed XLFD input */
6998 if (strlen (name) == 0)
6999 strcpy (name, "Monaco");
7001 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
7002 also uppercase after '-' or ' ' */
7003 name[0] = c_toupper (name[0]);
7004 for (len =strlen (name), i =0; i<len; i++)
7010 name[i+1] = c_toupper (name[i+1]);
7012 else if (name[i] == '_')
7016 name[i+1] = c_toupper (name[i+1]);
7019 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
7020 ret = [[NSString stringWithUTF8String: name] UTF8String];
7027 syms_of_nsterm (void)
7029 NSTRACE (syms_of_nsterm);
7031 ns_antialias_threshold = 10.0;
7033 /* from 23+ we need to tell emacs what modifiers there are.. */
7034 DEFSYM (Qmodifier_value, "modifier-value");
7035 DEFSYM (Qalt, "alt");
7036 DEFSYM (Qhyper, "hyper");
7037 DEFSYM (Qmeta, "meta");
7038 DEFSYM (Qsuper, "super");
7039 DEFSYM (Qcontrol, "control");
7040 DEFSYM (QUTF8_STRING, "UTF8_STRING");
7042 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
7043 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
7044 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
7045 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
7046 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
7048 DEFVAR_LISP ("ns-input-file", ns_input_file,
7049 "The file specified in the last NS event.");
7050 ns_input_file =Qnil;
7052 DEFVAR_LISP ("ns-input-text", ns_input_text,
7053 "The data received in the last NS text drag event.");
7054 ns_input_text =Qnil;
7056 DEFVAR_LISP ("ns-working-text", ns_working_text,
7057 "String for visualizing working composition sequence.");
7058 ns_working_text =Qnil;
7060 DEFVAR_LISP ("ns-input-font", ns_input_font,
7061 "The font specified in the last NS event.");
7062 ns_input_font =Qnil;
7064 DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
7065 "The fontsize specified in the last NS event.");
7066 ns_input_fontsize =Qnil;
7068 DEFVAR_LISP ("ns-input-line", ns_input_line,
7069 "The line specified in the last NS event.");
7070 ns_input_line =Qnil;
7072 DEFVAR_LISP ("ns-input-color", ns_input_color,
7073 "The color specified in the last NS event.");
7074 ns_input_color =Qnil;
7076 DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
7077 "The service name specified in the last NS event.");
7078 ns_input_spi_name =Qnil;
7080 DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
7081 "The service argument specified in the last NS event.");
7082 ns_input_spi_arg =Qnil;
7084 DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
7085 "This variable describes the behavior of the 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 none means that the alternate / option key is not interpreted by Emacs\n\
7088 at all, allowing it to be used at a lower level for accented character entry.");
7089 ns_alternate_modifier = Qmeta;
7091 DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
7092 "This variable describes the behavior of the right alternate or option key.\n\
7093 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7094 Set to left means be the same key as `ns-alternate-modifier'.\n\
7095 Set to none means that the alternate / option key is not interpreted by Emacs\n\
7096 at all, allowing it to be used at a lower level for accented character entry.");
7097 ns_right_alternate_modifier = Qleft;
7099 DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
7100 "This variable describes the behavior of the command key.\n\
7101 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
7102 ns_command_modifier = Qsuper;
7104 DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
7105 "This variable describes the behavior of the right command key.\n\
7106 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7107 Set to left means be the same key as `ns-command-modifier'.\n\
7108 Set to none means that the command / option key is not interpreted by Emacs\n\
7109 at all, allowing it to be used at a lower level for accented character entry.");
7110 ns_right_command_modifier = Qleft;
7112 DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
7113 "This variable describes the behavior of the control key.\n\
7114 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
7115 ns_control_modifier = Qcontrol;
7117 DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
7118 "This variable describes the behavior of the right control key.\n\
7119 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7120 Set to left means be the same key as `ns-control-modifier'.\n\
7121 Set to none means that the control / option key is not interpreted by Emacs\n\
7122 at all, allowing it to be used at a lower level for accented character entry.");
7123 ns_right_control_modifier = Qleft;
7125 DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
7126 "This variable describes the behavior of the function key (on laptops).\n\
7127 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7128 Set to none means that the function key is not interpreted by Emacs at all,\n\
7129 allowing it to be used at a lower level for accented character entry.");
7130 ns_function_modifier = Qnone;
7132 DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
7133 "Non-nil (the default) means to render text antialiased.");
7134 ns_antialias_text = Qt;
7136 DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
7137 "Whether to confirm application quit using dialog.");
7138 ns_confirm_quit = Qnil;
7140 staticpro (&ns_display_name_list);
7141 ns_display_name_list = Qnil;
7143 staticpro (&last_mouse_motion_frame);
7144 last_mouse_motion_frame = Qnil;
7146 DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
7147 doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
7148 Only works on OSX 10.6 or later. */);
7149 ns_auto_hide_menu_bar = Qnil;
7151 /* TODO: move to common code */
7152 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
7153 doc: /* Which toolkit scroll bars Emacs uses, if any.
7154 A value of nil means Emacs doesn't use toolkit scroll bars.
7155 With the X Window system, the value is a symbol describing the
7156 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
7157 With MS Windows or Nextstep, the value is t. */);
7158 Vx_toolkit_scroll_bars = Qt;
7160 DEFVAR_BOOL ("x-use-underline-position-properties",
7161 x_use_underline_position_properties,
7162 doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
7163 A value of nil means ignore them. If you encounter fonts with bogus
7164 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
7165 to 4.1, set this to nil. */);
7166 x_use_underline_position_properties = 0;
7168 DEFVAR_BOOL ("x-underline-at-descent-line",
7169 x_underline_at_descent_line,
7170 doc: /* Non-nil means to draw the underline at the same place as the descent line.
7171 A value of nil means to draw the underline according to the value of the
7172 variable `x-use-underline-position-properties', which is usually at the
7173 baseline level. The default value is nil. */);
7174 x_underline_at_descent_line = 0;
7176 /* Tell emacs about this window system. */
7177 Fprovide (intern ("ns"), Qnil);