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. */
36 #include <sys/types.h>
42 #include <c-strcase.h>
46 #include "blockinput.h"
47 #include "sysselect.h"
50 #include "character.h"
52 #include "composite.h"
55 #include "termhooks.h"
65 int term_trace_num = 0;
66 #define NSTRACE(x) fprintf (stderr, "%s:%d: [%d] " #x "\n", \
67 __FILE__, __LINE__, ++term_trace_num)
72 extern NSString *NSMenuDidBeginTrackingNotification;
74 /* ==========================================================================
78 ========================================================================== */
80 /* Convert a symbol indexed with an NSxxx value to a value as defined
81 in keyboard.c (lispy_function_key). I hope this is a correct way
83 static unsigned convert_ns_to_X_keysym[] =
85 NSHomeFunctionKey, 0x50,
86 NSLeftArrowFunctionKey, 0x51,
87 NSUpArrowFunctionKey, 0x52,
88 NSRightArrowFunctionKey, 0x53,
89 NSDownArrowFunctionKey, 0x54,
90 NSPageUpFunctionKey, 0x55,
91 NSPageDownFunctionKey, 0x56,
92 NSEndFunctionKey, 0x57,
93 NSBeginFunctionKey, 0x58,
94 NSSelectFunctionKey, 0x60,
95 NSPrintFunctionKey, 0x61,
96 NSClearLineFunctionKey, 0x0B,
97 NSExecuteFunctionKey, 0x62,
98 NSInsertFunctionKey, 0x63,
99 NSUndoFunctionKey, 0x65,
100 NSRedoFunctionKey, 0x66,
101 NSMenuFunctionKey, 0x67,
102 NSFindFunctionKey, 0x68,
103 NSHelpFunctionKey, 0x6A,
104 NSBreakFunctionKey, 0x6B,
106 NSF1FunctionKey, 0xBE,
107 NSF2FunctionKey, 0xBF,
108 NSF3FunctionKey, 0xC0,
109 NSF4FunctionKey, 0xC1,
110 NSF5FunctionKey, 0xC2,
111 NSF6FunctionKey, 0xC3,
112 NSF7FunctionKey, 0xC4,
113 NSF8FunctionKey, 0xC5,
114 NSF9FunctionKey, 0xC6,
115 NSF10FunctionKey, 0xC7,
116 NSF11FunctionKey, 0xC8,
117 NSF12FunctionKey, 0xC9,
118 NSF13FunctionKey, 0xCA,
119 NSF14FunctionKey, 0xCB,
120 NSF15FunctionKey, 0xCC,
121 NSF16FunctionKey, 0xCD,
122 NSF17FunctionKey, 0xCE,
123 NSF18FunctionKey, 0xCF,
124 NSF19FunctionKey, 0xD0,
125 NSF20FunctionKey, 0xD1,
126 NSF21FunctionKey, 0xD2,
127 NSF22FunctionKey, 0xD3,
128 NSF23FunctionKey, 0xD4,
129 NSF24FunctionKey, 0xD5,
131 NSBackspaceCharacter, 0x08, /* 8: Not on some KBs. */
132 NSDeleteCharacter, 0xFF, /* 127: Big 'delete' key upper right. */
133 NSDeleteFunctionKey, 0x9F, /* 63272: Del forw key off main array. */
135 NSTabCharacter, 0x09,
136 0x19, 0x09, /* left tab->regular since pass shift */
137 NSCarriageReturnCharacter, 0x0D,
138 NSNewlineCharacter, 0x0D,
139 NSEnterCharacter, 0x8D,
141 0x41|NSNumericPadKeyMask, 0xAE, /* KP_Decimal */
142 0x43|NSNumericPadKeyMask, 0xAA, /* KP_Multiply */
143 0x45|NSNumericPadKeyMask, 0xAB, /* KP_Add */
144 0x4B|NSNumericPadKeyMask, 0xAF, /* KP_Divide */
145 0x4E|NSNumericPadKeyMask, 0xAD, /* KP_Subtract */
146 0x51|NSNumericPadKeyMask, 0xBD, /* KP_Equal */
147 0x52|NSNumericPadKeyMask, 0xB0, /* KP_0 */
148 0x53|NSNumericPadKeyMask, 0xB1, /* KP_1 */
149 0x54|NSNumericPadKeyMask, 0xB2, /* KP_2 */
150 0x55|NSNumericPadKeyMask, 0xB3, /* KP_3 */
151 0x56|NSNumericPadKeyMask, 0xB4, /* KP_4 */
152 0x57|NSNumericPadKeyMask, 0xB5, /* KP_5 */
153 0x58|NSNumericPadKeyMask, 0xB6, /* KP_6 */
154 0x59|NSNumericPadKeyMask, 0xB7, /* KP_7 */
155 0x5B|NSNumericPadKeyMask, 0xB8, /* KP_8 */
156 0x5C|NSNumericPadKeyMask, 0xB9, /* KP_9 */
158 0x1B, 0x1B /* escape */
161 static Lisp_Object Qmodifier_value;
162 Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper;
163 extern Lisp_Object Qcursor_color, Qcursor_type, Qns, Qleft;
165 static Lisp_Object QUTF8_STRING;
167 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
168 the maximum font size to NOT antialias. On GNUstep there is currently
169 no way to control this behavior. */
170 float ns_antialias_threshold;
172 /* Used to pick up AppleHighlightColor on OS X */
173 NSString *ns_selection_color;
175 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
176 NSString *ns_app_name = @"Emacs"; /* default changed later */
178 /* Display variables */
179 struct ns_display_info *x_display_list; /* Chain of existing displays */
180 Lisp_Object ns_display_name_list;
181 long context_menu_value = 0;
184 NSPoint last_mouse_motion_position;
185 static NSRect last_mouse_glyph;
186 static Time last_mouse_movement_time = 0;
187 static Lisp_Object last_mouse_motion_frame;
188 static EmacsScroller *last_mouse_scroll_bar = nil;
189 static struct frame *ns_updating_frame;
190 static NSView *focus_view = NULL;
191 static int ns_window_num = 0;
192 #ifdef NS_IMPL_GNUSTEP
195 static BOOL gsaved = NO;
196 static BOOL ns_fake_keydown = NO;
197 int ns_tmp_flags; /* FIXME */
198 struct nsfont_info *ns_tmp_font; /* FIXME */
199 static BOOL ns_menu_bar_is_hidden = NO;
200 /*static int debug_lock = 0; */
203 static BOOL send_appdefined = YES;
204 #define NO_APPDEFINED_DATA (-8)
205 static int last_appdefined_event_data = NO_APPDEFINED_DATA;
206 static NSTimer *timed_entry = 0;
207 static NSTimer *scroll_repeat_entry = nil;
208 static fd_set select_readfds, select_writefds;
209 enum { SELECT_HAVE_READ = 1, SELECT_HAVE_WRITE = 2, SELECT_HAVE_TMO = 4 };
210 static int select_nfds = 0, select_valid = 0;
211 static EMACS_TIME select_timeout = { 0, 0 };
212 static int selfds[2] = { -1, -1 };
213 static pthread_mutex_t select_mutex;
214 static int apploopnr = 0;
215 static NSAutoreleasePool *outerpool;
216 static struct input_event *emacs_event = NULL;
217 static struct input_event *q_event_ptr = NULL;
218 static int n_emacs_events_pending = 0;
219 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
220 *ns_pending_service_args;
221 static BOOL ns_do_open_file = NO;
222 static BOOL ns_last_use_native_fullscreen;
225 struct input_event *q;
232 * State for pending menu activation:
233 * MENU_NONE Normal state
234 * MENU_PENDING A menu has been clicked on, but has been canceled so we can
235 * run lisp to update the menu.
236 * MENU_OPENING Menu is up to date, and the click event is redone so the menu
240 #define MENU_PENDING 1
241 #define MENU_OPENING 2
242 static int menu_will_open_state = MENU_NONE;
244 /* Saved position for menu click. */
245 static CGPoint menu_mouse_point;
247 /* Title for the menu to open. */
248 static char *menu_pending_title = 0;
250 /* Convert modifiers in a NeXTstep event to emacs style modifiers. */
251 #define NS_FUNCTION_KEY_MASK 0x800000
252 #define NSLeftControlKeyMask (0x000001 | NSControlKeyMask)
253 #define NSRightControlKeyMask (0x002000 | NSControlKeyMask)
254 #define NSLeftCommandKeyMask (0x000008 | NSCommandKeyMask)
255 #define NSRightCommandKeyMask (0x000010 | NSCommandKeyMask)
256 #define NSLeftAlternateKeyMask (0x000020 | NSAlternateKeyMask)
257 #define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
258 #define EV_MODIFIERS(e) \
259 ((([e modifierFlags] & NSHelpKeyMask) ? \
260 hyper_modifier : 0) \
261 | (!EQ (ns_right_alternate_modifier, Qleft) && \
262 (([e modifierFlags] & NSRightAlternateKeyMask) \
263 == NSRightAlternateKeyMask) ? \
264 parse_solitary_modifier (ns_right_alternate_modifier) : 0) \
265 | (([e modifierFlags] & NSAlternateKeyMask) ? \
266 parse_solitary_modifier (ns_alternate_modifier) : 0) \
267 | (([e modifierFlags] & NSShiftKeyMask) ? \
268 shift_modifier : 0) \
269 | (!EQ (ns_right_control_modifier, Qleft) && \
270 (([e modifierFlags] & NSRightControlKeyMask) \
271 == NSRightControlKeyMask) ? \
272 parse_solitary_modifier (ns_right_control_modifier) : 0) \
273 | (([e modifierFlags] & NSControlKeyMask) ? \
274 parse_solitary_modifier (ns_control_modifier) : 0) \
275 | (([e modifierFlags] & NS_FUNCTION_KEY_MASK) ? \
276 parse_solitary_modifier (ns_function_modifier) : 0) \
277 | (!EQ (ns_right_command_modifier, Qleft) && \
278 (([e modifierFlags] & NSRightCommandKeyMask) \
279 == NSRightCommandKeyMask) ? \
280 parse_solitary_modifier (ns_right_command_modifier) : 0) \
281 | (([e modifierFlags] & NSCommandKeyMask) ? \
282 parse_solitary_modifier (ns_command_modifier):0))
284 #define EV_UDMODIFIERS(e) \
285 ((([e type] == NSLeftMouseDown) ? down_modifier : 0) \
286 | (([e type] == NSRightMouseDown) ? down_modifier : 0) \
287 | (([e type] == NSOtherMouseDown) ? down_modifier : 0) \
288 | (([e type] == NSLeftMouseDragged) ? down_modifier : 0) \
289 | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
290 | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
291 | (([e type] == NSLeftMouseUp) ? up_modifier : 0) \
292 | (([e type] == NSRightMouseUp) ? up_modifier : 0) \
293 | (([e type] == NSOtherMouseUp) ? up_modifier : 0))
295 #define EV_BUTTON(e) \
296 ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 : \
297 (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
298 [e buttonNumber] - 1)
300 /* Convert the time field to a timestamp in milliseconds. */
301 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
303 /* This is a piece of code which is common to all the event handling
304 methods. Maybe it should even be a function. */
305 #define EV_TRAILER(e) \
307 XSETFRAME (emacs_event->frame_or_window, emacsframe); \
308 if (e) emacs_event->timestamp = EV_TIMESTAMP (e); \
311 n_emacs_events_pending++; \
312 kbd_buffer_store_event_hold (emacs_event, q_event_ptr); \
315 hold_event (emacs_event); \
316 EVENT_INIT (*emacs_event); \
317 ns_send_appdefined (-1); \
320 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
322 /* TODO: get rid of need for these forward declarations */
323 static void ns_condemn_scroll_bars (struct frame *f);
324 static void ns_judge_scroll_bars (struct frame *f);
325 void x_set_frame_alpha (struct frame *f);
328 /* ==========================================================================
332 ========================================================================== */
335 hold_event (struct input_event *event)
337 if (hold_event_q.nr == hold_event_q.cap)
339 if (hold_event_q.cap == 0) hold_event_q.cap = 10;
340 else hold_event_q.cap *= 2;
341 hold_event_q.q = (struct input_event *)
342 xrealloc (hold_event_q.q, hold_event_q.cap * sizeof (*hold_event_q.q));
345 hold_event_q.q[hold_event_q.nr++] = *event;
346 /* Make sure ns_read_socket is called, i.e. we have input. */
348 send_appdefined = YES;
352 append2 (Lisp_Object list, Lisp_Object item)
353 /* --------------------------------------------------------------------------
354 Utility to append to a list
355 -------------------------------------------------------------------------- */
357 Lisp_Object array[2];
359 array[1] = Fcons (item, Qnil);
360 return Fnconc (2, &array[0]);
365 ns_etc_directory (void)
366 /* If running as a self-contained app bundle, return as a string the
367 filename of the etc directory, if present; else nil. */
369 NSBundle *bundle = [NSBundle mainBundle];
370 NSString *resourceDir = [bundle resourcePath];
371 NSString *resourcePath;
372 NSFileManager *fileManager = [NSFileManager defaultManager];
375 resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
376 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
378 if (isDir) return [resourcePath UTF8String];
386 /* If running as a self-contained app bundle, return as a path string
387 the filenames of the libexec and bin directories, ie libexec:bin.
388 Otherwise, return nil.
389 Normally, Emacs does not add its own bin/ directory to the PATH.
390 However, a self-contained NS build has a different layout, with
391 bin/ and libexec/ subdirectories in the directory that contains
393 We put libexec first, because init_callproc_1 uses the first
394 element to initialize exec-directory. An alternative would be
395 for init_callproc to check for invocation-directory/libexec.
398 NSBundle *bundle = [NSBundle mainBundle];
399 NSString *resourceDir = [bundle resourcePath];
400 NSString *binDir = [bundle bundlePath];
401 NSString *resourcePath, *resourcePaths;
403 NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
404 NSFileManager *fileManager = [NSFileManager defaultManager];
406 NSEnumerator *pathEnum;
409 range = [resourceDir rangeOfString: @"Contents"];
410 if (range.location != NSNotFound)
412 binDir = [binDir stringByAppendingPathComponent: @"Contents"];
414 binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
418 paths = [binDir stringsByAppendingPaths:
419 [NSArray arrayWithObjects: @"libexec", @"bin", nil]];
420 pathEnum = [paths objectEnumerator];
423 while ((resourcePath = [pathEnum nextObject]))
425 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
428 if ([resourcePaths length] > 0)
430 = [resourcePaths stringByAppendingString: pathSeparator];
432 = [resourcePaths stringByAppendingString: resourcePath];
435 if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
443 /* If running as a self-contained app bundle, return as a path string
444 the filenames of the site-lisp, lisp and leim directories.
445 Ie, site-lisp:lisp:leim. Otherwise, return nil. */
447 NSBundle *bundle = [NSBundle mainBundle];
448 NSString *resourceDir = [bundle resourcePath];
449 NSString *resourcePath, *resourcePaths;
450 NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
451 NSFileManager *fileManager = [NSFileManager defaultManager];
453 NSArray *paths = [resourceDir stringsByAppendingPaths:
454 [NSArray arrayWithObjects:
455 @"site-lisp", @"lisp", @"leim", nil]];
456 NSEnumerator *pathEnum = [paths objectEnumerator];
459 /* Hack to skip site-lisp. */
460 if (no_site_lisp) resourcePath = [pathEnum nextObject];
462 while ((resourcePath = [pathEnum nextObject]))
464 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
467 if ([resourcePaths length] > 0)
469 = [resourcePaths stringByAppendingString: pathSeparator];
471 = [resourcePaths stringByAppendingString: resourcePath];
474 if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
480 ns_timeout (int usecs)
481 /* --------------------------------------------------------------------------
482 Blocking timer utility used by ns_ring_bell
483 -------------------------------------------------------------------------- */
485 EMACS_TIME wakeup = add_emacs_time (current_emacs_time (),
486 make_emacs_time (0, usecs * 1000));
488 /* Keep waiting until past the time wakeup. */
491 EMACS_TIME timeout, now = current_emacs_time ();
492 if (EMACS_TIME_LE (wakeup, now))
494 timeout = sub_emacs_time (wakeup, now);
496 /* Try to wait that long--but we might wake up sooner. */
497 pselect (0, NULL, NULL, NULL, &timeout, NULL);
503 ns_release_object (void *obj)
504 /* --------------------------------------------------------------------------
505 Release an object (callable from C)
506 -------------------------------------------------------------------------- */
513 ns_retain_object (void *obj)
514 /* --------------------------------------------------------------------------
515 Retain an object (callable from C)
516 -------------------------------------------------------------------------- */
523 ns_alloc_autorelease_pool (void)
524 /* --------------------------------------------------------------------------
525 Allocate a pool for temporary objects (callable from C)
526 -------------------------------------------------------------------------- */
528 return [[NSAutoreleasePool alloc] init];
533 ns_release_autorelease_pool (void *pool)
534 /* --------------------------------------------------------------------------
535 Free a pool and temporary objects it refers to (callable from C)
536 -------------------------------------------------------------------------- */
538 ns_release_object (pool);
543 /* ==========================================================================
545 Focus (clipping) and screen update
547 ========================================================================== */
550 // Window constraining
551 // -------------------
553 // To ensure that the windows are not placed under the menu bar, they
554 // are typically moved by the call-back constrainFrameRect. However,
555 // by overriding it, it's possible to inhibit this, leaving the window
556 // in it's original position.
558 // It's possible to hide the menu bar. However, technically, it's only
559 // possible to hide it when the application is active. To ensure that
560 // this work properly, the menu bar and window constraining are
561 // deferred until the application becomes active.
563 // Even though it's not possible to manually move a window above the
564 // top of the screen, it is allowed if it's done programmatically,
565 // when the menu is hidden. This allows the editable area to cover the
566 // full screen height.
571 // Use the following extra files:
574 // ;; Hide menu and place frame slightly above the top of the screen.
575 // (setq ns-auto-hide-menu-bar t)
576 // (set-frame-position (selected-frame) 0 -20)
580 // emacs -Q -l init.el
582 // Result: No menu bar, and the title bar should be above the screen.
588 // Result: Menu bar visible, frame placed immediately below the menu.
592 ns_constrain_all_frames (void)
594 Lisp_Object tail, frame;
596 FOR_EACH_FRAME (tail, frame)
598 struct frame *f = XFRAME (frame);
601 NSView *view = FRAME_NS_VIEW (f);
602 /* This no-op will trigger the default window placing
603 * constraint system. */
604 f->output_data.ns->dont_constrain = 0;
605 [[view window] setFrameOrigin:[[view window] frame].origin];
611 /* True, if the menu bar should be hidden. */
614 ns_menu_bar_should_be_hidden (void)
616 return !NILP (ns_auto_hide_menu_bar)
617 && [NSApp respondsToSelector:@selector(setPresentationOptions:)];
621 /* Show or hide the menu bar, based on user setting. */
624 ns_update_auto_hide_menu_bar (void)
627 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
630 NSTRACE (ns_update_auto_hide_menu_bar);
634 && [NSApp respondsToSelector:@selector(setPresentationOptions:)])
636 // Note, "setPresentationOptions" triggers an error unless the
637 // application is active.
638 BOOL menu_bar_should_be_hidden = ns_menu_bar_should_be_hidden ();
640 if (menu_bar_should_be_hidden != ns_menu_bar_is_hidden)
642 NSApplicationPresentationOptions options
643 = NSApplicationPresentationAutoHideDock;
645 if (menu_bar_should_be_hidden)
646 options |= NSApplicationPresentationAutoHideMenuBar;
648 [NSApp setPresentationOptions: options];
650 ns_menu_bar_is_hidden = menu_bar_should_be_hidden;
652 if (!ns_menu_bar_is_hidden)
654 ns_constrain_all_frames ();
666 ns_update_begin (struct frame *f)
667 /* --------------------------------------------------------------------------
668 Prepare for a grouped sequence of drawing calls
669 external (RIF) call; whole frame, called before update_window_begin
670 -------------------------------------------------------------------------- */
672 NSView *view = FRAME_NS_VIEW (f);
673 NSRect r = [view frame];
675 NSTRACE (ns_update_begin);
677 ns_update_auto_hide_menu_bar ();
679 ns_updating_frame = f;
682 /* drawRect may have been called for say the minibuffer, and then clip path
683 is for the minibuffer. But the display engine may draw more because
684 we have set the frame as garbaged. So reset clip path to the whole
686 bp = [[NSBezierPath bezierPathWithRect: r] retain];
690 #ifdef NS_IMPL_GNUSTEP
691 uRect = NSMakeRect (0, 0, 0, 0);
697 ns_update_window_begin (struct window *w)
698 /* --------------------------------------------------------------------------
699 Prepare for a grouped sequence of drawing calls
700 external (RIF) call; for one window, called after update_begin
701 -------------------------------------------------------------------------- */
703 struct frame *f = XFRAME (WINDOW_FRAME (w));
704 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
705 NSTRACE (ns_update_window_begin);
707 set_output_cursor (&w->cursor);
711 if (f == hlinfo->mouse_face_mouse_frame)
713 /* Don't do highlighting for mouse motion during the update. */
714 hlinfo->mouse_face_defer = 1;
716 /* If the frame needs to be redrawn,
717 simply forget about any prior mouse highlighting. */
718 if (FRAME_GARBAGED_P (f))
719 hlinfo->mouse_face_window = Qnil;
721 /* (further code for mouse faces ifdef'd out in other terms elided) */
729 ns_update_window_end (struct window *w, int cursor_on_p,
730 int mouse_face_overwritten_p)
731 /* --------------------------------------------------------------------------
732 Finished a grouped sequence of drawing calls
733 external (RIF) call; for one window called before update_end
734 -------------------------------------------------------------------------- */
736 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (XFRAME (w->frame));
738 /* note: this fn is nearly identical in all terms */
739 if (!w->pseudo_window_p)
744 display_and_set_cursor (w, 1,
745 output_cursor.hpos, output_cursor.vpos,
746 output_cursor.x, output_cursor.y);
748 if (draw_window_fringes (w, 1))
749 x_draw_vertical_border (w);
754 /* If a row with mouse-face was overwritten, arrange for
755 frame_up_to_date to redisplay the mouse highlight. */
756 if (mouse_face_overwritten_p)
758 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
759 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
760 hlinfo->mouse_face_window = Qnil;
763 updated_window = NULL;
764 NSTRACE (update_window_end);
769 ns_update_end (struct frame *f)
770 /* --------------------------------------------------------------------------
771 Finished a grouped sequence of drawing calls
772 external (RIF) call; for whole frame, called after update_window_end
773 -------------------------------------------------------------------------- */
775 NSView *view = FRAME_NS_VIEW (f);
777 /* if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
778 MOUSE_HL_INFO (f)->mouse_face_defer = 0;
782 #ifdef NS_IMPL_GNUSTEP
783 /* trigger flush only in the rectangle we tracked as being drawn */
784 [view unlockFocusNeedsFlush: NO];
785 /*fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", uRect.origin.x, uRect.origin.y, uRect.size.width, uRect.size.height); */
786 [view lockFocusInRect: uRect];
790 [[view window] flushWindow];
793 ns_updating_frame = NULL;
794 NSTRACE (ns_update_end);
799 ns_flush (struct frame *f)
800 /* --------------------------------------------------------------------------
802 NS impl is no-op since currently we flush in ns_update_end and elsewhere
803 -------------------------------------------------------------------------- */
810 ns_focus (struct frame *f, NSRect *r, int n)
811 /* --------------------------------------------------------------------------
812 Internal: Focus on given frame. During small local updates this is used to
813 draw, however during large updates, ns_update_begin and ns_update_end are
814 called to wrap the whole thing, in which case these calls are stubbed out.
815 Except, on GNUstep, we accumulate the rectangle being drawn into, because
816 the back end won't do this automatically, and will just end up flushing
818 -------------------------------------------------------------------------- */
820 // NSTRACE (ns_focus);
821 #ifdef NS_IMPL_GNUSTEP
824 u = NSUnionRect (r[0], r[1]);
829 fprintf (stderr, "focus: %d", c++);
830 if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
831 fprintf (stderr, "\n"); */
833 if (f != ns_updating_frame)
835 NSView *view = FRAME_NS_VIEW (f);
836 if (view != focus_view)
838 if (focus_view != NULL)
840 [focus_view unlockFocus];
841 [[focus_view window] flushWindow];
846 #ifdef NS_IMPL_GNUSTEP
847 r ? [view lockFocusInRect: u] : [view lockFocus];
852 /*if (view) debug_lock++; */
854 #ifdef NS_IMPL_GNUSTEP
857 /* more than one rect being drawn into */
860 [view unlockFocus]; /* add prev rect to redraw list */
861 [view lockFocusInRect: u]; /* focus for draw in new rect */
866 #ifdef NS_IMPL_GNUSTEP
869 /* in batch mode, but in GNUstep must still track rectangles explicitly */
870 uRect = (r ? NSUnionRect (uRect, u) : [FRAME_NS_VIEW (f) visibleRect]);
877 [[NSGraphicsContext currentContext] saveGraphicsState];
879 NSRectClipList (r, 2);
888 ns_unfocus (struct frame *f)
889 /* --------------------------------------------------------------------------
890 Internal: Remove focus on given frame
891 -------------------------------------------------------------------------- */
893 // NSTRACE (ns_unfocus);
897 [[NSGraphicsContext currentContext] restoreGraphicsState];
901 if (f != ns_updating_frame)
903 if (focus_view != NULL)
905 [focus_view unlockFocus];
906 [[focus_view window] flushWindow];
915 ns_clip_to_row (struct window *w, struct glyph_row *row, int area, BOOL gc)
916 /* --------------------------------------------------------------------------
917 Internal (but parallels other terms): Focus drawing on given row
918 -------------------------------------------------------------------------- */
920 struct frame *f = XFRAME (WINDOW_FRAME (w));
922 int window_x, window_y, window_width;
924 window_box (w, area, &window_x, &window_y, &window_width, 0);
926 clip_rect.origin.x = window_x;
927 clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
928 clip_rect.origin.y = max (clip_rect.origin.y, window_y);
929 clip_rect.size.width = window_width;
930 clip_rect.size.height = row->visible_height;
932 ns_focus (f, &clip_rect, 1);
937 ns_ring_bell (struct frame *f)
938 /* --------------------------------------------------------------------------
940 -------------------------------------------------------------------------- */
942 NSTRACE (ns_ring_bell);
945 NSAutoreleasePool *pool;
946 struct frame *frame = SELECTED_FRAME ();
950 pool = [[NSAutoreleasePool alloc] init];
952 view = FRAME_NS_VIEW (frame);
956 NSPoint dim = NSMakePoint (128, 128);
959 r.origin.x += (r.size.width - dim.x) / 2;
960 r.origin.y += (r.size.height - dim.y) / 2;
961 r.size.width = dim.x;
962 r.size.height = dim.y;
963 surr = NSInsetRect (r, -2, -2);
964 ns_focus (frame, &surr, 1);
965 [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
966 [ns_lookup_indexed_color (NS_FACE_FOREGROUND
967 (FRAME_DEFAULT_FACE (frame)), frame) set];
969 [[view window] flushWindow];
971 [[view window] restoreCachedImage];
972 [[view window] flushWindow];
986 ns_reset_terminal_modes (struct terminal *terminal)
987 /* Externally called as hook */
989 NSTRACE (ns_reset_terminal_modes);
994 ns_set_terminal_modes (struct terminal *terminal)
995 /* Externally called as hook */
997 NSTRACE (ns_set_terminal_modes);
1002 /* ==========================================================================
1004 Frame / window manager related functions
1006 ========================================================================== */
1010 ns_raise_frame (struct frame *f)
1011 /* --------------------------------------------------------------------------
1012 Bring window to foreground and make it active
1013 -------------------------------------------------------------------------- */
1015 NSView *view = FRAME_NS_VIEW (f);
1018 if (FRAME_VISIBLE_P (f))
1019 [[view window] makeKeyAndOrderFront: NSApp];
1025 ns_lower_frame (struct frame *f)
1026 /* --------------------------------------------------------------------------
1028 -------------------------------------------------------------------------- */
1030 NSView *view = FRAME_NS_VIEW (f);
1033 [[view window] orderBack: NSApp];
1039 ns_frame_raise_lower (struct frame *f, int raise)
1040 /* --------------------------------------------------------------------------
1042 -------------------------------------------------------------------------- */
1044 NSTRACE (ns_frame_raise_lower);
1054 ns_frame_rehighlight (struct frame *frame)
1055 /* --------------------------------------------------------------------------
1056 External (hook): called on things like window switching within frame
1057 -------------------------------------------------------------------------- */
1059 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
1060 struct frame *old_highlight = dpyinfo->x_highlight_frame;
1062 NSTRACE (ns_frame_rehighlight);
1063 if (dpyinfo->x_focus_frame)
1065 dpyinfo->x_highlight_frame
1066 = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1067 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1068 : dpyinfo->x_focus_frame);
1069 if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
1071 fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
1072 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
1076 dpyinfo->x_highlight_frame = 0;
1078 if (dpyinfo->x_highlight_frame &&
1079 dpyinfo->x_highlight_frame != old_highlight)
1083 x_update_cursor (old_highlight, 1);
1084 x_set_frame_alpha (old_highlight);
1086 if (dpyinfo->x_highlight_frame)
1088 x_update_cursor (dpyinfo->x_highlight_frame, 1);
1089 x_set_frame_alpha (dpyinfo->x_highlight_frame);
1096 x_make_frame_visible (struct frame *f)
1097 /* --------------------------------------------------------------------------
1098 External: Show the window (X11 semantics)
1099 -------------------------------------------------------------------------- */
1101 NSTRACE (x_make_frame_visible);
1102 /* XXX: at some points in past this was not needed, as the only place that
1103 called this (frame.c:Fraise_frame ()) also called raise_lower;
1104 if this ends up the case again, comment this out again. */
1105 if (!FRAME_VISIBLE_P (f))
1107 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1109 SET_FRAME_VISIBLE (f, 1);
1112 /* Making a new frame from a fullscreen frame will make the new frame
1113 fullscreen also. So skip handleFS as this will print an error. */
1114 if ([view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH
1115 && [view isFullscreen])
1118 if (f->want_fullscreen != FULLSCREEN_NONE)
1129 x_make_frame_invisible (struct frame *f)
1130 /* --------------------------------------------------------------------------
1131 External: Hide the window (X11 semantics)
1132 -------------------------------------------------------------------------- */
1134 NSView * view = FRAME_NS_VIEW (f);
1135 NSTRACE (x_make_frame_invisible);
1137 [[view window] orderOut: NSApp];
1138 SET_FRAME_VISIBLE (f, 0);
1139 SET_FRAME_ICONIFIED (f, 0);
1144 x_iconify_frame (struct frame *f)
1145 /* --------------------------------------------------------------------------
1146 External: Iconify window
1147 -------------------------------------------------------------------------- */
1149 NSView * view = FRAME_NS_VIEW (f);
1150 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1151 NSTRACE (x_iconify_frame);
1154 if (dpyinfo->x_highlight_frame == f)
1155 dpyinfo->x_highlight_frame = 0;
1157 if ([[view window] windowNumber] <= 0)
1159 /* the window is still deferred. Make it very small, bring it
1160 on screen and order it out. */
1161 NSRect s = { { 100, 100}, {0, 0} };
1163 t = [[view window] frame];
1164 [[view window] setFrame: s display: NO];
1165 [[view window] orderBack: NSApp];
1166 [[view window] orderOut: NSApp];
1167 [[view window] setFrame: t display: NO];
1169 [[view window] miniaturize: NSApp];
1172 /* Free X resources of frame F. */
1175 x_free_frame_resources (struct frame *f)
1177 NSView *view = FRAME_NS_VIEW (f);
1178 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1179 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1180 NSTRACE (x_free_frame_resources);
1183 [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1187 free_frame_menubar (f);
1189 if (FRAME_FACE_CACHE (f))
1190 free_frame_faces (f);
1192 if (f == dpyinfo->x_focus_frame)
1193 dpyinfo->x_focus_frame = 0;
1194 if (f == dpyinfo->x_highlight_frame)
1195 dpyinfo->x_highlight_frame = 0;
1196 if (f == hlinfo->mouse_face_mouse_frame)
1198 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
1199 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
1200 hlinfo->mouse_face_window = Qnil;
1201 hlinfo->mouse_face_mouse_frame = 0;
1204 if (f->output_data.ns->miniimage != nil)
1205 [f->output_data.ns->miniimage release];
1207 [[view window] close];
1210 xfree (f->output_data.ns);
1216 x_destroy_window (struct frame *f)
1217 /* --------------------------------------------------------------------------
1218 External: Delete the window
1219 -------------------------------------------------------------------------- */
1221 NSTRACE (x_destroy_window);
1223 x_free_frame_resources (f);
1229 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1230 /* --------------------------------------------------------------------------
1231 External: Position the window
1232 -------------------------------------------------------------------------- */
1234 NSView *view = FRAME_NS_VIEW (f);
1235 NSArray *screens = [NSScreen screens];
1236 NSScreen *fscreen = [screens objectAtIndex: 0];
1237 NSScreen *screen = [[view window] screen];
1239 NSTRACE (x_set_offset);
1246 if (view != nil && screen && fscreen)
1248 f->left_pos = f->size_hint_flags & XNegative
1249 ? [screen visibleFrame].size.width + f->left_pos - FRAME_PIXEL_WIDTH (f)
1251 /* We use visibleFrame here to take menu bar into account.
1252 Ideally we should also adjust left/top with visibleFrame.origin. */
1254 f->top_pos = f->size_hint_flags & YNegative
1255 ? ([screen visibleFrame].size.height + f->top_pos
1256 - FRAME_PIXEL_HEIGHT (f) - FRAME_NS_TITLEBAR_HEIGHT (f)
1257 - FRAME_TOOLBAR_HEIGHT (f))
1259 #ifdef NS_IMPL_GNUSTEP
1260 if (f->left_pos < 100)
1261 f->left_pos = 100; /* don't overlap menu */
1263 /* Constrain the setFrameTopLeftPoint so we don't move behind the
1265 f->output_data.ns->dont_constrain = 0;
1266 [[view window] setFrameTopLeftPoint:
1267 NSMakePoint (SCREENMAXBOUND (f->left_pos),
1268 SCREENMAXBOUND ([fscreen frame].size.height
1269 - NS_TOP_POS (f)))];
1270 f->size_hint_flags &= ~(XNegative|YNegative);
1278 x_set_window_size (struct frame *f, int change_grav, int cols, int rows)
1279 /* --------------------------------------------------------------------------
1280 Adjust window pixel size based on given character grid size
1281 Impl is a bit more complex than other terms, need to do some
1283 -------------------------------------------------------------------------- */
1285 EmacsView *view = FRAME_NS_VIEW (f);
1286 NSWindow *window = [view window];
1287 NSRect wr = [window frame];
1288 int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1289 int pixelwidth, pixelheight;
1291 NSTRACE (x_set_window_size);
1296 /*fprintf (stderr, "\tsetWindowSize: %d x %d, font size %d x %d\n", cols, rows, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f)); */
1300 check_frame_size (f, &rows, &cols);
1302 f->scroll_bar_actual_width = NS_SCROLL_BAR_WIDTH (f);
1303 compute_fringe_widths (f, 0);
1305 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols);
1306 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
1308 /* If we have a toolbar, take its height into account. */
1309 if (tb && ! [view isFullscreen])
1310 /* NOTE: previously this would generate wrong result if toolbar not
1311 yet displayed and fixing toolbar_height=32 helped, but
1312 now (200903) seems no longer needed */
1313 FRAME_TOOLBAR_HEIGHT (f) =
1314 NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1315 - FRAME_NS_TITLEBAR_HEIGHT (f);
1317 FRAME_TOOLBAR_HEIGHT (f) = 0;
1319 wr.size.width = pixelwidth + f->border_width;
1320 wr.size.height = pixelheight;
1321 if (! [view isFullscreen])
1322 wr.size.height += FRAME_NS_TITLEBAR_HEIGHT (f)
1323 + FRAME_TOOLBAR_HEIGHT (f);
1325 /* Do not try to constrain to this screen. We may have multiple
1326 screens, and want Emacs to span those. Constraining to screen
1327 prevents that, and that is not nice to the user. */
1328 if (f->output_data.ns->zooming)
1329 f->output_data.ns->zooming = 0;
1331 wr.origin.y += FRAME_PIXEL_HEIGHT (f) - pixelheight;
1333 [view setRows: rows andColumns: cols];
1334 [window setFrame: wr display: YES];
1336 /*fprintf (stderr, "\tx_set_window_size %d, %d\t%d, %d\n", cols, rows, pixelwidth, pixelheight); */
1338 /* This is a trick to compensate for Emacs' managing the scrollbar area
1339 as a fixed number of standard character columns. Instead of leaving
1340 blank space for the extra, we chopped it off above. Now for
1341 left-hand scrollbars, we shift all rendering to the left by the
1342 difference between the real width and Emacs' imagined one. For
1343 right-hand bars, don't worry about it since the extra is never used.
1344 (Obviously doesn't work for vertically split windows tho..) */
1346 NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1347 ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1348 - NS_SCROLL_BAR_WIDTH (f), 0)
1349 : NSMakePoint (0, 0);
1350 [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1351 [view setBoundsOrigin: origin];
1354 change_frame_size (f, rows, cols, 0, 1, 0); /* pretend, delay, safe */
1355 FRAME_PIXEL_WIDTH (f) = pixelwidth;
1356 FRAME_PIXEL_HEIGHT (f) = pixelheight;
1357 /* SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */
1359 mark_window_cursors_off (XWINDOW (f->root_window));
1360 cancel_mouse_face (f);
1367 ns_fullscreen_hook (FRAME_PTR f)
1369 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1371 if (!FRAME_VISIBLE_P (f))
1374 if (! [view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH)
1376 /* Old style fs don't initiate correctly if created from
1377 init/default-frame alist, so use a timer (not nice...).
1379 [NSTimer scheduledTimerWithTimeInterval: 0.5 target: view
1380 selector: @selector (handleFS)
1381 userInfo: nil repeats: NO];
1390 /* ==========================================================================
1394 ========================================================================== */
1398 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1400 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1401 if (idx < 1 || idx >= color_table->avail)
1403 return color_table->colors[idx];
1408 ns_index_color (NSColor *color, struct frame *f)
1410 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1414 if (!color_table->colors)
1416 color_table->size = NS_COLOR_CAPACITY;
1417 color_table->avail = 1; /* skip idx=0 as marker */
1418 color_table->colors = xmalloc (color_table->size * sizeof (NSColor *));
1419 color_table->colors[0] = nil;
1420 color_table->empty_indices = [[NSMutableSet alloc] init];
1423 /* do we already have this color ? */
1424 for (i = 1; i < color_table->avail; i++)
1425 if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1428 if ([color_table->empty_indices count] > 0)
1430 NSNumber *index = [color_table->empty_indices anyObject];
1431 [color_table->empty_indices removeObject: index];
1432 idx = [index unsignedLongValue];
1436 if (color_table->avail == color_table->size)
1437 color_table->colors =
1438 xpalloc (color_table->colors, &color_table->size, 1,
1439 min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1440 idx = color_table->avail++;
1443 color_table->colors[idx] = color;
1445 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1451 ns_free_indexed_color (unsigned long idx, struct frame *f)
1453 struct ns_color_table *color_table;
1460 color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1462 if (idx <= 0 || idx >= color_table->size) {
1463 message1 ("ns_free_indexed_color: Color index out of range.\n");
1467 index = [NSNumber numberWithUnsignedInt: idx];
1468 if ([color_table->empty_indices containsObject: index]) {
1469 message1 ("ns_free_indexed_color: attempt to free already freed color.\n");
1473 color = color_table->colors[idx];
1475 color_table->colors[idx] = nil;
1476 [color_table->empty_indices addObject: index];
1477 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1482 ns_get_color (const char *name, NSColor **col)
1483 /* --------------------------------------------------------------------------
1485 -------------------------------------------------------------------------- */
1486 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1487 X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1488 See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1491 static char hex[20];
1493 float r = -1.0, g, b;
1494 NSString *nsname = [NSString stringWithUTF8String: name];
1496 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1499 if ([nsname isEqualToString: @"ns_selection_color"])
1501 nsname = ns_selection_color;
1502 name = [ns_selection_color UTF8String];
1505 /* First, check for some sort of numeric specification. */
1508 if (name[0] == '0' || name[0] == '1' || name[0] == '.') /* RGB decimal */
1510 NSScanner *scanner = [NSScanner scannerWithString: nsname];
1511 [scanner scanFloat: &r];
1512 [scanner scanFloat: &g];
1513 [scanner scanFloat: &b];
1515 else if (!strncmp(name, "rgb:", 4)) /* A newer X11 format -- rgb:r/g/b */
1516 scaling = (snprintf (hex, sizeof hex, "%s", name + 4) - 2) / 3;
1517 else if (name[0] == '#') /* An old X11 format; convert to newer */
1519 int len = (strlen(name) - 1);
1520 int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1522 scaling = strlen(name+start) / 3;
1523 for (i = 0; i < 3; i++)
1524 sprintf (hex + i * (scaling + 1), "%.*s/", scaling,
1525 name + start + i * scaling);
1526 hex[3 * (scaling + 1) - 1] = '\0';
1532 float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1533 if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1543 *col = [NSColor colorWithCalibratedRed: r green: g blue: b alpha: 1.0];
1548 /* Otherwise, color is expected to be from a list */
1550 NSEnumerator *lenum, *cenum;
1554 #ifdef NS_IMPL_GNUSTEP
1555 /* XXX: who is wrong, the requestor or the implementation? */
1556 if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1558 nsname = @"highlightColor";
1561 lenum = [[NSColorList availableColorLists] objectEnumerator];
1562 while ( (clist = [lenum nextObject]) && new == nil)
1564 cenum = [[clist allKeys] objectEnumerator];
1565 while ( (name = [cenum nextObject]) && new == nil )
1567 if ([name compare: nsname
1568 options: NSCaseInsensitiveSearch] == NSOrderedSame )
1569 new = [clist colorWithKey: name];
1575 *col = [new colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1582 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1583 /* --------------------------------------------------------------------------
1584 Convert a Lisp string object to a NS color
1585 -------------------------------------------------------------------------- */
1587 NSTRACE (ns_lisp_to_color);
1588 if (STRINGP (color))
1589 return ns_get_color (SSDATA (color), col);
1590 else if (SYMBOLP (color))
1591 return ns_get_color (SSDATA (SYMBOL_NAME (color)), col);
1597 ns_color_to_lisp (NSColor *col)
1598 /* --------------------------------------------------------------------------
1599 Convert a color to a lisp string with the RGB equivalent
1600 -------------------------------------------------------------------------- */
1602 CGFloat red, green, blue, alpha, gray;
1605 NSTRACE (ns_color_to_lisp);
1608 if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1610 if ((str =[[col colorNameComponent] UTF8String]))
1613 return build_string ((char *)str);
1616 [[col colorUsingColorSpaceName: NSCalibratedRGBColorSpace]
1617 getRed: &red green: &green blue: &blue alpha: &alpha];
1618 if (red ==green && red ==blue)
1620 [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1621 getWhite: &gray alpha: &alpha];
1622 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1623 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1625 return build_string (buf);
1628 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1629 lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1632 return build_string (buf);
1637 ns_query_color(void *col, XColor *color_def, int setPixel)
1638 /* --------------------------------------------------------------------------
1639 Get ARGB values out of NSColor col and put them into color_def.
1640 If setPixel, set the pixel to a concatenated version.
1641 and set color_def pixel to the resulting index.
1642 -------------------------------------------------------------------------- */
1646 [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1647 color_def->red = r * 65535;
1648 color_def->green = g * 65535;
1649 color_def->blue = b * 65535;
1651 if (setPixel == YES)
1653 = ARGB_TO_ULONG((int)(a*255),
1654 (int)(r*255), (int)(g*255), (int)(b*255));
1659 ns_defined_color (struct frame *f,
1664 /* --------------------------------------------------------------------------
1665 Return true if named color found, and set color_def rgb accordingly.
1666 If makeIndex and alloc are nonzero put the color in the color_table,
1667 and set color_def pixel to the resulting index.
1668 If makeIndex is zero, set color_def pixel to ARGB.
1669 Return false if not found
1670 -------------------------------------------------------------------------- */
1673 NSTRACE (ns_defined_color);
1676 if (ns_get_color (name, &col) != 0) /* Color not found */
1681 if (makeIndex && alloc)
1682 color_def->pixel = ns_index_color (col, f);
1683 ns_query_color (col, color_def, !makeIndex);
1690 ns_get_rgb_color (struct frame *f, float r, float g, float b, float a)
1691 /* --------------------------------------------------------------------------
1692 return an autoreleased RGB color
1693 -------------------------------------------------------------------------- */
1695 /*static int c = 1; fprintf (stderr, "color request %d\n", c++); */
1696 if (r < 0.0) r = 0.0;
1697 else if (r > 1.0) r = 1.0;
1698 if (g < 0.0) g = 0.0;
1699 else if (g > 1.0) g = 1.0;
1700 if (b < 0.0) b = 0.0;
1701 else if (b > 1.0) b = 1.0;
1702 if (a < 0.0) a = 0.0;
1703 else if (a > 1.0) a = 1.0;
1704 return (unsigned long) ns_index_color(
1705 [NSColor colorWithCalibratedRed: r green: g blue: b alpha: a], f);
1710 x_set_frame_alpha (struct frame *f)
1711 /* --------------------------------------------------------------------------
1712 change the entire-frame transparency
1713 -------------------------------------------------------------------------- */
1715 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1716 EmacsView *view = FRAME_NS_VIEW (f);
1718 double alpha_min = 1.0;
1720 if (dpyinfo->x_highlight_frame == f)
1721 alpha = f->alpha[0];
1723 alpha = f->alpha[1];
1725 if (FLOATP (Vframe_alpha_lower_limit))
1726 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1727 else if (INTEGERP (Vframe_alpha_lower_limit))
1728 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1732 else if (1.0 < alpha)
1734 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1737 #ifdef NS_IMPL_COCOA
1738 [[view window] setAlphaValue: alpha];
1743 /* ==========================================================================
1747 ========================================================================== */
1751 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1752 /* --------------------------------------------------------------------------
1753 Programmatically reposition mouse pointer in pixel coordinates
1754 -------------------------------------------------------------------------- */
1756 NSTRACE (x_set_mouse_pixel_position);
1759 /* FIXME: this does not work, and what about GNUstep? */
1760 #ifdef NS_IMPL_COCOA
1761 [FRAME_NS_VIEW (f) lockFocus];
1762 PSsetmouse ((float)pix_x, (float)pix_y);
1763 [FRAME_NS_VIEW (f) unlockFocus];
1770 x_set_mouse_position (struct frame *f, int h, int v)
1771 /* --------------------------------------------------------------------------
1772 Programmatically reposition mouse pointer in character coordinates
1773 -------------------------------------------------------------------------- */
1777 pix_x = FRAME_COL_TO_PIXEL_X (f, h) + FRAME_COLUMN_WIDTH (f) / 2;
1778 pix_y = FRAME_LINE_TO_PIXEL_Y (f, v) + FRAME_LINE_HEIGHT (f) / 2;
1780 if (pix_x < 0) pix_x = 0;
1781 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
1783 if (pix_y < 0) pix_y = 0;
1784 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
1786 x_set_mouse_pixel_position (f, pix_x, pix_y);
1791 note_mouse_movement (struct frame *frame, float x, float y)
1792 /* ------------------------------------------------------------------------
1793 Called by EmacsView on mouseMovement events. Passes on
1794 to emacs mainstream code if we moved off of a rect of interest
1795 known as last_mouse_glyph.
1796 ------------------------------------------------------------------------ */
1798 // NSTRACE (note_mouse_movement);
1800 XSETFRAME (last_mouse_motion_frame, frame);
1802 /* Note, this doesn't get called for enter/leave, since we don't have a
1803 position. Those are taken care of in the corresponding NSView methods. */
1805 /* has movement gone beyond last rect we were tracking? */
1806 if (x < last_mouse_glyph.origin.x ||
1807 x >= (last_mouse_glyph.origin.x + last_mouse_glyph.size.width) ||
1808 y < last_mouse_glyph.origin.y ||
1809 y >= (last_mouse_glyph.origin.y + last_mouse_glyph.size.height))
1811 ns_update_begin(frame);
1812 frame->mouse_moved = 1;
1813 note_mouse_highlight (frame, x, y);
1814 remember_mouse_glyph (frame, x, y, &last_mouse_glyph);
1815 ns_update_end(frame);
1824 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1825 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1827 /* --------------------------------------------------------------------------
1828 External (hook): inform emacs about mouse position and hit parts.
1829 If a scrollbar is being dragged, set bar_window, part, x, y, time.
1830 x & y should be position in the scrollbar (the whole bar, not the handle)
1831 and length of scrollbar respectively
1832 -------------------------------------------------------------------------- */
1836 Lisp_Object frame, tail;
1838 struct ns_display_info *dpyinfo;
1840 NSTRACE (ns_mouse_position);
1844 fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1848 dpyinfo = FRAME_NS_DISPLAY_INFO (*fp);
1852 if (last_mouse_scroll_bar != nil && insist == 0)
1854 /* TODO: we do not use this path at the moment because drag events will
1855 go directly to the EmacsScroller. Leaving code in for now. */
1856 [last_mouse_scroll_bar getMouseMotionPart: (int *)part window: bar_window
1858 if (time) *time = last_mouse_movement_time;
1859 last_mouse_scroll_bar = nil;
1863 /* Clear the mouse-moved flag for every frame on this display. */
1864 FOR_EACH_FRAME (tail, frame)
1865 if (FRAME_NS_P (XFRAME (frame))
1866 && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1867 XFRAME (frame)->mouse_moved = 0;
1869 last_mouse_scroll_bar = nil;
1870 if (last_mouse_frame && FRAME_LIVE_P (last_mouse_frame))
1871 f = last_mouse_frame;
1873 f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame
1874 : SELECTED_FRAME ();
1876 if (f && f->output_data.ns) /* TODO: 2nd check no longer needed? */
1878 view = FRAME_NS_VIEW (*fp);
1880 position = [[view window] mouseLocationOutsideOfEventStream];
1881 position = [view convertPoint: position fromView: nil];
1882 remember_mouse_glyph (f, position.x, position.y, &last_mouse_glyph);
1883 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1885 if (bar_window) *bar_window = Qnil;
1886 if (part) *part = 0; /*scroll_bar_handle; */
1888 if (x) XSETINT (*x, lrint (position.x));
1889 if (y) XSETINT (*y, lrint (position.y));
1890 if (time) *time = last_mouse_movement_time;
1900 ns_frame_up_to_date (struct frame *f)
1901 /* --------------------------------------------------------------------------
1902 External (hook): Fix up mouse highlighting right after a full update.
1903 Can't use FRAME_MOUSE_UPDATE due to ns_frame_begin and ns_frame_end calls.
1904 -------------------------------------------------------------------------- */
1906 NSTRACE (ns_frame_up_to_date);
1910 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1911 if (f == hlinfo->mouse_face_mouse_frame)
1915 if (hlinfo->mouse_face_mouse_frame)
1916 note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
1917 hlinfo->mouse_face_mouse_x,
1918 hlinfo->mouse_face_mouse_y);
1927 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1928 /* --------------------------------------------------------------------------
1929 External (RIF): set frame mouse pointer type.
1930 -------------------------------------------------------------------------- */
1932 NSTRACE (ns_define_frame_cursor);
1933 if (FRAME_POINTER_TYPE (f) != cursor)
1935 EmacsView *view = FRAME_NS_VIEW (f);
1936 FRAME_POINTER_TYPE (f) = cursor;
1937 [[view window] invalidateCursorRectsForView: view];
1938 /* Redisplay assumes this function also draws the changed frame
1939 cursor, but this function doesn't, so do it explicitly. */
1940 x_update_cursor (f, 1);
1946 /* ==========================================================================
1950 ========================================================================== */
1954 ns_convert_key (unsigned code)
1955 /* --------------------------------------------------------------------------
1956 Internal call used by NSView-keyDown.
1957 -------------------------------------------------------------------------- */
1959 const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym)
1960 / sizeof (convert_ns_to_X_keysym[0]));
1962 /* An array would be faster, but less easy to read. */
1963 for (keysym = 0; keysym < last_keysym; keysym += 2)
1964 if (code == convert_ns_to_X_keysym[keysym])
1965 return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
1967 /* if decide to use keyCode and Carbon table, use this line:
1968 return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
1973 x_get_keysym_name (int keysym)
1974 /* --------------------------------------------------------------------------
1975 Called by keyboard.c. Not sure if the return val is important, except
1977 -------------------------------------------------------------------------- */
1979 static char value[16];
1980 NSTRACE (x_get_keysym_name);
1981 sprintf (value, "%d", keysym);
1987 /* ==========================================================================
1989 Block drawing operations
1991 ========================================================================== */
1995 ns_redraw_scroll_bars (struct frame *f)
1999 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
2000 NSTRACE (ns_redraw_scroll_bars);
2001 for (i =[subviews count]-1; i >= 0; i--)
2003 view = [subviews objectAtIndex: i];
2004 if (![view isKindOfClass: [EmacsScroller class]]) continue;
2011 ns_clear_frame (struct frame *f)
2012 /* --------------------------------------------------------------------------
2013 External (hook): Erase the entire frame
2014 -------------------------------------------------------------------------- */
2016 NSView *view = FRAME_NS_VIEW (f);
2019 NSTRACE (ns_clear_frame);
2021 /* comes on initial frame because we have
2022 after-make-frame-functions = select-frame */
2023 if (!FRAME_DEFAULT_FACE (f))
2026 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2028 output_cursor.hpos = output_cursor.vpos = 0;
2029 output_cursor.x = -1;
2034 ns_focus (f, &r, 1);
2035 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
2039 /* as of 2006/11 or so this is now needed */
2040 ns_redraw_scroll_bars (f);
2046 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2047 /* --------------------------------------------------------------------------
2048 External (RIF): Clear section of frame
2049 -------------------------------------------------------------------------- */
2051 NSRect r = NSMakeRect (x, y, width, height);
2052 NSView *view = FRAME_NS_VIEW (f);
2053 struct face *face = FRAME_DEFAULT_FACE (f);
2058 NSTRACE (ns_clear_frame_area);
2060 r = NSIntersectionRect (r, [view frame]);
2061 ns_focus (f, &r, 1);
2062 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2072 ns_scroll_run (struct window *w, struct run *run)
2073 /* --------------------------------------------------------------------------
2074 External (RIF): Insert or delete n lines at line vpos
2075 -------------------------------------------------------------------------- */
2077 struct frame *f = XFRAME (w->frame);
2078 int x, y, width, height, from_y, to_y, bottom_y;
2080 NSTRACE (ns_scroll_run);
2082 /* begin copy from other terms */
2083 /* Get frame-relative bounding box of the text display area of W,
2084 without mode lines. Include in this box the left and right
2086 window_box (w, -1, &x, &y, &width, &height);
2088 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2089 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2090 bottom_y = y + height;
2094 /* Scrolling up. Make sure we don't copy part of the mode
2095 line at the bottom. */
2096 if (from_y + run->height > bottom_y)
2097 height = bottom_y - from_y;
2099 height = run->height;
2103 /* Scrolling down. Make sure we don't copy over the mode line.
2105 if (to_y + run->height > bottom_y)
2106 height = bottom_y - to_y;
2108 height = run->height;
2110 /* end copy from other terms */
2121 NSRect srcRect = NSMakeRect (x, from_y, width, height);
2122 NSRect dstRect = NSMakeRect (x, to_y, width, height);
2123 NSPoint dstOrigin = NSMakePoint (x, to_y);
2125 ns_focus (f, &dstRect, 1);
2126 NSCopyBits (0, srcRect , dstOrigin);
2135 ns_after_update_window_line (struct glyph_row *desired_row)
2136 /* --------------------------------------------------------------------------
2137 External (RIF): preparatory to fringe update after text was updated
2138 -------------------------------------------------------------------------- */
2140 struct window *w = updated_window;
2144 NSTRACE (ns_after_update_window_line);
2146 /* begin copy from other terms */
2149 if (!desired_row->mode_line_p && !w->pseudo_window_p)
2150 desired_row->redraw_fringe_bitmaps_p = 1;
2152 /* When a window has disappeared, make sure that no rest of
2153 full-width rows stays visible in the internal border. */
2154 if (windows_or_buffers_changed
2155 && desired_row->full_width_p
2156 && (f = XFRAME (w->frame),
2157 width = FRAME_INTERNAL_BORDER_WIDTH (f),
2159 && (height = desired_row->visible_height,
2162 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2165 ns_clear_frame_area (f, 0, y, width, height);
2166 ns_clear_frame_area (f,
2167 FRAME_PIXEL_WIDTH (f) - width,
2175 ns_shift_glyphs_for_insert (struct frame *f,
2176 int x, int y, int width, int height,
2178 /* --------------------------------------------------------------------------
2179 External (RIF): copy an area horizontally, don't worry about clearing src
2180 -------------------------------------------------------------------------- */
2182 NSRect srcRect = NSMakeRect (x, y, width, height);
2183 NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2184 NSPoint dstOrigin = dstRect.origin;
2186 NSTRACE (ns_shift_glyphs_for_insert);
2188 ns_focus (f, &dstRect, 1);
2189 NSCopyBits (0, srcRect, dstOrigin);
2195 /* ==========================================================================
2197 Character encoding and metrics
2199 ========================================================================== */
2203 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2204 /* --------------------------------------------------------------------------
2205 External (RIF); compute left/right overhang of whole string and set in s
2206 -------------------------------------------------------------------------- */
2208 struct font *font = s->font;
2212 struct font_metrics metrics;
2213 unsigned int codes[2];
2214 codes[0] = *(s->char2b);
2215 codes[1] = *(s->char2b + s->nchars - 1);
2217 font->driver->text_extents (font, codes, 2, &metrics);
2218 s->left_overhang = -metrics.lbearing;
2220 = metrics.rbearing > metrics.width
2221 ? metrics.rbearing - metrics.width : 0;
2225 s->left_overhang = 0;
2226 s->right_overhang = ((struct nsfont_info *)font)->ital ?
2227 FONT_HEIGHT (font) * 0.2 : 0;
2233 /* ==========================================================================
2235 Fringe and cursor drawing
2237 ========================================================================== */
2240 extern int max_used_fringe_bitmap;
2242 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2243 struct draw_fringe_bitmap_params *p)
2244 /* --------------------------------------------------------------------------
2245 External (RIF); fringe-related
2246 -------------------------------------------------------------------------- */
2248 struct frame *f = XFRAME (WINDOW_FRAME (w));
2249 struct face *face = p->face;
2251 static EmacsImage **bimgs = NULL;
2252 static int nBimgs = 0;
2254 /* grow bimgs if needed */
2255 if (nBimgs < max_used_fringe_bitmap)
2257 bimgs = xrealloc (bimgs, max_used_fringe_bitmap * sizeof *bimgs);
2258 memset (bimgs + nBimgs, 0,
2259 (max_used_fringe_bitmap - nBimgs) * sizeof *bimgs);
2260 nBimgs = max_used_fringe_bitmap;
2263 /* Must clip because of partially visible lines. */
2264 rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
2265 ns_clip_to_row (w, row, -1, YES);
2269 int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
2271 /* If the fringe is adjacent to the left (right) scroll bar of a
2272 leftmost (rightmost, respectively) window, then extend its
2273 background to the gap between the fringe and the bar. */
2274 if ((WINDOW_LEFTMOST_P (w)
2275 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
2276 || (WINDOW_RIGHTMOST_P (w)
2277 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w)))
2279 int sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
2283 int bar_area_x = WINDOW_SCROLL_BAR_AREA_X (w);
2284 int bar_area_width = (WINDOW_CONFIG_SCROLL_BAR_COLS (w)
2285 * FRAME_COLUMN_WIDTH (f));
2289 /* Bitmap fills the fringe. */
2290 if (bar_area_x + bar_area_width == p->x)
2291 bx = bar_area_x + sb_width;
2292 else if (p->x + p->wd == bar_area_x)
2296 int header_line_height = WINDOW_HEADER_LINE_HEIGHT (w);
2298 nx = bar_area_width - sb_width;
2299 by = WINDOW_TO_FRAME_PIXEL_Y (w, max (header_line_height,
2301 ny = row->visible_height;
2306 if (bar_area_x + bar_area_width == bx)
2308 bx = bar_area_x + sb_width;
2309 nx += bar_area_width - sb_width;
2311 else if (bx + nx == bar_area_x)
2312 nx += bar_area_width - sb_width;
2317 if (bx >= 0 && nx > 0)
2319 NSRect r = NSMakeRect (bx, by, nx, ny);
2321 [ns_lookup_indexed_color (face->background, f) set];
2328 NSRect r = NSMakeRect (p->x, p->y, p->wd, p->h);
2329 EmacsImage *img = bimgs[p->which - 1];
2333 unsigned short *bits = p->bits + p->dh;
2336 unsigned char *cbits = xmalloc (len);
2338 for (i = 0; i < len; i++)
2339 cbits[i] = ~(bits[i] & 0xff);
2340 img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2342 bimgs[p->which - 1] = img;
2347 /* Since we composite the bitmap instead of just blitting it, we need
2348 to erase the whole background. */
2349 [ns_lookup_indexed_color(face->background, f) set];
2351 [img setXBMColor: ns_lookup_indexed_color(face->foreground, f)];
2352 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
2354 fromRect: NSZeroRect
2355 operation: NSCompositeSourceOver
2361 NSPoint pt = r.origin;
2363 [img compositeToPoint: pt operation: NSCompositeSourceOver];
2372 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2373 int x, int y, int cursor_type, int cursor_width,
2374 int on_p, int active_p)
2375 /* --------------------------------------------------------------------------
2376 External call (RIF): draw cursor.
2377 Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2378 -------------------------------------------------------------------------- */
2381 int fx, fy, h, cursor_height;
2382 struct frame *f = WINDOW_XFRAME (w);
2383 struct glyph *phys_cursor_glyph;
2385 struct glyph *cursor_glyph;
2387 NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2389 /* If cursor is out of bounds, don't draw garbage. This can happen
2390 in mini-buffer windows when switching between echo area glyphs
2393 NSTRACE (dumpcursor);
2398 w->phys_cursor_type = cursor_type;
2399 w->phys_cursor_on_p = on_p;
2401 if (cursor_type == NO_CURSOR)
2403 w->phys_cursor_width = 0;
2407 if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2409 if (glyph_row->exact_window_width_line_p
2410 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2412 glyph_row->cursor_in_fringe_p = 1;
2413 draw_fringe_bitmap (w, glyph_row, 0);
2418 /* We draw the cursor (with NSRectFill), then draw the glyph on top
2419 (other terminals do it the other way round). We must set
2420 w->phys_cursor_width to the cursor width. For bar cursors, that
2421 is CURSOR_WIDTH; for box cursors, it is the glyph width. */
2422 get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2424 /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2425 to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2426 if (cursor_type == BAR_CURSOR)
2428 if (cursor_width < 1)
2429 cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2430 w->phys_cursor_width = cursor_width;
2432 /* If we have an HBAR, "cursor_width" MAY specify height. */
2433 else if (cursor_type == HBAR_CURSOR)
2435 cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2436 fy += h - cursor_height;
2440 r.origin.x = fx, r.origin.y = fy;
2442 r.size.width = w->phys_cursor_width;
2444 /* TODO: only needed in rare cases with last-resort font in HELLO..
2445 should we do this more efficiently? */
2446 ns_clip_to_row (w, glyph_row, -1, NO); /* do ns_focus(f, &r, 1); if remove */
2449 face = FACE_FROM_ID (f, phys_cursor_glyph->face_id);
2450 if (face && NS_FACE_BACKGROUND (face)
2451 == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2453 [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2454 hollow_color = FRAME_CURSOR_COLOR (f);
2457 [FRAME_CURSOR_COLOR (f) set];
2459 #ifdef NS_IMPL_COCOA
2460 /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2461 atomic. Cleaner ways of doing this should be investigated.
2462 One way would be to set a global variable DRAWING_CURSOR
2463 when making the call to draw_phys..(), don't focus in that
2464 case, then move the ns_unfocus() here after that call. */
2465 NSDisableScreenUpdates ();
2468 switch (cursor_type)
2472 case FILLED_BOX_CURSOR:
2475 case HOLLOW_BOX_CURSOR:
2478 NSRectFill (NSInsetRect (r, 1, 1));
2479 [FRAME_CURSOR_COLOR (f) set];
2486 /* If the character under cursor is R2L, draw the bar cursor
2487 on the right of its glyph, rather than on the left. */
2488 cursor_glyph = get_phys_cursor_glyph (w);
2489 if ((cursor_glyph->resolved_level & 1) != 0)
2490 s.origin.x += cursor_glyph->pixel_width - s.size.width;
2497 /* draw the character under the cursor */
2498 if (cursor_type != NO_CURSOR)
2499 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2501 #ifdef NS_IMPL_COCOA
2502 NSEnableScreenUpdates ();
2509 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2510 /* --------------------------------------------------------------------------
2511 External (RIF): Draw a vertical line.
2512 -------------------------------------------------------------------------- */
2514 struct frame *f = XFRAME (WINDOW_FRAME (w));
2516 NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2518 NSTRACE (ns_draw_vertical_window_border);
2520 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2522 [ns_lookup_indexed_color(face->foreground, f) set];
2524 ns_focus (f, &r, 1);
2531 show_hourglass (struct atimer *timer)
2533 if (hourglass_shown_p)
2538 /* TODO: add NSProgressIndicator to selected frame (see macfns.c) */
2540 hourglass_shown_p = 1;
2546 hide_hourglass (void)
2548 if (!hourglass_shown_p)
2553 /* TODO: remove NSProgressIndicator from all frames */
2555 hourglass_shown_p = 0;
2561 /* ==========================================================================
2563 Glyph drawing operations
2565 ========================================================================== */
2568 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2569 /* --------------------------------------------------------------------------
2570 Wrapper utility to account for internal border width on full-width lines,
2571 and allow top full-width rows to hit the frame top. nr should be pointer
2572 to two successive NSRects. Number of rects actually used is returned.
2573 -------------------------------------------------------------------------- */
2575 int n = get_glyph_string_clip_rects (s, nr, 2);
2579 /* --------------------------------------------------------------------
2580 Draw a wavy line under glyph string s. The wave fills wave_height
2587 wave_height = 3 | * * * *
2588 --------------------------------------------------------------------- */
2591 ns_draw_underwave (struct glyph_string *s, CGFloat width, CGFloat x)
2593 int wave_height = 3, wave_length = 2;
2594 int y, dx, dy, odd, xmax;
2599 dy = wave_height - 1;
2600 y = s->ybase - wave_height + 3;
2603 /* Find and set clipping rectangle */
2604 waveClip = NSMakeRect (x, y, width, wave_height);
2605 [[NSGraphicsContext currentContext] saveGraphicsState];
2606 NSRectClip (waveClip);
2608 /* Draw the waves */
2609 a.x = x - ((int)(x) % dx) + 0.5;
2611 odd = (int)(a.x/dx) % 2;
2612 a.y = b.y = y + 0.5;
2621 [NSBezierPath strokeLineFromPoint:a toPoint:b];
2622 a.x = b.x, a.y = b.y;
2623 b.x += dx, b.y = y + 0.5 + odd*dy;
2627 /* Restore previous clipping rectangle(s) */
2628 [[NSGraphicsContext currentContext] restoreGraphicsState];
2634 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
2635 NSColor *defaultCol, CGFloat width, CGFloat x)
2636 /* --------------------------------------------------------------------------
2637 Draw underline, overline, and strike-through on glyph string s.
2638 -------------------------------------------------------------------------- */
2640 if (s->for_overlaps)
2644 if (face->underline_p)
2646 if (s->face->underline_type == FACE_UNDER_WAVE)
2648 if (face->underline_defaulted_p)
2651 [ns_lookup_indexed_color (face->underline_color, s->f) set];
2653 ns_draw_underwave (s, width, x);
2655 else if (s->face->underline_type == FACE_UNDER_LINE)
2659 unsigned long thickness, position;
2661 /* If the prev was underlined, match its appearance. */
2662 if (s->prev && s->prev->face->underline_p
2663 && s->prev->face->underline_type == FACE_UNDER_LINE
2664 && s->prev->underline_thickness > 0)
2666 thickness = s->prev->underline_thickness;
2667 position = s->prev->underline_position;
2672 unsigned long descent;
2675 descent = s->y + s->height - s->ybase;
2677 /* Use underline thickness of font, defaulting to 1. */
2678 thickness = (font && font->underline_thickness > 0)
2679 ? font->underline_thickness : 1;
2681 /* Determine the offset of underlining from the baseline. */
2682 if (x_underline_at_descent_line)
2683 position = descent - thickness;
2684 else if (x_use_underline_position_properties
2685 && font && font->underline_position >= 0)
2686 position = font->underline_position;
2688 position = lround (font->descent / 2);
2690 position = underline_minimum_offset;
2692 position = max (position, underline_minimum_offset);
2694 /* Ensure underlining is not cropped. */
2695 if (descent <= position)
2697 position = descent - 1;
2700 else if (descent < position + thickness)
2704 s->underline_thickness = thickness;
2705 s->underline_position = position;
2707 r = NSMakeRect (x, s->ybase + position, width, thickness);
2709 if (face->underline_defaulted_p)
2712 [ns_lookup_indexed_color (face->underline_color, s->f) set];
2716 /* Do overline. We follow other terms in using a thickness of 1
2717 and ignoring overline_margin. */
2718 if (face->overline_p)
2721 r = NSMakeRect (x, s->y, width, 1);
2723 if (face->overline_color_defaulted_p)
2726 [ns_lookup_indexed_color (face->overline_color, s->f) set];
2730 /* Do strike-through. We follow other terms for thickness and
2731 vertical position.*/
2732 if (face->strike_through_p)
2737 dy = lrint ((s->height - 1) / 2);
2738 r = NSMakeRect (x, s->y + dy, width, 1);
2740 if (face->strike_through_color_defaulted_p)
2743 [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
2749 ns_draw_box (NSRect r, float thickness, NSColor *col, char left_p, char right_p)
2750 /* --------------------------------------------------------------------------
2751 Draw an unfilled rect inside r, optionally leaving left and/or right open.
2752 Note we can't just use an NSDrawRect command, because of the possibility
2753 of some sides not being drawn, and because the rect will be filled.
2754 -------------------------------------------------------------------------- */
2760 s.size.height = thickness;
2762 s.origin.y += r.size.height - thickness;
2765 s.size.height = r.size.height;
2766 s.origin.y = r.origin.y;
2768 /* left, right (optional) */
2769 s.size.width = thickness;
2774 s.origin.x += r.size.width - thickness;
2781 ns_draw_relief (NSRect r, int thickness, char raised_p,
2782 char top_p, char bottom_p, char left_p, char right_p,
2783 struct glyph_string *s)
2784 /* --------------------------------------------------------------------------
2785 Draw a relief rect inside r, optionally leaving some sides open.
2786 Note we can't just use an NSDrawBezel command, because of the possibility
2787 of some sides not being drawn, and because the rect will be filled.
2788 -------------------------------------------------------------------------- */
2790 static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2791 NSColor *newBaseCol = nil;
2794 NSTRACE (ns_draw_relief);
2798 if (s->face->use_box_color_for_shadows_p)
2800 newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2802 /* else if (s->first_glyph->type == IMAGE_GLYPH
2804 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2806 newBaseCol = IMAGE_BACKGROUND (s->img, s->f, 0);
2810 newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2813 if (newBaseCol == nil)
2814 newBaseCol = [NSColor grayColor];
2816 if (newBaseCol != baseCol) /* TODO: better check */
2819 baseCol = [newBaseCol retain];
2821 lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2823 darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2826 [(raised_p ? lightCol : darkCol) set];
2828 /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2831 sr.size.height = thickness;
2832 if (top_p) NSRectFill (sr);
2835 sr.size.height = r.size.height;
2836 sr.size.width = thickness;
2837 if (left_p) NSRectFill (sr);
2839 [(raised_p ? darkCol : lightCol) set];
2842 sr.size.width = r.size.width;
2843 sr.size.height = thickness;
2844 sr.origin.y += r.size.height - thickness;
2845 if (bottom_p) NSRectFill (sr);
2848 sr.size.height = r.size.height;
2849 sr.origin.y = r.origin.y;
2850 sr.size.width = thickness;
2851 sr.origin.x += r.size.width - thickness;
2852 if (right_p) NSRectFill (sr);
2857 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2858 /* --------------------------------------------------------------------------
2859 Function modeled after x_draw_glyph_string_box ().
2860 Sets up parameters for drawing.
2861 -------------------------------------------------------------------------- */
2863 int right_x, last_x;
2864 char left_p, right_p;
2865 struct glyph *last_glyph;
2870 if (s->hl == DRAW_MOUSE_FACE)
2872 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2874 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2879 thickness = face->box_line_width;
2881 NSTRACE (ns_dumpglyphs_box_or_relief);
2883 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2884 ? WINDOW_RIGHT_EDGE_X (s->w)
2885 : window_box_right (s->w, s->area));
2886 last_glyph = (s->cmp || s->img
2887 ? s->first_glyph : s->first_glyph + s->nchars-1);
2889 right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2890 ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2892 left_p = (s->first_glyph->left_box_line_p
2893 || (s->hl == DRAW_MOUSE_FACE
2894 && (s->prev == NULL || s->prev->hl != s->hl)));
2895 right_p = (last_glyph->right_box_line_p
2896 || (s->hl == DRAW_MOUSE_FACE
2897 && (s->next == NULL || s->next->hl != s->hl)));
2899 r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2901 /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
2902 if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
2904 ns_draw_box (r, abs (thickness),
2905 ns_lookup_indexed_color (face->box_color, s->f),
2910 ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2911 1, 1, left_p, right_p, s);
2917 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2918 /* --------------------------------------------------------------------------
2919 Modeled after x_draw_glyph_string_background, which draws BG in
2920 certain cases. Others are left to the text rendering routine.
2921 -------------------------------------------------------------------------- */
2923 NSTRACE (ns_maybe_dumpglyphs_background);
2925 if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2927 int box_line_width = max (s->face->box_line_width, 0);
2928 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2929 || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2932 if (s->hl == DRAW_MOUSE_FACE)
2934 face = FACE_FROM_ID (s->f,
2935 MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2937 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2940 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2942 [(NS_FACE_BACKGROUND (face) != 0
2943 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2944 : FRAME_BACKGROUND_COLOR (s->f)) set];
2947 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (s->f);
2948 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2951 if (s->hl != DRAW_CURSOR)
2953 NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2954 s->background_width,
2955 s->height-2*box_line_width);
2959 s->background_filled_p = 1;
2966 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2967 /* --------------------------------------------------------------------------
2968 Renders an image and associated borders.
2969 -------------------------------------------------------------------------- */
2971 EmacsImage *img = s->img->pixmap;
2972 int box_line_vwidth = max (s->face->box_line_width, 0);
2973 int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2974 int bg_x, bg_y, bg_height;
2981 NSTRACE (ns_dumpglyphs_image);
2983 if (s->face->box != FACE_NO_BOX
2984 && s->first_glyph->left_box_line_p && s->slice.x == 0)
2985 x += abs (s->face->box_line_width);
2988 bg_y = s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2989 bg_height = s->height;
2990 /* other terms have this, but was causing problems w/tabbar mode */
2991 /* - 2 * box_line_vwidth; */
2993 if (s->slice.x == 0) x += s->img->hmargin;
2994 if (s->slice.y == 0) y += s->img->vmargin;
2996 /* Draw BG: if we need larger area than image itself cleared, do that,
2997 otherwise, since we composite the image under NS (instead of mucking
2998 with its background color), we must clear just the image area. */
2999 if (s->hl == DRAW_MOUSE_FACE)
3001 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3003 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3006 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3008 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
3010 if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
3011 || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
3013 br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
3014 s->background_filled_p = 1;
3018 br = NSMakeRect (x, y, s->slice.width, s->slice.height);
3023 /* Draw the image.. do we need to draw placeholder if img ==nil? */
3026 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
3027 NSRect dr = NSMakeRect (x, y, s->slice.width, s->slice.height);
3028 NSRect ir = NSMakeRect (s->slice.x, s->slice.y,
3029 s->slice.width, s->slice.height);
3032 operation: NSCompositeSourceOver
3037 [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3038 operation: NSCompositeSourceOver];
3042 if (s->hl == DRAW_CURSOR)
3044 [FRAME_CURSOR_COLOR (s->f) set];
3045 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3046 tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3048 /* Currently on NS img->mask is always 0. Since
3049 get_window_cursor_type specifies a hollow box cursor when on
3050 a non-masked image we never reach this clause. But we put it
3051 in in anticipation of better support for image masks on
3053 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3057 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3060 /* Draw underline, overline, strike-through. */
3061 ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3063 /* Draw relief, if requested */
3064 if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3066 if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3068 th = tool_bar_button_relief >= 0 ?
3069 tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3070 raised_p = (s->hl == DRAW_IMAGE_RAISED);
3074 th = abs (s->img->relief);
3075 raised_p = (s->img->relief > 0);
3078 r.origin.x = x - th;
3079 r.origin.y = y - th;
3080 r.size.width = s->slice.width + 2*th-1;
3081 r.size.height = s->slice.height + 2*th-1;
3082 ns_draw_relief (r, th, raised_p,
3084 s->slice.y + s->slice.height == s->img->height,
3086 s->slice.x + s->slice.width == s->img->width, s);
3089 /* If there is no mask, the background won't be seen,
3090 so draw a rectangle on the image for the cursor.
3091 Do this for all images, getting transparency right is not reliable. */
3092 if (s->hl == DRAW_CURSOR)
3094 int thickness = abs (s->img->relief);
3095 if (thickness == 0) thickness = 1;
3096 ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3102 ns_dumpglyphs_stretch (struct glyph_string *s)
3107 NSColor *fgCol, *bgCol;
3109 if (!s->background_filled_p)
3111 n = ns_get_glyph_string_clip_rect (s, r);
3112 *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3114 ns_focus (s->f, r, n);
3116 if (s->hl == DRAW_MOUSE_FACE)
3118 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3120 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3123 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3125 bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3126 fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3128 for (i = 0; i < n; ++i)
3130 if (!s->row->full_width_p)
3132 int overrun, leftoverrun;
3134 /* truncate to avoid overwriting fringe and/or scrollbar */
3135 overrun = max (0, (s->x + s->background_width)
3136 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3137 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3138 r[i].size.width -= overrun;
3140 /* truncate to avoid overwriting to left of the window box */
3141 leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3142 + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3144 if (leftoverrun > 0)
3146 r[i].origin.x += leftoverrun;
3147 r[i].size.width -= leftoverrun;
3150 /* XXX: Try to work between problem where a stretch glyph on
3151 a partially-visible bottom row will clear part of the
3152 modeline, and another where list-buffers headers and similar
3153 rows erroneously have visible_height set to 0. Not sure
3154 where this is coming from as other terms seem not to show. */
3155 r[i].size.height = min (s->height, s->row->visible_height);
3160 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3161 overwriting cursor (usually when cursor on a tab) */
3162 if (s->hl == DRAW_CURSOR)
3167 width = s->w->phys_cursor_width;
3168 r[i].size.width -= width;
3169 r[i].origin.x += width;
3173 /* Draw overlining, etc. on the cursor. */
3174 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3175 ns_draw_text_decoration (s, face, bgCol, width, x);
3177 ns_draw_text_decoration (s, face, fgCol, width, x);
3184 /* Draw overlining, etc. on the stretch glyph (or the part
3185 of the stretch glyph after the cursor). */
3186 ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3190 s->background_filled_p = 1;
3196 ns_draw_glyph_string (struct glyph_string *s)
3197 /* --------------------------------------------------------------------------
3198 External (RIF): Main draw-text call.
3199 -------------------------------------------------------------------------- */
3201 /* TODO (optimize): focus for box and contents draw */
3204 char box_drawn_p = 0;
3206 NSTRACE (ns_draw_glyph_string);
3208 if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3211 struct glyph_string *next;
3213 for (width = 0, next = s->next;
3214 next && width < s->right_overhang;
3215 width += next->width, next = next->next)
3216 if (next->first_glyph->type != IMAGE_GLYPH)
3218 if (next->first_glyph->type != STRETCH_GLYPH)
3220 n = ns_get_glyph_string_clip_rect (s->next, r);
3221 ns_focus (s->f, r, n);
3222 ns_maybe_dumpglyphs_background (s->next, 1);
3227 ns_dumpglyphs_stretch (s->next);
3229 next->num_clips = 0;
3233 if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3234 && (s->first_glyph->type == CHAR_GLYPH
3235 || s->first_glyph->type == COMPOSITE_GLYPH))
3237 n = ns_get_glyph_string_clip_rect (s, r);
3238 ns_focus (s->f, r, n);
3239 ns_maybe_dumpglyphs_background (s, 1);
3240 ns_dumpglyphs_box_or_relief (s);
3245 switch (s->first_glyph->type)
3249 n = ns_get_glyph_string_clip_rect (s, r);
3250 ns_focus (s->f, r, n);
3251 ns_dumpglyphs_image (s, r[0]);
3256 ns_dumpglyphs_stretch (s);
3260 case COMPOSITE_GLYPH:
3261 n = ns_get_glyph_string_clip_rect (s, r);
3262 ns_focus (s->f, r, n);
3264 if (s->for_overlaps || (s->cmp_from > 0
3265 && ! s->first_glyph->u.cmp.automatic))
3266 s->background_filled_p = 1;
3268 ns_maybe_dumpglyphs_background
3269 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3271 ns_tmp_flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3272 (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3273 (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3274 NS_DUMPGLYPH_NORMAL));
3275 ns_tmp_font = (struct nsfont_info *)s->face->font;
3276 if (ns_tmp_font == NULL)
3277 ns_tmp_font = (struct nsfont_info *)FRAME_FONT (s->f);
3279 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3281 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3282 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3283 NS_FACE_FOREGROUND (s->face) = tmp;
3286 ns_tmp_font->font.driver->draw
3287 (s, 0, s->nchars, s->x, s->y,
3288 (ns_tmp_flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3289 || ns_tmp_flags == NS_DUMPGLYPH_MOUSEFACE);
3291 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3293 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3294 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3295 NS_FACE_FOREGROUND (s->face) = tmp;
3301 case GLYPHLESS_GLYPH:
3302 n = ns_get_glyph_string_clip_rect (s, r);
3303 ns_focus (s->f, r, n);
3305 if (s->for_overlaps || (s->cmp_from > 0
3306 && ! s->first_glyph->u.cmp.automatic))
3307 s->background_filled_p = 1;
3309 ns_maybe_dumpglyphs_background
3310 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3312 /* Not yet implemented. */
3321 /* Draw box if not done already. */
3322 if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3324 n = ns_get_glyph_string_clip_rect (s, r);
3325 ns_focus (s->f, r, n);
3326 ns_dumpglyphs_box_or_relief (s);
3335 /* ==========================================================================
3339 ========================================================================== */
3343 ns_send_appdefined (int value)
3344 /* --------------------------------------------------------------------------
3345 Internal: post an appdefined event which EmacsApp-sendEvent will
3346 recognize and take as a command to halt the event loop.
3347 -------------------------------------------------------------------------- */
3349 /*NSTRACE (ns_send_appdefined); */
3351 /* Only post this event if we haven't already posted one. This will end
3352 the [NXApp run] main loop after having processed all events queued at
3354 if (send_appdefined)
3358 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
3359 send_appdefined = NO;
3361 /* Don't need wakeup timer any more */
3364 [timed_entry invalidate];
3365 [timed_entry release];
3369 nxev = [NSEvent otherEventWithType: NSApplicationDefined
3370 location: NSMakePoint (0, 0)
3373 windowNumber: [[NSApp mainWindow] windowNumber]
3374 context: [NSApp context]
3379 /* Post an application defined event on the event queue. When this is
3380 received the [NXApp run] will return, thus having processed all
3381 events which are currently queued. */
3382 [NSApp postEvent: nxev atStart: NO];
3386 #ifdef HAVE_NATIVE_FS
3390 Lisp_Object frame, tail;
3392 if (ns_last_use_native_fullscreen == ns_use_native_fullscreen)
3395 ns_last_use_native_fullscreen = ns_use_native_fullscreen;
3397 /* Clear the mouse-moved flag for every frame on this display. */
3398 FOR_EACH_FRAME (tail, frame)
3400 struct frame *f = XFRAME (frame);
3403 EmacsView *view = FRAME_NS_VIEW (f);
3404 [view updateCollectionBehaviour];
3411 ns_get_pending_menu_title ()
3413 return menu_pending_title;
3416 /* Check if menu open should be cancelled or continued as normal. */
3418 ns_check_menu_open (NSMenu *menu)
3420 /* GNUStep and OSX <= 10.4 does not have cancelTracking. */
3421 #if defined(NS_IMPL_COCOA) && \
3422 MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
3424 /* Click in menu bar? */
3425 NSArray *a = [[NSApp mainMenu] itemArray];
3428 for (i = 0; ! found && i < [a count]; i++)
3429 found = menu == [[a objectAtIndex:i] submenu];
3432 if (menu_will_open_state == MENU_NONE && emacs_event)
3434 NSEvent *theEvent = [NSApp currentEvent];
3435 struct frame *emacsframe = SELECTED_FRAME ();
3437 [menu cancelTracking];
3438 menu_will_open_state = MENU_PENDING;
3439 emacs_event->kind = MENU_BAR_ACTIVATE_EVENT;
3440 EV_TRAILER (theEvent);
3442 CGEventRef ourEvent = CGEventCreate (NULL);
3443 menu_mouse_point = CGEventGetLocation (ourEvent);
3444 CFRelease (ourEvent);
3445 xfree (menu_pending_title);
3446 menu_pending_title = xstrdup ([[menu title] UTF8String]);
3448 else if (menu_will_open_state == MENU_OPENING)
3450 menu_will_open_state = MENU_NONE;
3456 /* Redo saved menu click if state is MENU_PENDING. */
3458 ns_check_pending_open_menu ()
3460 #ifdef NS_IMPL_COCOA
3461 if (menu_will_open_state == MENU_PENDING)
3463 CGEventSourceRef source
3464 = CGEventSourceCreate (kCGEventSourceStateHIDSystemState);
3466 CGEventRef event = CGEventCreateMouseEvent (source,
3467 kCGEventLeftMouseDown,
3469 kCGMouseButtonLeft);
3470 CGEventSetType (event, kCGEventLeftMouseDown);
3471 CGEventPost (kCGHIDEventTap, event);
3475 menu_will_open_state = MENU_OPENING;
3482 ns_read_socket (struct terminal *terminal, struct input_event *hold_quit)
3483 /* --------------------------------------------------------------------------
3484 External (hook): Post an event to ourself and keep reading events until
3485 we read it back again. In effect process all events which were waiting.
3486 From 21+ we have to manage the event buffer ourselves.
3487 -------------------------------------------------------------------------- */
3489 struct input_event ev;
3492 /* NSTRACE (ns_read_socket); */
3494 #ifdef HAVE_NATIVE_FS
3498 if ([NSApp modalWindow] != nil)
3501 if (hold_event_q.nr > 0)
3504 for (i = 0; i < hold_event_q.nr; ++i)
3505 kbd_buffer_store_event_hold (&hold_event_q.q[i], hold_quit);
3506 hold_event_q.nr = 0;
3511 n_emacs_events_pending = 0;
3514 q_event_ptr = hold_quit;
3516 /* we manage autorelease pools by allocate/reallocate each time around
3517 the loop; strict nesting is occasionally violated but seems not to
3518 matter.. earlier methods using full nesting caused major memory leaks */
3519 [outerpool release];
3520 outerpool = [[NSAutoreleasePool alloc] init];
3522 /* If have pending open-file requests, attend to the next one of those. */
3523 if (ns_pending_files && [ns_pending_files count] != 0
3524 && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3526 [ns_pending_files removeObjectAtIndex: 0];
3528 /* Deal with pending service requests. */
3529 else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3531 NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3532 withArg: [ns_pending_service_args objectAtIndex: 0]])
3534 [ns_pending_service_names removeObjectAtIndex: 0];
3535 [ns_pending_service_args removeObjectAtIndex: 0];
3539 /* Run and wait for events. We must always send one NX_APPDEFINED event
3540 to ourself, otherwise [NXApp run] will never exit. */
3541 send_appdefined = YES;
3542 ns_send_appdefined (-1);
3544 if (++apploopnr != 1)
3552 nevents = n_emacs_events_pending;
3553 n_emacs_events_pending = 0;
3554 emacs_event = q_event_ptr = NULL;
3562 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3563 fd_set *exceptfds, EMACS_TIME *timeout, sigset_t *sigmask)
3564 /* --------------------------------------------------------------------------
3565 Replacement for select, checking for events
3566 -------------------------------------------------------------------------- */
3570 struct input_event event;
3573 /* NSTRACE (ns_select); */
3575 #ifdef HAVE_NATIVE_FS
3579 if (hold_event_q.nr > 0)
3581 /* We already have events pending. */
3587 for (k = 0; k < nfds+1; k++)
3589 if (readfds && FD_ISSET(k, readfds)) ++nr;
3590 if (writefds && FD_ISSET(k, writefds)) ++nr;
3594 || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0))
3595 return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
3597 [outerpool release];
3598 outerpool = [[NSAutoreleasePool alloc] init];
3601 send_appdefined = YES;
3604 pthread_mutex_lock (&select_mutex);
3609 select_readfds = *readfds;
3610 select_valid += SELECT_HAVE_READ;
3614 select_writefds = *writefds;
3615 select_valid += SELECT_HAVE_WRITE;
3620 select_timeout = *timeout;
3621 select_valid += SELECT_HAVE_TMO;
3624 pthread_mutex_unlock (&select_mutex);
3626 /* Inform fd_handler that select should be called */
3628 emacs_write (selfds[1], &c, 1);
3630 else if (nr == 0 && timeout)
3632 /* No file descriptor, just a timeout, no need to wake fd_handler */
3633 double time = EMACS_TIME_TO_DOUBLE (*timeout);
3634 timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3637 @selector (timeout_handler:)
3642 else /* No timeout and no file descriptors, can this happen? */
3644 /* Send appdefined so we exit from the loop */
3645 ns_send_appdefined (-1);
3650 emacs_event = &event;
3651 if (++apploopnr != 1)
3658 if (nr > 0 && readfds)
3661 emacs_write (selfds[1], &c, 1);
3665 t = last_appdefined_event_data;
3667 if (t != NO_APPDEFINED_DATA)
3669 last_appdefined_event_data = NO_APPDEFINED_DATA;
3673 /* The NX_APPDEFINED event we received was a timeout. */
3678 /* The NX_APPDEFINED event we received was the result of
3679 at least one real input event arriving. */
3685 /* Received back from select () in fd_handler; copy the results */
3686 pthread_mutex_lock (&select_mutex);
3687 if (readfds) *readfds = select_readfds;
3688 if (writefds) *writefds = select_writefds;
3689 if (timeout) *timeout = select_timeout;
3690 pthread_mutex_unlock (&select_mutex);
3705 /* ==========================================================================
3709 ========================================================================== */
3713 ns_set_vertical_scroll_bar (struct window *window,
3714 int portion, int whole, int position)
3715 /* --------------------------------------------------------------------------
3716 External (hook): Update or add scrollbar
3717 -------------------------------------------------------------------------- */
3721 struct frame *f = XFRAME (WINDOW_FRAME (window));
3722 EmacsView *view = FRAME_NS_VIEW (f);
3723 int window_y, window_height;
3724 int top, left, height, width, sb_width, sb_left;
3726 BOOL fringe_extended_p;
3728 /* optimization; display engine sends WAY too many of these.. */
3729 if (!NILP (window->vertical_scroll_bar))
3731 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3732 if ([bar checkSamePosition: position portion: portion whole: whole])
3734 if (view->scrollbarsNeedingUpdate == 0)
3736 if (!windows_or_buffers_changed)
3740 view->scrollbarsNeedingUpdate--;
3744 NSTRACE (ns_set_vertical_scroll_bar);
3746 /* Get dimensions. */
3747 window_box (window, -1, 0, &window_y, 0, &window_height);
3749 height = window_height;
3750 width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3751 left = WINDOW_SCROLL_BAR_AREA_X (window);
3753 /* allow for displaying a skinnier scrollbar than char area allotted */
3754 sb_width = (WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) > 0) ?
3755 WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) : width;
3758 r = NSMakeRect (sb_left, top, sb_width, height);
3759 /* the parent view is flipped, so we need to flip y value */
3761 r.origin.y = (v.size.height - r.size.height - r.origin.y);
3763 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (window))
3764 fringe_extended_p = (WINDOW_LEFTMOST_P (window)
3765 && WINDOW_LEFT_FRINGE_WIDTH (window)
3766 && (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (window)
3767 || WINDOW_LEFT_MARGIN_COLS (window) == 0));
3769 fringe_extended_p = (WINDOW_RIGHTMOST_P (window)
3770 && WINDOW_RIGHT_FRINGE_WIDTH (window)
3771 && (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (window)
3772 || WINDOW_RIGHT_MARGIN_COLS (window) == 0));
3774 XSETWINDOW (win, window);
3777 /* we want at least 5 lines to display a scrollbar */
3778 if (WINDOW_TOTAL_LINES (window) < 5)
3780 if (!NILP (window->vertical_scroll_bar))
3782 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3783 [bar removeFromSuperview];
3784 wset_vertical_scroll_bar (window, Qnil);
3786 ns_clear_frame_area (f, sb_left, top, width, height);
3791 if (NILP (window->vertical_scroll_bar))
3793 if (width > 0 && height > 0)
3795 if (fringe_extended_p)
3796 ns_clear_frame_area (f, sb_left, top, sb_width, height);
3798 ns_clear_frame_area (f, left, top, width, height);
3801 bar = [[EmacsScroller alloc] initFrame: r window: win];
3802 wset_vertical_scroll_bar (window, make_save_pointer (bar));
3807 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3808 oldRect = [bar frame];
3809 r.size.width = oldRect.size.width;
3810 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3812 if (oldRect.origin.x != r.origin.x)
3813 ns_clear_frame_area (f, sb_left, top, width, height);
3818 [bar setPosition: position portion: portion whole: whole];
3824 ns_condemn_scroll_bars (struct frame *f)
3825 /* --------------------------------------------------------------------------
3826 External (hook): arrange for all frame's scrollbars to be removed
3827 at next call to judge_scroll_bars, except for those redeemed.
3828 -------------------------------------------------------------------------- */
3832 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3834 NSTRACE (ns_condemn_scroll_bars);
3836 for (i =[subviews count]-1; i >= 0; i--)
3838 view = [subviews objectAtIndex: i];
3839 if ([view isKindOfClass: [EmacsScroller class]])
3846 ns_redeem_scroll_bar (struct window *window)
3847 /* --------------------------------------------------------------------------
3848 External (hook): arrange to spare this window's scrollbar
3849 at next call to judge_scroll_bars.
3850 -------------------------------------------------------------------------- */
3853 NSTRACE (ns_redeem_scroll_bar);
3854 if (!NILP (window->vertical_scroll_bar))
3856 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3863 ns_judge_scroll_bars (struct frame *f)
3864 /* --------------------------------------------------------------------------
3865 External (hook): destroy all scrollbars on frame that weren't
3866 redeemed after call to condemn_scroll_bars.
3867 -------------------------------------------------------------------------- */
3871 EmacsView *eview = FRAME_NS_VIEW (f);
3872 NSArray *subviews = [[eview superview] subviews];
3875 NSTRACE (ns_judge_scroll_bars);
3876 for (i = [subviews count]-1; i >= 0; --i)
3878 view = [subviews objectAtIndex: i];
3879 if (![view isKindOfClass: [EmacsScroller class]]) continue;
3885 [eview updateFrameSize: NO];
3890 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
3892 /* XXX irrelevant under NS */
3897 /* ==========================================================================
3901 ========================================================================== */
3904 x_display_pixel_height (struct ns_display_info *dpyinfo)
3906 NSScreen *screen = [NSScreen mainScreen];
3907 return [screen frame].size.height;
3911 x_display_pixel_width (struct ns_display_info *dpyinfo)
3913 NSScreen *screen = [NSScreen mainScreen];
3914 return [screen frame].size.width;
3918 static Lisp_Object ns_string_to_lispmod (const char *s)
3919 /* --------------------------------------------------------------------------
3920 Convert modifier name to lisp symbol
3921 -------------------------------------------------------------------------- */
3923 if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
3925 else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
3927 else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
3929 else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
3931 else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
3933 else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
3941 ns_default (const char *parameter, Lisp_Object *result,
3942 Lisp_Object yesval, Lisp_Object noval,
3943 BOOL is_float, BOOL is_modstring)
3944 /* --------------------------------------------------------------------------
3945 Check a parameter value in user's preferences
3946 -------------------------------------------------------------------------- */
3948 const char *value = ns_get_defaults_value (parameter);
3954 if (c_strcasecmp (value, "YES") == 0)
3956 else if (c_strcasecmp (value, "NO") == 0)
3958 else if (is_float && (f = strtod (value, &pos), pos != value))
3959 *result = make_float (f);
3960 else if (is_modstring && value)
3961 *result = ns_string_to_lispmod (value);
3962 else fprintf (stderr,
3963 "Bad value for default \"%s\": \"%s\"\n", parameter, value);
3969 ns_initialize_display_info (struct ns_display_info *dpyinfo)
3970 /* --------------------------------------------------------------------------
3971 Initialize global info and storage for display.
3972 -------------------------------------------------------------------------- */
3974 NSScreen *screen = [NSScreen mainScreen];
3975 NSWindowDepth depth = [screen depth];
3976 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
3978 dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
3979 dpyinfo->resy = 72.27;
3980 dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
3981 NSColorSpaceFromDepth (depth)]
3982 && ![NSCalibratedWhiteColorSpace isEqualToString:
3983 NSColorSpaceFromDepth (depth)];
3984 dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
3985 dpyinfo->image_cache = make_image_cache ();
3986 dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
3987 dpyinfo->color_table->colors = NULL;
3988 dpyinfo->root_window = 42; /* a placeholder.. */
3990 hlinfo->mouse_face_mouse_frame = NULL;
3991 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
3992 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
3993 hlinfo->mouse_face_face_id = DEFAULT_FACE_ID;
3994 hlinfo->mouse_face_window = hlinfo->mouse_face_overlay = Qnil;
3995 hlinfo->mouse_face_hidden = 0;
3997 hlinfo->mouse_face_mouse_x = hlinfo->mouse_face_mouse_y = 0;
3998 hlinfo->mouse_face_defer = 0;
4000 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
4002 dpyinfo->n_fonts = 0;
4003 dpyinfo->smallest_font_height = 1;
4004 dpyinfo->smallest_char_width = 1;
4008 /* This and next define (many of the) public functions in this file. */
4009 /* x_... are generic versions in xdisp.c that we, and other terms, get away
4010 with using despite presence in the "system dependent" redisplay
4011 interface. In addition, many of the ns_ methods have code that is
4012 shared with all terms, indicating need for further refactoring. */
4013 extern frame_parm_handler ns_frame_parm_handlers[];
4014 static struct redisplay_interface ns_redisplay_interface =
4016 ns_frame_parm_handlers,
4020 x_clear_end_of_line,
4022 ns_after_update_window_line,
4023 ns_update_window_begin,
4024 ns_update_window_end,
4027 0, /* flush_display_optional */
4028 x_clear_window_mouse_face,
4029 x_get_glyph_overhangs,
4030 x_fix_overlapping_area,
4031 ns_draw_fringe_bitmap,
4032 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
4033 0, /* destroy_fringe_bitmap */
4034 ns_compute_glyph_string_overhangs,
4035 ns_draw_glyph_string, /* interface to nsfont.m */
4036 ns_define_frame_cursor,
4037 ns_clear_frame_area,
4038 ns_draw_window_cursor,
4039 ns_draw_vertical_window_border,
4040 ns_shift_glyphs_for_insert
4045 ns_delete_display (struct ns_display_info *dpyinfo)
4051 /* This function is called when the last frame on a display is deleted. */
4053 ns_delete_terminal (struct terminal *terminal)
4055 struct ns_display_info *dpyinfo = terminal->display_info.ns;
4057 /* Protect against recursive calls. delete_frame in
4058 delete_terminal calls us back when it deletes our last frame. */
4059 if (!terminal->name)
4064 x_destroy_all_bitmaps (dpyinfo);
4065 ns_delete_display (dpyinfo);
4070 static struct terminal *
4071 ns_create_terminal (struct ns_display_info *dpyinfo)
4072 /* --------------------------------------------------------------------------
4073 Set up use of NS before we make the first connection.
4074 -------------------------------------------------------------------------- */
4076 struct terminal *terminal;
4078 NSTRACE (ns_create_terminal);
4080 terminal = create_terminal ();
4082 terminal->type = output_ns;
4083 terminal->display_info.ns = dpyinfo;
4084 dpyinfo->terminal = terminal;
4086 terminal->rif = &ns_redisplay_interface;
4088 terminal->clear_frame_hook = ns_clear_frame;
4089 terminal->ins_del_lines_hook = 0; /* XXX vestigial? */
4090 terminal->delete_glyphs_hook = 0; /* XXX vestigial? */
4091 terminal->ring_bell_hook = ns_ring_bell;
4092 terminal->reset_terminal_modes_hook = ns_reset_terminal_modes;
4093 terminal->set_terminal_modes_hook = ns_set_terminal_modes;
4094 terminal->update_begin_hook = ns_update_begin;
4095 terminal->update_end_hook = ns_update_end;
4096 terminal->set_terminal_window_hook = NULL; /* XXX vestigial? */
4097 terminal->read_socket_hook = ns_read_socket;
4098 terminal->frame_up_to_date_hook = ns_frame_up_to_date;
4099 terminal->mouse_position_hook = ns_mouse_position;
4100 terminal->frame_rehighlight_hook = ns_frame_rehighlight;
4101 terminal->frame_raise_lower_hook = ns_frame_raise_lower;
4103 terminal->fullscreen_hook = ns_fullscreen_hook;
4105 terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
4106 terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
4107 terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
4108 terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
4110 terminal->delete_frame_hook = x_destroy_window;
4111 terminal->delete_terminal_hook = ns_delete_terminal;
4113 terminal->scroll_region_ok = 1;
4114 terminal->char_ins_del_ok = 1;
4115 terminal->line_ins_del_ok = 1;
4116 terminal->fast_clear_end_of_line = 1;
4117 terminal->memory_below_frame = 0;
4123 struct ns_display_info *
4124 ns_term_init (Lisp_Object display_name)
4125 /* --------------------------------------------------------------------------
4126 Start the Application and get things rolling.
4127 -------------------------------------------------------------------------- */
4129 struct terminal *terminal;
4130 struct ns_display_info *dpyinfo;
4131 static int ns_initialized = 0;
4134 if (ns_initialized) return x_display_list;
4137 NSTRACE (ns_term_init);
4139 [outerpool release];
4140 outerpool = [[NSAutoreleasePool alloc] init];
4142 /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4143 /*GSDebugAllocationActive (YES); */
4147 Fset_input_interrupt_mode (Qnil);
4149 if (selfds[0] == -1)
4151 if (pipe (selfds) == -1)
4153 fprintf (stderr, "Failed to create pipe: %s\n",
4154 emacs_strerror (errno));
4158 fcntl (selfds[0], F_SETFL, O_NONBLOCK|fcntl (selfds[0], F_GETFL));
4159 FD_ZERO (&select_readfds);
4160 FD_ZERO (&select_writefds);
4161 pthread_mutex_init (&select_mutex, NULL);
4164 ns_pending_files = [[NSMutableArray alloc] init];
4165 ns_pending_service_names = [[NSMutableArray alloc] init];
4166 ns_pending_service_args = [[NSMutableArray alloc] init];
4168 /* Start app and create the main menu, window, view.
4169 Needs to be here because ns_initialize_display_info () uses AppKit classes.
4170 The view will then ask the NSApp to stop and return to Emacs. */
4171 [EmacsApp sharedApplication];
4174 [NSApp setDelegate: NSApp];
4176 /* Start the select thread. */
4177 [NSThread detachNewThreadSelector:@selector (fd_handler:)
4181 /* debugging: log all notifications */
4182 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
4183 selector: @selector (logNotification:)
4184 name: nil object: nil]; */
4186 dpyinfo = xzalloc (sizeof *dpyinfo);
4188 ns_initialize_display_info (dpyinfo);
4189 terminal = ns_create_terminal (dpyinfo);
4191 terminal->kboard = xmalloc (sizeof *terminal->kboard);
4192 init_kboard (terminal->kboard);
4193 kset_window_system (terminal->kboard, Qns);
4194 terminal->kboard->next_kboard = all_kboards;
4195 all_kboards = terminal->kboard;
4196 /* Don't let the initial kboard remain current longer than necessary.
4197 That would cause problems if a file loaded on startup tries to
4198 prompt in the mini-buffer. */
4199 if (current_kboard == initial_kboard)
4200 current_kboard = terminal->kboard;
4201 terminal->kboard->reference_count++;
4203 dpyinfo->next = x_display_list;
4204 x_display_list = dpyinfo;
4206 /* Put it on ns_display_name_list */
4207 ns_display_name_list = Fcons (Fcons (display_name, Qnil),
4208 ns_display_name_list);
4209 dpyinfo->name_list_element = XCAR (ns_display_name_list);
4211 terminal->name = xstrdup (SSDATA (display_name));
4215 if (!inhibit_x_resources)
4217 ns_default ("GSFontAntiAlias", &ns_antialias_text,
4220 /* this is a standard variable */
4221 ns_default ("AppleAntiAliasingThreshold", &tmp,
4222 make_float (10.0), make_float (6.0), YES, NO);
4223 ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4226 ns_selection_color = [[NSUserDefaults standardUserDefaults]
4227 stringForKey: @"AppleHighlightColor"];
4228 if (ns_selection_color == nil)
4229 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
4232 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4236 Lisp_Object color_file, color_map, color;
4240 color_file = Fexpand_file_name (build_string ("rgb.txt"),
4241 Fsymbol_value (intern ("data-directory")));
4243 color_map = Fx_load_color_file (color_file);
4244 if (NILP (color_map))
4245 fatal ("Could not read %s.\n", SDATA (color_file));
4247 cl = [[NSColorList alloc] initWithName: @"Emacs"];
4248 for ( ; CONSP (color_map); color_map = XCDR (color_map))
4250 color = XCAR (color_map);
4251 name = SSDATA (XCAR (color));
4252 c = XINT (XCDR (color));
4254 [NSColor colorWithCalibratedRed: RED_FROM_ULONG (c) / 255.0
4255 green: GREEN_FROM_ULONG (c) / 255.0
4256 blue: BLUE_FROM_ULONG (c) / 255.0
4258 forKey: [NSString stringWithUTF8String: name]];
4260 [cl writeToFile: nil];
4265 #ifdef NS_IMPL_GNUSTEP
4266 Vwindow_system_version = build_string (gnustep_base_version);
4268 /*PSnextrelease (128, c); */
4269 char c[DBL_BUFSIZE_BOUND];
4270 int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4271 Vwindow_system_version = make_unibyte_string (c, len);
4275 delete_keyboard_wait_descriptor (0);
4277 ns_app_name = [[NSProcessInfo processInfo] processName];
4279 /* Set up OS X app menu */
4280 #ifdef NS_IMPL_COCOA
4284 /* set up the application menu */
4285 svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4286 [svcsMenu setAutoenablesItems: NO];
4287 appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4288 [appMenu setAutoenablesItems: NO];
4289 mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4290 dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4292 [appMenu insertItemWithTitle: @"About Emacs"
4293 action: @selector (orderFrontStandardAboutPanel:)
4296 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4297 [appMenu insertItemWithTitle: @"Preferences..."
4298 action: @selector (showPreferencesWindow:)
4301 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4302 item = [appMenu insertItemWithTitle: @"Services"
4303 action: @selector (menuDown:)
4306 [appMenu setSubmenu: svcsMenu forItem: item];
4307 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4308 [appMenu insertItemWithTitle: @"Hide Emacs"
4309 action: @selector (hide:)
4312 item = [appMenu insertItemWithTitle: @"Hide Others"
4313 action: @selector (hideOtherApplications:)
4316 [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4317 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4318 [appMenu insertItemWithTitle: @"Quit Emacs"
4319 action: @selector (terminate:)
4323 item = [mainMenu insertItemWithTitle: ns_app_name
4324 action: @selector (menuDown:)
4327 [mainMenu setSubmenu: appMenu forItem: item];
4328 [dockMenu insertItemWithTitle: @"New Frame"
4329 action: @selector (newFrame:)
4333 [NSApp setMainMenu: mainMenu];
4334 [NSApp setAppleMenu: appMenu];
4335 [NSApp setServicesMenu: svcsMenu];
4336 /* Needed at least on Cocoa, to get dock menu to show windows */
4337 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4339 [[NSNotificationCenter defaultCenter]
4340 addObserver: mainMenu
4341 selector: @selector (trackingNotification:)
4342 name: NSMenuDidBeginTrackingNotification object: mainMenu];
4343 [[NSNotificationCenter defaultCenter]
4344 addObserver: mainMenu
4345 selector: @selector (trackingNotification:)
4346 name: NSMenuDidEndTrackingNotification object: mainMenu];
4348 #endif /* MAC OS X menu setup */
4350 /* Register our external input/output types, used for determining
4351 applicable services and also drag/drop eligibility. */
4352 ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
4353 ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
4355 ns_drag_types = [[NSArray arrayWithObjects:
4357 NSTabularTextPboardType,
4358 NSFilenamesPboardType,
4361 NSFontPboardType, nil] retain];
4363 /* If fullscreen is in init/default-frame-alist, focus isn't set
4364 right for fullscreen windows, so set this. */
4365 [NSApp activateIgnoringOtherApps:YES];
4368 ns_do_open_file = YES;
4374 ns_term_shutdown (int sig)
4376 [[NSUserDefaults standardUserDefaults] synchronize];
4378 /* code not reached in emacs.c after this is called by shut_down_emacs: */
4379 if (STRINGP (Vauto_save_list_file_name))
4380 unlink (SSDATA (Vauto_save_list_file_name));
4382 if (sig == 0 || sig == SIGTERM)
4384 [NSApp terminate: NSApp];
4386 else // force a stack trace to happen
4393 /* ==========================================================================
4395 EmacsApp implementation
4397 ========================================================================== */
4400 @implementation EmacsApp
4402 - (void)logNotification: (NSNotification *)notification
4404 const char *name = [[notification name] UTF8String];
4405 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4406 && !strstr (name, "WindowNumber"))
4407 NSLog (@"notification: '%@'", [notification name]);
4411 - (void)sendEvent: (NSEvent *)theEvent
4412 /* --------------------------------------------------------------------------
4413 Called when NSApp is running for each event received. Used to stop
4414 the loop when we choose, since there's no way to just run one iteration.
4415 -------------------------------------------------------------------------- */
4417 int type = [theEvent type];
4418 NSWindow *window = [theEvent window];
4419 /* NSTRACE (sendEvent); */
4420 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4422 #ifdef NS_IMPL_COCOA
4423 if (type == NSApplicationDefined
4424 && [theEvent data2] == NSAPP_DATA2_RUNASSCRIPT)
4432 if (type == NSCursorUpdate && window == nil)
4434 fprintf (stderr, "Dropping external cursor update event.\n");
4438 if (type == NSApplicationDefined)
4440 /* Events posted by ns_send_appdefined interrupt the run loop here.
4441 But, if a modal window is up, an appdefined can still come through,
4442 (e.g., from a makeKeyWindow event) but stopping self also stops the
4443 modal loop. Just defer it until later. */
4444 if ([NSApp modalWindow] == nil)
4446 last_appdefined_event_data = [theEvent data1];
4451 send_appdefined = YES;
4455 [super sendEvent: theEvent];
4459 - (void)showPreferencesWindow: (id)sender
4461 struct frame *emacsframe = SELECTED_FRAME ();
4462 NSEvent *theEvent = [NSApp currentEvent];
4466 emacs_event->kind = NS_NONKEY_EVENT;
4467 emacs_event->code = KEY_NS_SHOW_PREFS;
4468 emacs_event->modifiers = 0;
4469 EV_TRAILER (theEvent);
4473 - (void)newFrame: (id)sender
4475 struct frame *emacsframe = SELECTED_FRAME ();
4476 NSEvent *theEvent = [NSApp currentEvent];
4480 emacs_event->kind = NS_NONKEY_EVENT;
4481 emacs_event->code = KEY_NS_NEW_FRAME;
4482 emacs_event->modifiers = 0;
4483 EV_TRAILER (theEvent);
4487 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4488 - (BOOL) openFile: (NSString *)fileName
4490 struct frame *emacsframe = SELECTED_FRAME ();
4491 NSEvent *theEvent = [NSApp currentEvent];
4496 emacs_event->kind = NS_NONKEY_EVENT;
4497 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4498 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4499 ns_input_line = Qnil; /* can be start or cons start,end */
4500 emacs_event->modifiers =0;
4501 EV_TRAILER (theEvent);
4507 /* **************************************************************************
4509 EmacsApp delegate implementation
4511 ************************************************************************** */
4513 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4514 /* --------------------------------------------------------------------------
4515 When application is loaded, terminate event loop in ns_term_init
4516 -------------------------------------------------------------------------- */
4518 NSTRACE (applicationDidFinishLaunching);
4519 [NSApp setServicesProvider: NSApp];
4520 ns_send_appdefined (-2);
4524 /* Termination sequences:
4527 MenuBar | File | Exit:
4528 Select Quit from App menubar:
4530 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4533 Select Quit from Dock menu:
4536 Cancel -> Nothing else
4540 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4545 - (void) terminate: (id)sender
4547 struct frame *emacsframe = SELECTED_FRAME ();
4552 emacs_event->kind = NS_NONKEY_EVENT;
4553 emacs_event->code = KEY_NS_POWER_OFF;
4554 emacs_event->arg = Qt; /* mark as non-key event */
4555 EV_TRAILER ((id)nil);
4559 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4563 if (NILP (ns_confirm_quit)) // || ns_shutdown_properly --> TO DO
4564 return NSTerminateNow;
4566 ret = NSRunAlertPanel(ns_app_name,
4567 @"Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?",
4568 @"Save Buffers and Exit", @"Cancel", nil);
4570 if (ret == NSAlertDefaultReturn)
4571 return NSTerminateNow;
4572 else if (ret == NSAlertAlternateReturn)
4573 return NSTerminateCancel;
4574 return NSTerminateNow; /* just in case */
4578 not_in_argv (NSString *arg)
4581 const char *a = [arg UTF8String];
4582 for (k = 1; k < initial_argc; ++k)
4583 if (strcmp (a, initial_argv[k]) == 0) return 0;
4587 /* Notification from the Workspace to open a file */
4588 - (BOOL)application: sender openFile: (NSString *)file
4590 if (ns_do_open_file || not_in_argv (file))
4591 [ns_pending_files addObject: file];
4596 /* Open a file as a temporary file */
4597 - (BOOL)application: sender openTempFile: (NSString *)file
4599 if (ns_do_open_file || not_in_argv (file))
4600 [ns_pending_files addObject: file];
4605 /* Notification from the Workspace to open a file noninteractively (?) */
4606 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4608 if (ns_do_open_file || not_in_argv (file))
4609 [ns_pending_files addObject: file];
4613 /* Notification from the Workspace to open multiple files */
4614 - (void)application: sender openFiles: (NSArray *)fileList
4616 NSEnumerator *files = [fileList objectEnumerator];
4618 /* Don't open files from the command line unconditionally,
4619 Cocoa parses the command line wrong, --option value tries to open value
4620 if --option is the last option. */
4621 while ((file = [files nextObject]) != nil)
4622 if (ns_do_open_file || not_in_argv (file))
4623 [ns_pending_files addObject: file];
4625 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4630 /* Handle dock menu requests. */
4631 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4637 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4638 - (void)applicationWillBecomeActive: (NSNotification *)notification
4640 //ns_app_active=YES;
4642 - (void)applicationDidBecomeActive: (NSNotification *)notification
4644 NSTRACE (applicationDidBecomeActive);
4646 //ns_app_active=YES;
4648 ns_update_auto_hide_menu_bar ();
4649 // No constraining takes place when the application is not active.
4650 ns_constrain_all_frames ();
4652 - (void)applicationDidResignActive: (NSNotification *)notification
4655 ns_send_appdefined (-1);
4660 /* ==========================================================================
4662 EmacsApp aux handlers for managing event loop
4664 ========================================================================== */
4667 - (void)timeout_handler: (NSTimer *)timedEntry
4668 /* --------------------------------------------------------------------------
4669 The timeout specified to ns_select has passed.
4670 -------------------------------------------------------------------------- */
4672 /*NSTRACE (timeout_handler); */
4673 ns_send_appdefined (-2);
4676 - (void)fd_handler:(id)unused
4677 /* --------------------------------------------------------------------------
4678 Check data waiting on file descriptors and terminate if so
4679 -------------------------------------------------------------------------- */
4682 int waiting = 1, nfds;
4685 SELECT_TYPE readfds, writefds, *wfds;
4686 EMACS_TIME timeout, *tmo;
4687 NSAutoreleasePool *pool = nil;
4689 /* NSTRACE (fd_handler); */
4694 pool = [[NSAutoreleasePool alloc] init];
4700 FD_SET (selfds[0], &fds);
4701 result = select (selfds[0]+1, &fds, NULL, NULL, NULL);
4702 if (result > 0 && read (selfds[0], &c, 1) == 1 && c == 'g')
4707 pthread_mutex_lock (&select_mutex);
4710 if (select_valid & SELECT_HAVE_READ)
4711 readfds = select_readfds;
4715 if (select_valid & SELECT_HAVE_WRITE)
4717 writefds = select_writefds;
4722 if (select_valid & SELECT_HAVE_TMO)
4724 timeout = select_timeout;
4730 pthread_mutex_unlock (&select_mutex);
4732 FD_SET (selfds[0], &readfds);
4733 if (selfds[0] >= nfds) nfds = selfds[0]+1;
4735 result = pselect (nfds, &readfds, wfds, NULL, tmo, NULL);
4738 ns_send_appdefined (-2);
4739 else if (result > 0)
4741 if (FD_ISSET (selfds[0], &readfds))
4743 if (read (selfds[0], &c, 1) == 1 && c == 's')
4748 pthread_mutex_lock (&select_mutex);
4749 if (select_valid & SELECT_HAVE_READ)
4750 select_readfds = readfds;
4751 if (select_valid & SELECT_HAVE_WRITE)
4752 select_writefds = writefds;
4753 if (select_valid & SELECT_HAVE_TMO)
4754 select_timeout = timeout;
4755 pthread_mutex_unlock (&select_mutex);
4757 ns_send_appdefined (result);
4767 /* ==========================================================================
4771 ========================================================================== */
4773 /* called from system: queue for next pass through event loop */
4774 - (void)requestService: (NSPasteboard *)pboard
4775 userData: (NSString *)userData
4776 error: (NSString **)error
4778 [ns_pending_service_names addObject: userData];
4779 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
4780 SSDATA (ns_string_from_pasteboard (pboard))]];
4784 /* called from ns_read_socket to clear queue */
4785 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
4787 struct frame *emacsframe = SELECTED_FRAME ();
4788 NSEvent *theEvent = [NSApp currentEvent];
4793 emacs_event->kind = NS_NONKEY_EVENT;
4794 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
4795 ns_input_spi_name = build_string ([name UTF8String]);
4796 ns_input_spi_arg = build_string ([arg UTF8String]);
4797 emacs_event->modifiers = EV_MODIFIERS (theEvent);
4798 EV_TRAILER (theEvent);
4808 /* ==========================================================================
4810 EmacsView implementation
4812 ========================================================================== */
4815 @implementation EmacsView
4817 /* needed to inform when window closed from LISP */
4818 - (void) setWindowClosing: (BOOL)closing
4820 windowClosing = closing;
4826 NSTRACE (EmacsView_dealloc);
4828 if (fs_state == FULLSCREEN_BOTH)
4829 [nonfs_window release];
4834 /* called on font panel selection */
4835 - (void)changeFont: (id)sender
4837 NSEvent *e =[[self window] currentEvent];
4838 struct face *face =FRAME_DEFAULT_FACE (emacsframe);
4842 NSTRACE (changeFont);
4846 if ((newFont = [sender convertFont:
4847 ((struct nsfont_info *)face->font)->nsfont]))
4849 SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
4851 emacs_event->kind = NS_NONKEY_EVENT;
4852 emacs_event->modifiers = 0;
4853 emacs_event->code = KEY_NS_CHANGE_FONT;
4855 size = [newFont pointSize];
4856 ns_input_fontsize = make_number (lrint (size));
4857 ns_input_font = build_string ([[newFont familyName] UTF8String]);
4863 - (BOOL)acceptsFirstResponder
4865 NSTRACE (acceptsFirstResponder);
4870 - (void)resetCursorRects
4872 NSRect visible = [self visibleRect];
4873 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
4874 NSTRACE (resetCursorRects);
4876 if (currentCursor == nil)
4877 currentCursor = [NSCursor arrowCursor];
4879 if (!NSIsEmptyRect (visible))
4880 [self addCursorRect: visible cursor: currentCursor];
4881 [currentCursor setOnMouseEntered: YES];
4886 /*****************************************************************************/
4887 /* Keyboard handling. */
4890 - (void)keyDown: (NSEvent *)theEvent
4892 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
4894 unsigned fnKeysym = 0;
4895 static NSMutableArray *nsEvArray;
4896 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
4897 static BOOL firstTime = YES;
4900 unsigned int flags = [theEvent modifierFlags];
4904 /* Rhapsody and OS X give up and down events for the arrow keys */
4905 if (ns_fake_keydown == YES)
4906 ns_fake_keydown = NO;
4907 else if ([theEvent type] != NSKeyDown)
4913 if (![[self window] isKeyWindow]
4914 && [[theEvent window] isKindOfClass: [EmacsWindow class]]
4915 /* we must avoid an infinite loop here. */
4916 && (EmacsView *)[[theEvent window] delegate] != self)
4918 /* XXX: There is an occasional condition in which, when Emacs display
4919 updates a different frame from the current one, and temporarily
4920 selects it, then processes some interrupt-driven input
4921 (dispnew.c:3878), OS will send the event to the correct NSWindow, but
4922 for some reason that window has its first responder set to the NSView
4923 most recently updated (I guess), which is not the correct one. */
4924 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
4928 if (nsEvArray == nil)
4929 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
4931 [NSCursor setHiddenUntilMouseMoves: YES];
4933 if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
4935 clear_mouse_face (hlinfo);
4936 hlinfo->mouse_face_hidden = 1;
4939 if (!processingCompose)
4941 /* When using screen sharing, no left or right information is sent,
4942 so use Left key in those cases. */
4943 int is_left_key, is_right_key;
4945 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
4946 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
4948 /* (Carbon way: [theEvent keyCode]) */
4950 /* is it a "function key"? */
4951 fnKeysym = (code < 0x00ff && (flags&NSNumericPadKeyMask))
4952 ? ns_convert_key ([theEvent keyCode] | NSNumericPadKeyMask)
4953 : ns_convert_key (code);
4957 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
4958 because Emacs treats Delete and KP-Delete same (in simple.el). */
4959 if (fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
4960 code = 0xFF08; /* backspace */
4965 /* are there modifiers? */
4966 emacs_event->modifiers = 0;
4968 if (flags & NSHelpKeyMask)
4969 emacs_event->modifiers |= hyper_modifier;
4971 if (flags & NSShiftKeyMask)
4972 emacs_event->modifiers |= shift_modifier;
4974 is_right_key = (flags & NSRightCommandKeyMask) == NSRightCommandKeyMask;
4975 is_left_key = (flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask
4976 || (! is_right_key && (flags & NSCommandKeyMask) == NSCommandKeyMask);
4979 emacs_event->modifiers |= parse_solitary_modifier
4980 (EQ (ns_right_command_modifier, Qleft)
4981 ? ns_command_modifier
4982 : ns_right_command_modifier);
4986 emacs_event->modifiers |= parse_solitary_modifier
4987 (ns_command_modifier);
4989 /* if super (default), take input manager's word so things like
4990 dvorak / qwerty layout work */
4991 if (EQ (ns_command_modifier, Qsuper)
4993 && [[theEvent characters] length] != 0)
4995 /* XXX: the code we get will be unshifted, so if we have
4996 a shift modifier, must convert ourselves */
4997 if (!(flags & NSShiftKeyMask))
4998 code = [[theEvent characters] characterAtIndex: 0];
5000 /* this is ugly and also requires linking w/Carbon framework
5001 (for LMGetKbdType) so for now leave this rare (?) case
5002 undealt with.. in future look into CGEvent methods */
5005 long smv = GetScriptManagerVariable (smKeyScript);
5006 Handle uchrHandle = GetResource
5007 ('uchr', GetScriptVariable (smv, smScriptKeys));
5009 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
5010 [[theEvent characters] characterAtIndex: 0],
5011 kUCKeyActionDisplay,
5012 (flags & ~NSCommandKeyMask) >> 8,
5013 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
5014 &dummy, 1, &dummy, &code);
5021 is_right_key = (flags & NSRightControlKeyMask) == NSRightControlKeyMask;
5022 is_left_key = (flags & NSLeftControlKeyMask) == NSLeftControlKeyMask
5023 || (! is_right_key && (flags & NSControlKeyMask) == NSControlKeyMask);
5026 emacs_event->modifiers |= parse_solitary_modifier
5027 (EQ (ns_right_control_modifier, Qleft)
5028 ? ns_control_modifier
5029 : ns_right_control_modifier);
5032 emacs_event->modifiers |= parse_solitary_modifier
5033 (ns_control_modifier);
5035 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
5036 emacs_event->modifiers |=
5037 parse_solitary_modifier (ns_function_modifier);
5039 left_is_none = NILP (ns_alternate_modifier)
5040 || EQ (ns_alternate_modifier, Qnone);
5042 is_right_key = (flags & NSRightAlternateKeyMask)
5043 == NSRightAlternateKeyMask;
5044 is_left_key = (flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask
5046 && (flags & NSAlternateKeyMask) == NSAlternateKeyMask);
5050 if ((NILP (ns_right_alternate_modifier)
5051 || EQ (ns_right_alternate_modifier, Qnone)
5052 || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
5054 { /* accept pre-interp alt comb */
5055 if ([[theEvent characters] length] > 0)
5056 code = [[theEvent characters] characterAtIndex: 0];
5057 /*HACK: clear lone shift modifier to stop next if from firing */
5058 if (emacs_event->modifiers == shift_modifier)
5059 emacs_event->modifiers = 0;
5062 emacs_event->modifiers |= parse_solitary_modifier
5063 (EQ (ns_right_alternate_modifier, Qleft)
5064 ? ns_alternate_modifier
5065 : ns_right_alternate_modifier);
5068 if (is_left_key) /* default = meta */
5070 if (left_is_none && !fnKeysym)
5071 { /* accept pre-interp alt comb */
5072 if ([[theEvent characters] length] > 0)
5073 code = [[theEvent characters] characterAtIndex: 0];
5074 /*HACK: clear lone shift modifier to stop next if from firing */
5075 if (emacs_event->modifiers == shift_modifier)
5076 emacs_event->modifiers = 0;
5079 emacs_event->modifiers |=
5080 parse_solitary_modifier (ns_alternate_modifier);
5084 fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
5085 code, fnKeysym, flags, emacs_event->modifiers);
5087 /* if it was a function key or had modifiers, pass it directly to emacs */
5088 if (fnKeysym || (emacs_event->modifiers
5089 && (emacs_event->modifiers != shift_modifier)
5090 && [[theEvent charactersIgnoringModifiers] length] > 0))
5091 /*[[theEvent characters] length] */
5093 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5095 code |= (1<<28)|(3<<16);
5096 else if (code == 0x7f)
5097 code |= (1<<28)|(3<<16);
5099 emacs_event->kind = code > 0xFF
5100 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5102 emacs_event->code = code;
5103 EV_TRAILER (theEvent);
5104 processingCompose = NO;
5110 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
5111 /* if we get here we should send the key for input manager processing */
5112 if (firstTime && [[NSInputManager currentInputManager]
5113 wantsToDelayTextChangeNotifications] == NO)
5115 "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
5118 if (NS_KEYLOG && !processingCompose)
5119 fprintf (stderr, "keyDown: Begin compose sequence.\n");
5121 processingCompose = YES;
5122 [nsEvArray addObject: theEvent];
5123 [self interpretKeyEvents: nsEvArray];
5124 [nsEvArray removeObject: theEvent];
5128 #ifdef NS_IMPL_COCOA
5129 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
5130 decided not to send key-down for.
5131 See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
5132 This only applies on Tiger and earlier.
5133 If it matches one of these, send it on to keyDown. */
5134 -(void)keyUp: (NSEvent *)theEvent
5136 int flags = [theEvent modifierFlags];
5137 int code = [theEvent keyCode];
5138 if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
5139 code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
5142 fprintf (stderr, "keyUp: passed test");
5143 ns_fake_keydown = YES;
5144 [self keyDown: theEvent];
5150 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
5153 /* <NSTextInput>: called when done composing;
5154 NOTE: also called when we delete over working text, followed immed.
5155 by doCommandBySelector: deleteBackward: */
5156 - (void)insertText: (id)aString
5159 int len = [(NSString *)aString length];
5163 NSLog (@"insertText '%@'\tlen = %d", aString, len);
5164 processingCompose = NO;
5169 /* first, clear any working text */
5170 if (workingText != nil)
5171 [self deleteWorkingText];
5173 /* now insert the string as keystrokes */
5174 for (i =0; i<len; i++)
5176 code = [aString characterAtIndex: i];
5177 /* TODO: still need this? */
5179 code = '~'; /* 0x7E */
5180 if (code != 32) /* Space */
5181 emacs_event->modifiers = 0;
5183 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5184 emacs_event->code = code;
5185 EV_TRAILER ((id)nil);
5190 /* <NSTextInput>: inserts display of composing characters */
5191 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
5193 NSString *str = [aString respondsToSelector: @selector (string)] ?
5194 [aString string] : aString;
5196 NSLog (@"setMarkedText '%@' len =%d range %d from %d", str, [str length],
5197 selRange.length, selRange.location);
5199 if (workingText != nil)
5200 [self deleteWorkingText];
5201 if ([str length] == 0)
5207 processingCompose = YES;
5208 workingText = [str copy];
5209 ns_working_text = build_string ([workingText UTF8String]);
5211 emacs_event->kind = NS_TEXT_EVENT;
5212 emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
5213 EV_TRAILER ((id)nil);
5217 /* delete display of composing characters [not in <NSTextInput>] */
5218 - (void)deleteWorkingText
5220 if (workingText == nil)
5223 NSLog(@"deleteWorkingText len =%d\n", [workingText length]);
5224 [workingText release];
5226 processingCompose = NO;
5231 emacs_event->kind = NS_TEXT_EVENT;
5232 emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
5233 EV_TRAILER ((id)nil);
5237 - (BOOL)hasMarkedText
5239 return workingText != nil;
5243 - (NSRange)markedRange
5245 NSRange rng = workingText != nil
5246 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
5248 NSLog (@"markedRange request");
5256 NSLog (@"unmark (accept) text");
5257 [self deleteWorkingText];
5258 processingCompose = NO;
5262 /* used to position char selection windows, etc. */
5263 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
5267 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
5269 NSLog (@"firstRectForCharRange request");
5271 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
5272 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
5273 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
5274 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
5275 +FRAME_LINE_HEIGHT (emacsframe));
5277 pt = [self convertPoint: pt toView: nil];
5278 pt = [[self window] convertBaseToScreen: pt];
5284 - (NSInteger)conversationIdentifier
5286 return (NSInteger)self;
5290 - (void)doCommandBySelector: (SEL)aSelector
5293 NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
5295 processingCompose = NO;
5296 if (aSelector == @selector (deleteBackward:))
5298 /* happens when user backspaces over an ongoing composition:
5299 throw a 'delete' into the event queue */
5302 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5303 emacs_event->code = 0xFF08;
5304 EV_TRAILER ((id)nil);
5308 - (NSArray *)validAttributesForMarkedText
5310 static NSArray *arr = nil;
5311 if (arr == nil) arr = [NSArray new];
5312 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
5316 - (NSRange)selectedRange
5319 NSLog (@"selectedRange request");
5320 return NSMakeRange (NSNotFound, 0);
5323 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
5326 NSLog (@"characterIndexForPoint request");
5330 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
5332 static NSAttributedString *str = nil;
5333 if (str == nil) str = [NSAttributedString new];
5335 NSLog (@"attributedSubstringFromRange request");
5339 /* End <NSTextInput> impl. */
5340 /*****************************************************************************/
5343 /* This is what happens when the user presses a mouse button. */
5344 - (void)mouseDown: (NSEvent *)theEvent
5346 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5348 NSTRACE (mouseDown);
5350 [self deleteWorkingText];
5355 last_mouse_frame = emacsframe;
5356 /* appears to be needed to prevent spurious movement events generated on
5358 last_mouse_frame->mouse_moved = 0;
5360 if ([theEvent type] == NSScrollWheel)
5362 float delta = [theEvent deltaY];
5363 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
5366 emacs_event->kind = WHEEL_EVENT;
5367 emacs_event->code = 0;
5368 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
5369 ((delta > 0) ? up_modifier : down_modifier);
5373 emacs_event->kind = MOUSE_CLICK_EVENT;
5374 emacs_event->code = EV_BUTTON (theEvent);
5375 emacs_event->modifiers = EV_MODIFIERS (theEvent)
5376 | EV_UDMODIFIERS (theEvent);
5378 XSETINT (emacs_event->x, lrint (p.x));
5379 XSETINT (emacs_event->y, lrint (p.y));
5380 EV_TRAILER (theEvent);
5384 - (void)rightMouseDown: (NSEvent *)theEvent
5386 NSTRACE (rightMouseDown);
5387 [self mouseDown: theEvent];
5391 - (void)otherMouseDown: (NSEvent *)theEvent
5393 NSTRACE (otherMouseDown);
5394 [self mouseDown: theEvent];
5398 - (void)mouseUp: (NSEvent *)theEvent
5401 [self mouseDown: theEvent];
5405 - (void)rightMouseUp: (NSEvent *)theEvent
5407 NSTRACE (rightMouseUp);
5408 [self mouseDown: theEvent];
5412 - (void)otherMouseUp: (NSEvent *)theEvent
5414 NSTRACE (otherMouseUp);
5415 [self mouseDown: theEvent];
5419 - (void) scrollWheel: (NSEvent *)theEvent
5421 NSTRACE (scrollWheel);
5422 [self mouseDown: theEvent];
5426 /* Tell emacs the mouse has moved. */
5427 - (void)mouseMoved: (NSEvent *)e
5429 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5432 // NSTRACE (mouseMoved);
5434 last_mouse_movement_time = EV_TIMESTAMP (e);
5435 last_mouse_motion_position
5436 = [self convertPoint: [e locationInWindow] fromView: nil];
5438 /* update any mouse face */
5439 if (hlinfo->mouse_face_hidden)
5441 hlinfo->mouse_face_hidden = 0;
5442 clear_mouse_face (hlinfo);
5445 /* tooltip handling */
5446 previous_help_echo_string = help_echo_string;
5447 help_echo_string = Qnil;
5449 if (!note_mouse_movement (emacsframe, last_mouse_motion_position.x,
5450 last_mouse_motion_position.y))
5451 help_echo_string = previous_help_echo_string;
5453 XSETFRAME (frame, emacsframe);
5454 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
5456 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
5457 (note_mouse_highlight), which is called through the
5458 note_mouse_movement () call above */
5459 gen_help_event (help_echo_string, frame, help_echo_window,
5460 help_echo_object, help_echo_pos);
5464 help_echo_string = Qnil;
5465 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
5468 if (emacsframe->mouse_moved && send_appdefined)
5469 ns_send_appdefined (-1);
5473 - (void)mouseDragged: (NSEvent *)e
5475 NSTRACE (mouseDragged);
5476 [self mouseMoved: e];
5480 - (void)rightMouseDragged: (NSEvent *)e
5482 NSTRACE (rightMouseDragged);
5483 [self mouseMoved: e];
5487 - (void)otherMouseDragged: (NSEvent *)e
5489 NSTRACE (otherMouseDragged);
5490 [self mouseMoved: e];
5494 - (BOOL)windowShouldClose: (id)sender
5496 NSEvent *e =[[self window] currentEvent];
5498 NSTRACE (windowShouldClose);
5499 windowClosing = YES;
5502 emacs_event->kind = DELETE_WINDOW_EVENT;
5503 emacs_event->modifiers = 0;
5504 emacs_event->code = 0;
5506 /* Don't close this window, let this be done from lisp code. */
5510 - (void) updateFrameSize: (BOOL) delay;
5512 NSWindow *window = [self window];
5513 NSRect wr = [window frame];
5516 #ifdef NS_IMPL_GNUSTEP
5520 int oldc = cols, oldr = rows;
5521 int oldw = FRAME_PIXEL_WIDTH (emacsframe),
5522 oldh = FRAME_PIXEL_HEIGHT (emacsframe);
5525 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, wr.size.width + gsextra);
5527 if (cols < MINWIDTH)
5530 if (! [self isFullscreen])
5532 extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5533 + FRAME_TOOLBAR_HEIGHT (emacsframe) - gsextra;
5536 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, wr.size.height - extra);
5538 if (rows < MINHEIGHT)
5541 neww = (int)wr.size.width - emacsframe->border_width;
5542 newh = (int)wr.size.height - extra;
5544 if (oldr != rows || oldc != cols || neww != oldw || newh != oldh)
5546 struct frame *f = emacsframe;
5547 NSView *view = FRAME_NS_VIEW (emacsframe);
5548 NSWindow *win = [view window];
5549 NSSize sz = [win resizeIncrements];
5551 FRAME_PIXEL_WIDTH (emacsframe) = neww;
5552 FRAME_PIXEL_HEIGHT (emacsframe) = newh;
5553 change_frame_size (emacsframe, rows, cols, 0, delay, 0);
5554 SET_FRAME_GARBAGED (emacsframe);
5555 cancel_mouse_face (emacsframe);
5557 // Did resize increments change because of a font change?
5558 if (sz.width != FRAME_COLUMN_WIDTH (emacsframe) ||
5559 sz.height != FRAME_LINE_HEIGHT (emacsframe))
5561 sz.width = FRAME_COLUMN_WIDTH (emacsframe);
5562 sz.height = FRAME_LINE_HEIGHT (emacsframe);
5563 [win setResizeIncrements: sz];
5566 [view setFrame: NSMakeRect (0, 0, neww, newh)];
5567 [self windowDidMove:nil]; // Update top/left.
5571 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
5572 /* normalize frame to gridded text size */
5576 #ifdef NS_IMPL_GNUSTEP
5580 NSTRACE (windowWillResize);
5581 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
5583 if (fs_state == FULLSCREEN_MAXIMIZED
5584 && (maximized_width != (int)frameSize.width
5585 || maximized_height != (int)frameSize.height))
5586 [self setFSValue: FULLSCREEN_NONE];
5587 else if (fs_state == FULLSCREEN_WIDTH
5588 && maximized_width != (int)frameSize.width)
5589 [self setFSValue: FULLSCREEN_NONE];
5590 else if (fs_state == FULLSCREEN_HEIGHT
5591 && maximized_height != (int)frameSize.height)
5592 [self setFSValue: FULLSCREEN_NONE];
5593 if (fs_state == FULLSCREEN_NONE)
5594 maximized_width = maximized_height = -1;
5596 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe,
5597 frameSize.width + gsextra);
5598 if (cols < MINWIDTH)
5601 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe,
5602 frameSize.height - extra);
5603 if (rows < MINHEIGHT)
5605 #ifdef NS_IMPL_COCOA
5607 /* this sets window title to have size in it; the wm does this under GS */
5608 NSRect r = [[self window] frame];
5609 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
5620 NSWindow *window = [self window];
5623 const char *t = [[[self window] title] UTF8String];
5624 char *pos = strstr (t, " — ");
5627 old_title = xstrdup (t);
5629 size_title = xmalloc (strlen (old_title) + 40);
5630 esprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
5631 [window setTitle: [NSString stringWithUTF8String: size_title]];
5636 #endif /* NS_IMPL_COCOA */
5637 /*fprintf (stderr," ...size became %.0f x %.0f (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
5643 - (void)windowDidResize: (NSNotification *)notification
5645 if (! [self fsIsNative])
5647 NSWindow *theWindow = [notification object];
5648 /* We can get notification on the non-FS window when in
5650 if ([self window] != theWindow) return;
5653 #ifdef NS_IMPL_GNUSTEP
5654 NSWindow *theWindow = [notification object];
5656 /* In GNUstep, at least currently, it's possible to get a didResize
5657 without getting a willResize.. therefore we need to act as if we got
5658 the willResize now */
5659 NSSize sz = [theWindow frame].size;
5660 sz = [self windowWillResize: theWindow toSize: sz];
5661 #endif /* NS_IMPL_GNUSTEP */
5663 NSTRACE (windowDidResize);
5664 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
5666 #ifdef NS_IMPL_COCOA
5672 #endif /* NS_IMPL_COCOA */
5674 if (cols > 0 && rows > 0)
5676 [self updateFrameSize: YES];
5679 ns_send_appdefined (-1);
5683 - (void)windowDidBecomeKey: (NSNotification *)notification
5684 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5686 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5687 struct frame *old_focus = dpyinfo->x_focus_frame;
5689 NSTRACE (windowDidBecomeKey);
5691 if (emacsframe != old_focus)
5692 dpyinfo->x_focus_frame = emacsframe;
5694 ns_frame_rehighlight (emacsframe);
5698 emacs_event->kind = FOCUS_IN_EVENT;
5699 EV_TRAILER ((id)nil);
5704 - (void)windowDidResignKey: (NSNotification *)notification
5705 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5707 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5708 NSTRACE (windowDidResignKey);
5710 if (dpyinfo->x_focus_frame == emacsframe)
5711 dpyinfo->x_focus_frame = 0;
5713 ns_frame_rehighlight (emacsframe);
5715 /* FIXME: for some reason needed on second and subsequent clicks away
5716 from sole-frame Emacs to get hollow box to show */
5717 if (!windowClosing && [[self window] isVisible] == YES)
5719 x_update_cursor (emacsframe, 1);
5720 x_set_frame_alpha (emacsframe);
5725 [self deleteWorkingText];
5726 emacs_event->kind = FOCUS_IN_EVENT;
5727 EV_TRAILER ((id)nil);
5732 - (void)windowWillMiniaturize: sender
5734 NSTRACE (windowWillMiniaturize);
5750 - initFrameFromEmacs: (struct frame *)f
5755 NSButton *toggleButton;
5760 NSTRACE (initFrameFromEmacs);
5763 processingCompose = NO;
5764 scrollbarsNeedingUpdate = 0;
5765 fs_state = FULLSCREEN_NONE;
5766 fs_before_fs = next_maximized = -1;
5767 #ifdef HAVE_NATIVE_FS
5768 fs_is_native = ns_use_native_fullscreen;
5772 maximized_width = maximized_height = -1;
5775 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
5777 ns_userRect = NSMakeRect (0, 0, 0, 0);
5778 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
5779 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
5780 [self initWithFrame: r];
5781 [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
5783 FRAME_NS_VIEW (f) = self;
5787 win = [[EmacsWindow alloc]
5788 initWithContentRect: r
5789 styleMask: (NSResizableWindowMask |
5790 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
5791 NSTitledWindowMask |
5793 NSMiniaturizableWindowMask |
5794 NSClosableWindowMask)
5795 backing: NSBackingStoreBuffered
5798 #ifdef HAVE_NATIVE_FS
5799 [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
5803 bwidth = f->border_width = wr.size.width - r.size.width;
5804 tibar_height = FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
5806 [win setAcceptsMouseMovedEvents: YES];
5807 [win setDelegate: self];
5808 [win useOptimizedDrawing: YES];
5810 sz.width = FRAME_COLUMN_WIDTH (f);
5811 sz.height = FRAME_LINE_HEIGHT (f);
5812 [win setResizeIncrements: sz];
5814 [[win contentView] addSubview: self];
5817 [self registerForDraggedTypes: ns_drag_types];
5820 name = [NSString stringWithUTF8String:
5821 NILP (tem) ? "Emacs" : SSDATA (tem)];
5822 [win setTitle: name];
5824 /* toolbar support */
5825 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
5826 [NSString stringWithFormat: @"Emacs Frame %d",
5828 [win setToolbar: toolbar];
5829 [toolbar setVisible: NO];
5830 #ifdef NS_IMPL_COCOA
5831 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
5832 [toggleButton setTarget: self];
5833 [toggleButton setAction: @selector (toggleToolbar: )];
5835 FRAME_TOOLBAR_HEIGHT (f) = 0;
5839 [win setMiniwindowTitle:
5840 [NSString stringWithUTF8String: SSDATA (tem)]];
5843 NSScreen *screen = [win screen];
5846 [win setFrameTopLeftPoint: NSMakePoint
5847 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
5848 IN_BOUND (-SCREENMAX,
5849 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
5852 [win makeFirstResponder: self];
5854 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5855 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
5856 [win setBackgroundColor: col];
5857 if ([col alphaComponent] != 1.0)
5858 [win setOpaque: NO];
5860 [self allocateGState];
5862 [NSApp registerServicesMenuSendTypes: ns_send_types
5870 - (void)windowDidMove: sender
5872 NSWindow *win = [self window];
5873 NSRect r = [win frame];
5874 NSArray *screens = [NSScreen screens];
5875 NSScreen *screen = [screens objectAtIndex: 0];
5877 NSTRACE (windowDidMove);
5879 if (!emacsframe->output_data.ns)
5883 emacsframe->left_pos = r.origin.x;
5884 emacsframe->top_pos =
5885 [screen frame].size.height - (r.origin.y + r.size.height);
5890 /* Called AFTER method below, but before our windowWillResize call there leads
5891 to windowDidResize -> x_set_window_size. Update emacs' notion of frame
5892 location so set_window_size moves the frame. */
5893 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
5895 emacsframe->output_data.ns->zooming = 1;
5900 /* Override to do something slightly nonstandard, but nice. First click on
5901 zoom button will zoom vertically. Second will zoom completely. Third
5902 returns to original. */
5903 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
5904 defaultFrame:(NSRect)defaultFrame
5906 NSRect result = [sender frame];
5908 NSTRACE (windowWillUseStandardFrame);
5910 if (fs_before_fs != -1) /* Entering fullscreen */
5912 result = defaultFrame;
5914 else if (next_maximized == FULLSCREEN_HEIGHT
5915 || (next_maximized == -1
5916 && abs (defaultFrame.size.height - result.size.height)
5917 > FRAME_LINE_HEIGHT (emacsframe)))
5920 ns_userRect = result;
5921 maximized_height = result.size.height = defaultFrame.size.height;
5922 maximized_width = -1;
5923 result.origin.y = defaultFrame.origin.y;
5924 [self setFSValue: FULLSCREEN_HEIGHT];
5926 else if (next_maximized == FULLSCREEN_WIDTH)
5928 ns_userRect = result;
5929 maximized_width = result.size.width = defaultFrame.size.width;
5930 maximized_height = -1;
5931 result.origin.x = defaultFrame.origin.x;
5932 [self setFSValue: FULLSCREEN_WIDTH];
5934 else if (next_maximized == FULLSCREEN_MAXIMIZED
5935 || (next_maximized == -1
5936 && abs (defaultFrame.size.width - result.size.width)
5937 > FRAME_COLUMN_WIDTH (emacsframe)))
5939 result = defaultFrame; /* second click */
5940 maximized_width = result.size.width;
5941 maximized_height = result.size.height;
5942 [self setFSValue: FULLSCREEN_MAXIMIZED];
5947 result = ns_userRect.size.height ? ns_userRect : result;
5948 ns_userRect = NSMakeRect (0, 0, 0, 0);
5949 [self setFSValue: FULLSCREEN_NONE];
5950 maximized_width = maximized_width = -1;
5953 if (fs_before_fs == -1) next_maximized = -1;
5954 [self windowWillResize: sender toSize: result.size];
5959 - (void)windowDidDeminiaturize: sender
5961 NSTRACE (windowDidDeminiaturize);
5962 if (!emacsframe->output_data.ns)
5965 SET_FRAME_ICONIFIED (emacsframe, 0);
5966 SET_FRAME_VISIBLE (emacsframe, 1);
5967 windows_or_buffers_changed++;
5971 emacs_event->kind = DEICONIFY_EVENT;
5972 EV_TRAILER ((id)nil);
5977 - (void)windowDidExpose: sender
5979 NSTRACE (windowDidExpose);
5980 if (!emacsframe->output_data.ns)
5983 SET_FRAME_VISIBLE (emacsframe, 1);
5984 SET_FRAME_GARBAGED (emacsframe);
5986 if (send_appdefined)
5987 ns_send_appdefined (-1);
5991 - (void)windowDidMiniaturize: sender
5993 NSTRACE (windowDidMiniaturize);
5994 if (!emacsframe->output_data.ns)
5997 SET_FRAME_ICONIFIED (emacsframe, 1);
5998 SET_FRAME_VISIBLE (emacsframe, 0);
6002 emacs_event->kind = ICONIFY_EVENT;
6003 EV_TRAILER ((id)nil);
6007 #ifdef HAVE_NATIVE_FS
6008 - (NSApplicationPresentationOptions)window:(NSWindow *)window
6009 willUseFullScreenPresentationOptions:
6010 (NSApplicationPresentationOptions)proposedOptions
6012 return proposedOptions|NSApplicationPresentationAutoHideToolbar;
6016 - (void)windowWillEnterFullScreen:(NSNotification *)notification
6018 fs_before_fs = fs_state;
6021 - (void)windowDidEnterFullScreen:(NSNotification *)notification
6023 [self setFSValue: FULLSCREEN_BOTH];
6024 if (! [self fsIsNative])
6026 [self windowDidBecomeKey:notification];
6027 [nonfs_window orderOut:self];
6029 else if (! FRAME_EXTERNAL_TOOL_BAR (emacsframe))
6030 [toolbar setVisible:NO];
6033 - (void)windowWillExitFullScreen:(NSNotification *)notification
6035 if (next_maximized != -1)
6036 fs_before_fs = next_maximized;
6039 - (void)windowDidExitFullScreen:(NSNotification *)notification
6041 [self setFSValue: fs_before_fs];
6043 [self updateCollectionBehaviour];
6044 if (FRAME_EXTERNAL_TOOL_BAR (emacsframe))
6046 [toolbar setVisible:YES];
6047 update_frame_tool_bar (emacsframe);
6048 [self updateFrameSize:YES];
6049 [[self window] display];
6052 [toolbar setVisible:NO];
6054 if (next_maximized != -1)
6055 [[self window] performZoom:self];
6060 return fs_is_native;
6063 - (BOOL)isFullscreen
6065 if (! fs_is_native) return nonfs_window != nil;
6066 #ifdef HAVE_NATIVE_FS
6067 return ([[self window] styleMask] & NSFullScreenWindowMask) != 0;
6073 #ifdef HAVE_NATIVE_FS
6074 - (void)updateCollectionBehaviour
6076 if (! [self isFullscreen])
6078 NSWindow *win = [self window];
6079 NSWindowCollectionBehavior b = [win collectionBehavior];
6080 if (ns_use_native_fullscreen)
6081 b |= NSWindowCollectionBehaviorFullScreenPrimary;
6083 b &= ~NSWindowCollectionBehaviorFullScreenPrimary;
6085 [win setCollectionBehavior: b];
6086 fs_is_native = ns_use_native_fullscreen;
6091 - (void)toggleFullScreen: (id)sender
6102 [[self window] toggleFullScreen:sender];
6107 onFirstScreen = [[w screen] isEqual:[[NSScreen screens] objectAtIndex:0]];
6110 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6111 (FRAME_DEFAULT_FACE (f)),
6114 sz.width = FRAME_COLUMN_WIDTH (f);
6115 sz.height = FRAME_LINE_HEIGHT (f);
6117 if (fs_state != FULLSCREEN_BOTH)
6119 /* Hide dock and menubar if we are on the primary screen. */
6122 #if defined (NS_IMPL_COCOA) && \
6123 MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
6124 NSApplicationPresentationOptions options
6125 = NSApplicationPresentationAutoHideDock
6126 | NSApplicationPresentationAutoHideMenuBar;
6128 [NSApp setPresentationOptions: options];
6130 [NSMenu setMenuBarVisible:NO];
6134 fw = [[EmacsFSWindow alloc]
6135 initWithContentRect:[w contentRectForFrameRect:wr]
6136 styleMask:NSBorderlessWindowMask
6137 backing:NSBackingStoreBuffered
6141 [fw setContentView:[w contentView]];
6142 [fw setTitle:[w title]];
6143 [fw setDelegate:self];
6144 [fw setAcceptsMouseMovedEvents: YES];
6145 [fw useOptimizedDrawing: YES];
6146 [fw setResizeIncrements: sz];
6147 [fw setBackgroundColor: col];
6148 if ([col alphaComponent] != 1.0)
6151 f->border_width = 0;
6152 FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
6153 tobar_height = FRAME_TOOLBAR_HEIGHT (f);
6154 FRAME_TOOLBAR_HEIGHT (f) = 0;
6158 [self windowWillEnterFullScreen:nil];
6159 [fw makeKeyAndOrderFront:NSApp];
6160 [fw makeFirstResponder:self];
6162 r = [fw frameRectForContentRect:[[fw screen] frame]];
6163 [fw setFrame: r display:YES animate:YES];
6164 [self windowDidEnterFullScreen:nil];
6175 #if defined (NS_IMPL_COCOA) && \
6176 MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
6177 [NSApp setPresentationOptions: NSApplicationPresentationDefault];
6179 [NSMenu setMenuBarVisible:YES];
6183 [w setContentView:[fw contentView]];
6184 [w setResizeIncrements: sz];
6185 [w setBackgroundColor: col];
6186 if ([col alphaComponent] != 1.0)
6189 f->border_width = bwidth;
6190 FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
6191 if (FRAME_EXTERNAL_TOOL_BAR (f))
6192 FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
6194 [self windowWillExitFullScreen:nil];
6195 [fw setFrame: [w frame] display:YES animate:YES];
6197 [w makeKeyAndOrderFront:NSApp];
6198 [self windowDidExitFullScreen:nil];
6199 [self updateFrameSize:YES];
6205 if (fs_state != emacsframe->want_fullscreen)
6207 if (fs_state == FULLSCREEN_BOTH)
6209 [self toggleFullScreen:self];
6212 switch (emacsframe->want_fullscreen)
6214 case FULLSCREEN_BOTH:
6215 [self toggleFullScreen:self];
6217 case FULLSCREEN_WIDTH:
6218 next_maximized = FULLSCREEN_WIDTH;
6219 if (fs_state != FULLSCREEN_BOTH)
6220 [[self window] performZoom:self];
6222 case FULLSCREEN_HEIGHT:
6223 next_maximized = FULLSCREEN_HEIGHT;
6224 if (fs_state != FULLSCREEN_BOTH)
6225 [[self window] performZoom:self];
6227 case FULLSCREEN_MAXIMIZED:
6228 next_maximized = FULLSCREEN_MAXIMIZED;
6229 if (fs_state != FULLSCREEN_BOTH)
6230 [[self window] performZoom:self];
6232 case FULLSCREEN_NONE:
6233 if (fs_state != FULLSCREEN_BOTH)
6235 next_maximized = FULLSCREEN_NONE;
6236 [[self window] performZoom:self];
6241 emacsframe->want_fullscreen = FULLSCREEN_NONE;
6246 - (void) setFSValue: (int)value
6248 Lisp_Object lval = Qnil;
6251 case FULLSCREEN_BOTH:
6254 case FULLSCREEN_WIDTH:
6257 case FULLSCREEN_HEIGHT:
6260 case FULLSCREEN_MAXIMIZED:
6264 store_frame_param (emacsframe, Qfullscreen, lval);
6268 - (void)mouseEntered: (NSEvent *)theEvent
6270 NSTRACE (mouseEntered);
6271 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
6275 - (void)mouseExited: (NSEvent *)theEvent
6277 Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
6279 NSTRACE (mouseExited);
6284 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
6286 if (emacsframe == hlinfo->mouse_face_mouse_frame)
6288 clear_mouse_face (hlinfo);
6289 hlinfo->mouse_face_mouse_frame = 0;
6297 if (context_menu_value == -1)
6298 context_menu_value = [sender tag];
6301 NSInteger tag = [sender tag];
6302 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
6303 emacsframe->menu_bar_vector,
6307 ns_send_appdefined (-1);
6312 - (EmacsToolbar *)toolbar
6318 /* this gets called on toolbar button click */
6319 - toolbarClicked: (id)item
6322 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
6324 NSTRACE (toolbarClicked);
6329 /* send first event (for some reason two needed) */
6330 theEvent = [[self window] currentEvent];
6331 emacs_event->kind = TOOL_BAR_EVENT;
6332 XSETFRAME (emacs_event->arg, emacsframe);
6333 EV_TRAILER (theEvent);
6335 emacs_event->kind = TOOL_BAR_EVENT;
6336 /* XSETINT (emacs_event->code, 0); */
6337 emacs_event->arg = AREF (emacsframe->tool_bar_items,
6338 idx + TOOL_BAR_ITEM_KEY);
6339 emacs_event->modifiers = EV_MODIFIERS (theEvent);
6340 EV_TRAILER (theEvent);
6345 - toggleToolbar: (id)sender
6350 emacs_event->kind = NS_NONKEY_EVENT;
6351 emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
6352 EV_TRAILER ((id)nil);
6357 - (void)drawRect: (NSRect)rect
6359 int x = NSMinX (rect), y = NSMinY (rect);
6360 int width = NSWidth (rect), height = NSHeight (rect);
6364 if (!emacsframe || !emacsframe->output_data.ns)
6367 ns_clear_frame_area (emacsframe, x, y, width, height);
6368 expose_frame (emacsframe, x, y, width, height);
6371 drawRect: may be called (at least in OS X 10.5) for invisible
6372 views as well for some reason. Thus, do not infer visibility
6375 emacsframe->async_visible = 1;
6376 emacsframe->async_iconified = 0;
6381 /* NSDraggingDestination protocol methods. Actually this is not really a
6382 protocol, but a category of Object. O well... */
6384 -(NSUInteger) draggingEntered: (id <NSDraggingInfo>) sender
6386 NSTRACE (draggingEntered);
6387 return NSDragOperationGeneric;
6391 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
6397 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
6402 NSEvent *theEvent = [[self window] currentEvent];
6405 NSTRACE (performDragOperation);
6410 position = [self convertPoint: [sender draggingLocation] fromView: nil];
6411 x = lrint (position.x); y = lrint (position.y);
6413 pb = [sender draggingPasteboard];
6414 type = [pb availableTypeFromArray: ns_drag_types];
6419 else if ([type isEqualToString: NSFilenamesPboardType])
6422 NSEnumerator *fenum;
6425 if (!(files = [pb propertyListForType: type]))
6428 fenum = [files objectEnumerator];
6429 while ( (file = [fenum nextObject]) )
6431 emacs_event->kind = NS_NONKEY_EVENT;
6432 emacs_event->code = KEY_NS_DRAG_FILE;
6433 XSETINT (emacs_event->x, x);
6434 XSETINT (emacs_event->y, y);
6435 ns_input_file = append2 (ns_input_file,
6436 build_string ([file UTF8String]));
6437 emacs_event->modifiers = EV_MODIFIERS (theEvent);
6438 EV_TRAILER (theEvent);
6442 else if ([type isEqualToString: NSURLPboardType])
6447 if (!(fileURL = [NSURL URLFromPasteboard: pb]) ||
6448 [fileURL isFileURL] == NO)
6451 file = [fileURL path];
6452 emacs_event->kind = NS_NONKEY_EVENT;
6453 emacs_event->code = KEY_NS_DRAG_FILE;
6454 XSETINT (emacs_event->x, x);
6455 XSETINT (emacs_event->y, y);
6456 ns_input_file = append2 (ns_input_file, build_string ([file UTF8String]));
6457 emacs_event->modifiers = EV_MODIFIERS (theEvent);
6458 EV_TRAILER (theEvent);
6461 else if ([type isEqualToString: NSStringPboardType]
6462 || [type isEqualToString: NSTabularTextPboardType])
6466 if (! (data = [pb stringForType: type]))
6469 emacs_event->kind = NS_NONKEY_EVENT;
6470 emacs_event->code = KEY_NS_DRAG_TEXT;
6471 XSETINT (emacs_event->x, x);
6472 XSETINT (emacs_event->y, y);
6473 ns_input_text = build_string ([data UTF8String]);
6474 emacs_event->modifiers = EV_MODIFIERS (theEvent);
6475 EV_TRAILER (theEvent);
6478 else if ([type isEqualToString: NSColorPboardType])
6480 NSColor *c = [NSColor colorFromPasteboard: pb];
6481 emacs_event->kind = NS_NONKEY_EVENT;
6482 emacs_event->code = KEY_NS_DRAG_COLOR;
6483 XSETINT (emacs_event->x, x);
6484 XSETINT (emacs_event->y, y);
6485 ns_input_color = ns_color_to_lisp (c);
6486 emacs_event->modifiers = EV_MODIFIERS (theEvent);
6487 EV_TRAILER (theEvent);
6490 else if ([type isEqualToString: NSFontPboardType])
6492 /* impl based on GNUstep NSTextView.m */
6493 NSData *data = [pb dataForType: NSFontPboardType];
6494 NSDictionary *dict = [NSUnarchiver unarchiveObjectWithData: data];
6495 NSFont *font = [dict objectForKey: NSFontAttributeName];
6501 emacs_event->kind = NS_NONKEY_EVENT;
6502 emacs_event->code = KEY_NS_CHANGE_FONT;
6503 XSETINT (emacs_event->x, x);
6504 XSETINT (emacs_event->y, y);
6505 ns_input_font = build_string ([[font fontName] UTF8String]);
6506 snprintf (fontSize, 10, "%f", [font pointSize]);
6507 ns_input_fontsize = build_string (fontSize);
6508 emacs_event->modifiers = EV_MODIFIERS (theEvent);
6509 EV_TRAILER (theEvent);
6514 error ("Invalid data type in dragging pasteboard.");
6520 - (id) validRequestorForSendType: (NSString *)typeSent
6521 returnType: (NSString *)typeReturned
6523 NSTRACE (validRequestorForSendType);
6524 if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
6525 && typeReturned == nil)
6527 if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
6531 return [super validRequestorForSendType: typeSent
6532 returnType: typeReturned];
6536 /* The next two methods are part of NSServicesRequests informal protocol,
6537 supposedly called when a services menu item is chosen from this app.
6538 But this should not happen because we override the services menu with our
6539 own entries which call ns-perform-service.
6540 Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
6541 So let's at least stub them out until further investigation can be done. */
6543 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
6545 /* we could call ns_string_from_pasteboard(pboard) here but then it should
6546 be written into the buffer in place of the existing selection..
6547 ordinary service calls go through functions defined in ns-win.el */
6551 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
6553 NSArray *typesDeclared;
6556 /* We only support NSStringPboardType */
6557 if ([types containsObject:NSStringPboardType] == NO) {
6561 val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
6562 if (CONSP (val) && SYMBOLP (XCAR (val)))
6565 if (CONSP (val) && NILP (XCDR (val)))
6568 if (! STRINGP (val))
6571 typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
6572 [pb declareTypes:typesDeclared owner:nil];
6573 ns_string_to_pasteboard (pb, val);
6578 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
6579 (gives a miniaturized version of the window); currently we use the latter for
6580 frames whose active buffer doesn't correspond to any file
6581 (e.g., '*scratch*') */
6582 - setMiniwindowImage: (BOOL) setMini
6584 id image = [[self window] miniwindowImage];
6585 NSTRACE (setMiniwindowImage);
6587 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
6588 about "AppleDockIconEnabled" notwithstanding, however the set message
6589 below has its effect nonetheless. */
6590 if (image != emacsframe->output_data.ns->miniimage)
6592 if (image && [image isKindOfClass: [EmacsImage class]])
6594 [[self window] setMiniwindowImage:
6595 setMini ? emacsframe->output_data.ns->miniimage : nil];
6602 - (void) setRows: (int) r andColumns: (int) c
6608 @end /* EmacsView */
6612 /* ==========================================================================
6614 EmacsWindow implementation
6616 ========================================================================== */
6618 @implementation EmacsWindow
6620 #ifdef NS_IMPL_COCOA
6621 - (id)accessibilityAttributeValue:(NSString *)attribute
6623 Lisp_Object str = Qnil;
6624 struct frame *f = SELECTED_FRAME ();
6625 struct buffer *curbuf = XBUFFER (XWINDOW (f->selected_window)->contents);
6627 if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
6628 return NSAccessibilityTextFieldRole;
6630 if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]
6631 && curbuf && ! NILP (BVAR (curbuf, mark_active)))
6633 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
6635 else if (curbuf && [attribute isEqualToString:NSAccessibilityValueAttribute])
6637 if (! NILP (BVAR (curbuf, mark_active)))
6638 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
6642 ptrdiff_t start_byte = BUF_BEGV_BYTE (curbuf);
6643 ptrdiff_t byte_range = BUF_ZV_BYTE (curbuf) - start_byte;
6644 ptrdiff_t range = BUF_ZV (curbuf) - BUF_BEGV (curbuf);
6646 if (! NILP (BVAR (curbuf, enable_multibyte_characters)))
6647 str = make_uninit_multibyte_string (range, byte_range);
6649 str = make_uninit_string (range);
6650 /* To check: This returns emacs-utf-8, which is a superset of utf-8.
6651 Is this a problem? */
6652 memcpy (SDATA (str), BYTE_POS_ADDR (start_byte), byte_range);
6659 if (CONSP (str) && SYMBOLP (XCAR (str)))
6662 if (CONSP (str) && NILP (XCDR (str)))
6667 const char *utfStr = SSDATA (str);
6668 NSString *nsStr = [NSString stringWithUTF8String: utfStr];
6673 return [super accessibilityAttributeValue:attribute];
6675 #endif /* NS_IMPL_COCOA */
6677 /* If we have multiple monitors, one above the other, we don't want to
6678 restrict the height to just one monitor. So we override this. */
6679 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
6681 /* When making the frame visible for the first time or if there is just
6682 one screen, we want to constrain. Other times not. */
6683 NSUInteger nr_screens = [[NSScreen screens] count];
6684 struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
6685 NSTRACE (constrainFrameRect);
6687 if (nr_screens == 1)
6689 NSRect r = [super constrainFrameRect:frameRect toScreen:screen];
6693 if (f->output_data.ns->dont_constrain
6694 || ns_menu_bar_should_be_hidden ())
6697 f->output_data.ns->dont_constrain = 1;
6698 return [super constrainFrameRect:frameRect toScreen:screen];
6701 @end /* EmacsWindow */
6704 @implementation EmacsFSWindow
6706 - (BOOL)canBecomeKeyWindow
6711 - (BOOL)canBecomeMainWindow
6718 /* ==========================================================================
6720 EmacsScroller implementation
6722 ========================================================================== */
6725 @implementation EmacsScroller
6727 /* for repeat button push */
6728 #define SCROLL_BAR_FIRST_DELAY 0.5
6729 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
6731 + (CGFloat) scrollerWidth
6733 /* TODO: if we want to allow variable widths, this is the place to do it,
6734 however neither GNUstep nor Cocoa support it very well */
6735 return [NSScroller scrollerWidth];
6739 - initFrame: (NSRect )r window: (Lisp_Object)nwin
6741 NSTRACE (EmacsScroller_initFrame);
6743 r.size.width = [EmacsScroller scrollerWidth];
6744 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
6745 [self setContinuous: YES];
6746 [self setEnabled: YES];
6748 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
6749 locked against the top and bottom edges, and right edge on OS X, where
6750 scrollers are on right. */
6751 #ifdef NS_IMPL_GNUSTEP
6752 [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
6754 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
6759 pixel_height = NSHeight (r);
6760 if (pixel_height == 0) pixel_height = 1;
6761 min_portion = 20 / pixel_height;
6763 frame = XFRAME (XWINDOW (win)->frame);
6764 if (FRAME_LIVE_P (frame))
6767 EmacsView *view = FRAME_NS_VIEW (frame);
6768 NSView *sview = [[view window] contentView];
6769 NSArray *subs = [sview subviews];
6771 /* disable optimization stopping redraw of other scrollbars */
6772 view->scrollbarsNeedingUpdate = 0;
6773 for (i =[subs count]-1; i >= 0; i--)
6774 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
6775 view->scrollbarsNeedingUpdate++;
6776 [sview addSubview: self];
6779 /* [self setFrame: r]; */
6785 - (void)setFrame: (NSRect)newRect
6787 NSTRACE (EmacsScroller_setFrame);
6788 /* block_input (); */
6789 pixel_height = NSHeight (newRect);
6790 if (pixel_height == 0) pixel_height = 1;
6791 min_portion = 20 / pixel_height;
6792 [super setFrame: newRect];
6794 /* unblock_input (); */
6800 NSTRACE (EmacsScroller_dealloc);
6802 wset_vertical_scroll_bar (XWINDOW (win), Qnil);
6830 /* ensure other scrollbar updates after deletion */
6831 view = (EmacsView *)FRAME_NS_VIEW (frame);
6833 view->scrollbarsNeedingUpdate++;
6834 [self removeFromSuperview];
6842 - (void)resetCursorRects
6844 NSRect visible = [self visibleRect];
6845 NSTRACE (resetCursorRects);
6847 if (!NSIsEmptyRect (visible))
6848 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
6849 [[NSCursor arrowCursor] setOnMouseEntered: YES];
6853 - (int) checkSamePosition: (int) position portion: (int) portion
6856 return em_position ==position && em_portion ==portion && em_whole ==whole
6857 && portion != whole; /* needed for resize empty buf */
6861 - setPosition: (int)position portion: (int)portion whole: (int)whole
6863 NSTRACE (setPosition);
6865 em_position = position;
6866 em_portion = portion;
6869 if (portion >= whole)
6871 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
6872 [self setKnobProportion: 1.0];
6873 [self setDoubleValue: 1.0];
6875 [self setFloatValue: 0.0 knobProportion: 1.0];
6881 portion = max ((float)whole*min_portion/pixel_height, portion);
6882 pos = (float)position / (whole - portion);
6883 por = (float)portion/whole;
6884 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
6885 [self setKnobProportion: por];
6886 [self setDoubleValue: pos];
6888 [self setFloatValue: pos knobProportion: por];
6892 /* Events may come here even if the event loop is not running.
6893 If we don't enter the event loop, the scroll bar will not update.
6894 So send SIGIO to ourselves. */
6895 if (apploopnr == 0) raise (SIGIO);
6900 /* FIXME: unused at moment (see ns_mouse_position) at the moment because
6901 drag events will go directly to the EmacsScroller. Leaving in for now. */
6902 -(void)getMouseMotionPart: (int *)part window: (Lisp_Object *)window
6903 x: (Lisp_Object *)x y: ( Lisp_Object *)y
6905 *part = last_hit_part;
6907 XSETINT (*y, pixel_height);
6908 if ([self floatValue] > 0.999)
6909 XSETINT (*x, pixel_height);
6911 XSETINT (*x, pixel_height * [self floatValue]);
6915 /* set up emacs_event */
6916 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
6921 emacs_event->part = last_hit_part;
6922 emacs_event->code = 0;
6923 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
6924 emacs_event->frame_or_window = win;
6925 emacs_event->timestamp = EV_TIMESTAMP (e);
6926 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
6927 emacs_event->arg = Qnil;
6928 XSETINT (emacs_event->x, loc * pixel_height);
6929 XSETINT (emacs_event->y, pixel_height-20);
6933 n_emacs_events_pending++;
6934 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
6937 hold_event (emacs_event);
6938 EVENT_INIT (*emacs_event);
6939 ns_send_appdefined (-1);
6943 /* called manually thru timer to implement repeated button action w/hold-down */
6944 - repeatScroll: (NSTimer *)scrollEntry
6946 NSEvent *e = [[self window] currentEvent];
6947 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
6948 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
6950 /* clear timer if need be */
6951 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
6953 [scroll_repeat_entry invalidate];
6954 [scroll_repeat_entry release];
6955 scroll_repeat_entry = nil;
6961 = [[NSTimer scheduledTimerWithTimeInterval:
6962 SCROLL_BAR_CONTINUOUS_DELAY
6964 selector: @selector (repeatScroll:)
6970 [self sendScrollEventAtLoc: 0 fromEvent: e];
6975 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
6976 mouseDragged events without going into a modal loop. */
6977 - (void)mouseDown: (NSEvent *)e
6980 /* hitPart is only updated AFTER event is passed on */
6981 NSScrollerPart part = [self testPart: [e locationInWindow]];
6982 double inc = 0.0, loc, kloc, pos;
6985 NSTRACE (EmacsScroller_mouseDown);
6989 case NSScrollerDecrementPage:
6990 last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
6991 case NSScrollerIncrementPage:
6992 last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
6993 case NSScrollerDecrementLine:
6994 last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
6995 case NSScrollerIncrementLine:
6996 last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
6997 case NSScrollerKnob:
6998 last_hit_part = scroll_bar_handle; break;
6999 case NSScrollerKnobSlot: /* GNUstep-only */
7000 last_hit_part = scroll_bar_move_ratio; break;
7001 default: /* NSScrollerNoPart? */
7002 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
7009 pos = 0; /* ignored */
7011 /* set a timer to repeat, as we can't let superclass do this modally */
7013 = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
7015 selector: @selector (repeatScroll:)
7022 /* handle, or on GNUstep possibly slot */
7023 NSEvent *fake_event;
7025 /* compute float loc in slot and mouse offset on knob */
7026 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
7028 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
7034 else if (loc >= NSHeight (sr))
7036 loc = NSHeight (sr);
7044 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
7046 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
7048 last_mouse_offset = kloc;
7050 /* if knob, tell emacs a location offset by knob pos
7051 (to indicate top of handle) */
7052 if (part == NSScrollerKnob)
7053 pos = (loc - last_mouse_offset) / NSHeight (sr);
7055 /* else this is a slot click on GNUstep: go straight there */
7056 pos = loc / NSHeight (sr);
7058 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
7059 fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
7060 location: [e locationInWindow]
7061 modifierFlags: [e modifierFlags]
7062 timestamp: [e timestamp]
7063 windowNumber: [e windowNumber]
7064 context: [e context]
7065 eventNumber: [e eventNumber]
7066 clickCount: [e clickCount]
7067 pressure: [e pressure]];
7068 [super mouseUp: fake_event];
7071 if (part != NSScrollerKnob)
7072 [self sendScrollEventAtLoc: pos fromEvent: e];
7076 /* Called as we manually track scroller drags, rather than superclass. */
7077 - (void)mouseDragged: (NSEvent *)e
7083 NSTRACE (EmacsScroller_mouseDragged);
7085 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
7087 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
7094 else if (loc >= NSHeight (sr) + last_mouse_offset)
7096 loc = NSHeight (sr) + last_mouse_offset;
7100 pos = /*(edge ? loc :*/ (loc - last_mouse_offset) / NSHeight (sr);
7101 [self sendScrollEventAtLoc: pos fromEvent: e];
7105 - (void)mouseUp: (NSEvent *)e
7107 if (scroll_repeat_entry)
7109 [scroll_repeat_entry invalidate];
7110 [scroll_repeat_entry release];
7111 scroll_repeat_entry = nil;
7117 /* treat scrollwheel events in the bar as though they were in the main window */
7118 - (void) scrollWheel: (NSEvent *)theEvent
7120 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
7121 [view mouseDown: theEvent];
7124 @end /* EmacsScroller */
7129 /* ==========================================================================
7131 Font-related functions; these used to be in nsfaces.m
7133 ========================================================================== */
7137 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
7139 struct font *font = XFONT_OBJECT (font_object);
7142 fontset = fontset_from_font (font_object);
7143 FRAME_FONTSET (f) = fontset;
7145 if (FRAME_FONT (f) == font)
7146 /* This font is already set in frame F. There's nothing more to
7150 FRAME_FONT (f) = font;
7152 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
7153 FRAME_COLUMN_WIDTH (f) = font->average_width;
7154 FRAME_LINE_HEIGHT (f) = font->height;
7156 compute_fringe_widths (f, 1);
7158 /* Compute the scroll bar width in character columns. */
7159 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
7161 int wid = FRAME_COLUMN_WIDTH (f);
7162 FRAME_CONFIG_SCROLL_BAR_COLS (f)
7163 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
7167 int wid = FRAME_COLUMN_WIDTH (f);
7168 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
7171 /* Now make the frame display the given font. */
7172 if (FRAME_NS_WINDOW (f) != 0)
7173 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
7179 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
7180 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
7184 ns_xlfd_to_fontname (const char *xlfd)
7185 /* --------------------------------------------------------------------------
7186 Convert an X font name (XLFD) to an NS font name.
7187 Only family is used.
7188 The string returned is temporarily allocated.
7189 -------------------------------------------------------------------------- */
7191 char *name = xmalloc (180);
7195 if (!strncmp (xlfd, "--", 2))
7196 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
7198 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
7200 /* stopgap for malformed XLFD input */
7201 if (strlen (name) == 0)
7202 strcpy (name, "Monaco");
7204 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
7205 also uppercase after '-' or ' ' */
7206 name[0] = c_toupper (name[0]);
7207 for (len =strlen (name), i =0; i<len; i++)
7213 name[i+1] = c_toupper (name[i+1]);
7215 else if (name[i] == '_')
7219 name[i+1] = c_toupper (name[i+1]);
7222 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
7223 ret = [[NSString stringWithUTF8String: name] UTF8String];
7230 syms_of_nsterm (void)
7232 NSTRACE (syms_of_nsterm);
7234 ns_antialias_threshold = 10.0;
7236 /* from 23+ we need to tell emacs what modifiers there are.. */
7237 DEFSYM (Qmodifier_value, "modifier-value");
7238 DEFSYM (Qalt, "alt");
7239 DEFSYM (Qhyper, "hyper");
7240 DEFSYM (Qmeta, "meta");
7241 DEFSYM (Qsuper, "super");
7242 DEFSYM (Qcontrol, "control");
7243 DEFSYM (QUTF8_STRING, "UTF8_STRING");
7245 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
7246 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
7247 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
7248 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
7249 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
7251 DEFVAR_LISP ("ns-input-file", ns_input_file,
7252 "The file specified in the last NS event.");
7253 ns_input_file =Qnil;
7255 DEFVAR_LISP ("ns-input-text", ns_input_text,
7256 "The data received in the last NS text drag event.");
7257 ns_input_text =Qnil;
7259 DEFVAR_LISP ("ns-working-text", ns_working_text,
7260 "String for visualizing working composition sequence.");
7261 ns_working_text =Qnil;
7263 DEFVAR_LISP ("ns-input-font", ns_input_font,
7264 "The font specified in the last NS event.");
7265 ns_input_font =Qnil;
7267 DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
7268 "The fontsize specified in the last NS event.");
7269 ns_input_fontsize =Qnil;
7271 DEFVAR_LISP ("ns-input-line", ns_input_line,
7272 "The line specified in the last NS event.");
7273 ns_input_line =Qnil;
7275 DEFVAR_LISP ("ns-input-color", ns_input_color,
7276 "The color specified in the last NS event.");
7277 ns_input_color =Qnil;
7279 DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
7280 "The service name specified in the last NS event.");
7281 ns_input_spi_name =Qnil;
7283 DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
7284 "The service argument specified in the last NS event.");
7285 ns_input_spi_arg =Qnil;
7287 DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
7288 "This variable describes the behavior of the alternate or option key.\n\
7289 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7290 Set to none means that the alternate / option key is not interpreted by Emacs\n\
7291 at all, allowing it to be used at a lower level for accented character entry.");
7292 ns_alternate_modifier = Qmeta;
7294 DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
7295 "This variable describes the behavior of the right alternate or option key.\n\
7296 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7297 Set to left means be the same key as `ns-alternate-modifier'.\n\
7298 Set to none means that the alternate / option key is not interpreted by Emacs\n\
7299 at all, allowing it to be used at a lower level for accented character entry.");
7300 ns_right_alternate_modifier = Qleft;
7302 DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
7303 "This variable describes the behavior of the command key.\n\
7304 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
7305 ns_command_modifier = Qsuper;
7307 DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
7308 "This variable describes the behavior of the right command key.\n\
7309 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7310 Set to left means be the same key as `ns-command-modifier'.\n\
7311 Set to none means that the command / option key is not interpreted by Emacs\n\
7312 at all, allowing it to be used at a lower level for accented character entry.");
7313 ns_right_command_modifier = Qleft;
7315 DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
7316 "This variable describes the behavior of the control key.\n\
7317 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
7318 ns_control_modifier = Qcontrol;
7320 DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
7321 "This variable describes the behavior of the right control key.\n\
7322 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7323 Set to left means be the same key as `ns-control-modifier'.\n\
7324 Set to none means that the control / option key is not interpreted by Emacs\n\
7325 at all, allowing it to be used at a lower level for accented character entry.");
7326 ns_right_control_modifier = Qleft;
7328 DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
7329 "This variable describes the behavior of the function key (on laptops).\n\
7330 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7331 Set to none means that the function key is not interpreted by Emacs at all,\n\
7332 allowing it to be used at a lower level for accented character entry.");
7333 ns_function_modifier = Qnone;
7335 DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
7336 "Non-nil (the default) means to render text antialiased.");
7337 ns_antialias_text = Qt;
7339 DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
7340 "Whether to confirm application quit using dialog.");
7341 ns_confirm_quit = Qnil;
7343 staticpro (&ns_display_name_list);
7344 ns_display_name_list = Qnil;
7346 staticpro (&last_mouse_motion_frame);
7347 last_mouse_motion_frame = Qnil;
7349 DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
7350 doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
7351 Only works on OSX 10.6 or later. */);
7352 ns_auto_hide_menu_bar = Qnil;
7354 DEFVAR_BOOL ("ns-use-native-fullscreen", ns_use_native_fullscreen,
7355 doc: /*Non-nil means to use native fullscreen on OSX >= 10.7.
7356 Nil means use fullscreen the old (< 10.7) way. The old way works better with
7357 multiple monitors, but lacks tool bar. This variable is ignored on OSX < 10.7.
7358 Default is t for OSX >= 10.7, nil otherwise. */);
7359 #ifdef HAVE_NATIVE_FS
7360 ns_use_native_fullscreen = YES;
7362 ns_use_native_fullscreen = NO;
7364 ns_last_use_native_fullscreen = ns_use_native_fullscreen;
7366 /* TODO: move to common code */
7367 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
7368 doc: /* Which toolkit scroll bars Emacs uses, if any.
7369 A value of nil means Emacs doesn't use toolkit scroll bars.
7370 With the X Window system, the value is a symbol describing the
7371 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
7372 With MS Windows or Nextstep, the value is t. */);
7373 Vx_toolkit_scroll_bars = Qt;
7375 DEFVAR_BOOL ("x-use-underline-position-properties",
7376 x_use_underline_position_properties,
7377 doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
7378 A value of nil means ignore them. If you encounter fonts with bogus
7379 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
7380 to 4.1, set this to nil. */);
7381 x_use_underline_position_properties = 0;
7383 DEFVAR_BOOL ("x-underline-at-descent-line",
7384 x_underline_at_descent_line,
7385 doc: /* Non-nil means to draw the underline at the same place as the descent line.
7386 A value of nil means to draw the underline according to the value of the
7387 variable `x-use-underline-position-properties', which is usually at the
7388 baseline level. The default value is nil. */);
7389 x_underline_at_descent_line = 0;
7391 /* Tell emacs about this window system. */
7392 Fprovide (intern ("ns"), Qnil);