1 /* NeXT/Open/GNUstep / MacOSX communication module. -*- coding: utf-8 -*-
3 Copyright (C) 1989, 1993-1994, 2005-2006, 2008-2015 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"
63 #ifdef NS_IMPL_GNUSTEP
72 extern NSString *NSMenuDidBeginTrackingNotification;
77 int nstrace_depth = 0;
79 /* Called when nstrace_enabled goes out of scope. */
80 void nstrace_leave(int * pointer_to_nstrace_enabled)
82 if (*pointer_to_nstrace_enabled)
89 void ns_print_fullscreen_type_name (char const * s, int fs_type)
91 // This is a support function for the NSTRACE system, don't add a
92 // NSTRACE () here. However, a local `nstrace_enabled' variable is
93 // needed by the NSTRACE_MSG macros.
94 int nstrace_enabled = 1;
99 NSTRACE_MSG ("%s: FULLSCREEN_NONE", s);
102 case FULLSCREEN_WIDTH:
103 NSTRACE_MSG ("%s: FULLSCREEN_WIDTH", s);
106 case FULLSCREEN_HEIGHT:
107 NSTRACE_MSG ("%s: FULLSCREEN_HEIGHT", s);
110 case FULLSCREEN_BOTH:
111 NSTRACE_MSG ("%s: FULLSCREEN_BOTH", s);
114 case FULLSCREEN_MAXIMIZED:
115 NSTRACE_MSG ("%s: FULLSCREEN_MAXIMIZED", s);
119 NSTRACE_MSG ("%s: %d", s, fs_type);
126 /* ==========================================================================
128 NSColor, EmacsColor category.
130 ========================================================================== */
131 @implementation NSColor (EmacsColor)
132 + (NSColor *)colorForEmacsRed:(CGFloat)red green:(CGFloat)green
133 blue:(CGFloat)blue alpha:(CGFloat)alpha
136 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
137 if (ns_use_srgb_colorspace)
138 return [NSColor colorWithSRGBRed: red
144 return [NSColor colorWithCalibratedRed: red
150 - (NSColor *)colorUsingDefaultColorSpace
153 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
154 if (ns_use_srgb_colorspace)
155 return [self colorUsingColorSpace: [NSColorSpace sRGBColorSpace]];
158 return [self colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
163 /* ==========================================================================
167 ========================================================================== */
169 /* Convert a symbol indexed with an NSxxx value to a value as defined
170 in keyboard.c (lispy_function_key). I hope this is a correct way
171 of doing things... */
172 static unsigned convert_ns_to_X_keysym[] =
174 NSHomeFunctionKey, 0x50,
175 NSLeftArrowFunctionKey, 0x51,
176 NSUpArrowFunctionKey, 0x52,
177 NSRightArrowFunctionKey, 0x53,
178 NSDownArrowFunctionKey, 0x54,
179 NSPageUpFunctionKey, 0x55,
180 NSPageDownFunctionKey, 0x56,
181 NSEndFunctionKey, 0x57,
182 NSBeginFunctionKey, 0x58,
183 NSSelectFunctionKey, 0x60,
184 NSPrintFunctionKey, 0x61,
185 NSClearLineFunctionKey, 0x0B,
186 NSExecuteFunctionKey, 0x62,
187 NSInsertFunctionKey, 0x63,
188 NSUndoFunctionKey, 0x65,
189 NSRedoFunctionKey, 0x66,
190 NSMenuFunctionKey, 0x67,
191 NSFindFunctionKey, 0x68,
192 NSHelpFunctionKey, 0x6A,
193 NSBreakFunctionKey, 0x6B,
195 NSF1FunctionKey, 0xBE,
196 NSF2FunctionKey, 0xBF,
197 NSF3FunctionKey, 0xC0,
198 NSF4FunctionKey, 0xC1,
199 NSF5FunctionKey, 0xC2,
200 NSF6FunctionKey, 0xC3,
201 NSF7FunctionKey, 0xC4,
202 NSF8FunctionKey, 0xC5,
203 NSF9FunctionKey, 0xC6,
204 NSF10FunctionKey, 0xC7,
205 NSF11FunctionKey, 0xC8,
206 NSF12FunctionKey, 0xC9,
207 NSF13FunctionKey, 0xCA,
208 NSF14FunctionKey, 0xCB,
209 NSF15FunctionKey, 0xCC,
210 NSF16FunctionKey, 0xCD,
211 NSF17FunctionKey, 0xCE,
212 NSF18FunctionKey, 0xCF,
213 NSF19FunctionKey, 0xD0,
214 NSF20FunctionKey, 0xD1,
215 NSF21FunctionKey, 0xD2,
216 NSF22FunctionKey, 0xD3,
217 NSF23FunctionKey, 0xD4,
218 NSF24FunctionKey, 0xD5,
220 NSBackspaceCharacter, 0x08, /* 8: Not on some KBs. */
221 NSDeleteCharacter, 0xFF, /* 127: Big 'delete' key upper right. */
222 NSDeleteFunctionKey, 0x9F, /* 63272: Del forw key off main array. */
224 NSTabCharacter, 0x09,
225 0x19, 0x09, /* left tab->regular since pass shift */
226 NSCarriageReturnCharacter, 0x0D,
227 NSNewlineCharacter, 0x0D,
228 NSEnterCharacter, 0x8D,
230 0x41|NSNumericPadKeyMask, 0xAE, /* KP_Decimal */
231 0x43|NSNumericPadKeyMask, 0xAA, /* KP_Multiply */
232 0x45|NSNumericPadKeyMask, 0xAB, /* KP_Add */
233 0x4B|NSNumericPadKeyMask, 0xAF, /* KP_Divide */
234 0x4E|NSNumericPadKeyMask, 0xAD, /* KP_Subtract */
235 0x51|NSNumericPadKeyMask, 0xBD, /* KP_Equal */
236 0x52|NSNumericPadKeyMask, 0xB0, /* KP_0 */
237 0x53|NSNumericPadKeyMask, 0xB1, /* KP_1 */
238 0x54|NSNumericPadKeyMask, 0xB2, /* KP_2 */
239 0x55|NSNumericPadKeyMask, 0xB3, /* KP_3 */
240 0x56|NSNumericPadKeyMask, 0xB4, /* KP_4 */
241 0x57|NSNumericPadKeyMask, 0xB5, /* KP_5 */
242 0x58|NSNumericPadKeyMask, 0xB6, /* KP_6 */
243 0x59|NSNumericPadKeyMask, 0xB7, /* KP_7 */
244 0x5B|NSNumericPadKeyMask, 0xB8, /* KP_8 */
245 0x5C|NSNumericPadKeyMask, 0xB9, /* KP_9 */
247 0x1B, 0x1B /* escape */
250 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
251 the maximum font size to NOT antialias. On GNUstep there is currently
252 no way to control this behavior. */
253 float ns_antialias_threshold;
255 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
256 NSString *ns_app_name = @"Emacs"; /* default changed later */
258 /* Display variables */
259 struct ns_display_info *x_display_list; /* Chain of existing displays */
260 long context_menu_value = 0;
263 static struct frame *ns_updating_frame;
264 static NSView *focus_view = NULL;
265 static int ns_window_num = 0;
266 #ifdef NS_IMPL_GNUSTEP
267 static NSRect uRect; // TODO: This is dead, remove it?
269 static BOOL gsaved = NO;
270 static BOOL ns_fake_keydown = NO;
272 static BOOL ns_menu_bar_is_hidden = NO;
274 /*static int debug_lock = 0; */
277 static BOOL send_appdefined = YES;
278 #define NO_APPDEFINED_DATA (-8)
279 static int last_appdefined_event_data = NO_APPDEFINED_DATA;
280 static NSTimer *timed_entry = 0;
281 static NSTimer *scroll_repeat_entry = nil;
282 static fd_set select_readfds, select_writefds;
283 enum { SELECT_HAVE_READ = 1, SELECT_HAVE_WRITE = 2, SELECT_HAVE_TMO = 4 };
284 static int select_nfds = 0, select_valid = 0;
285 static struct timespec select_timeout = { 0, 0 };
286 static int selfds[2] = { -1, -1 };
287 static pthread_mutex_t select_mutex;
288 static int apploopnr = 0;
289 static NSAutoreleasePool *outerpool;
290 static struct input_event *emacs_event = NULL;
291 static struct input_event *q_event_ptr = NULL;
292 static int n_emacs_events_pending = 0;
293 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
294 *ns_pending_service_args;
295 static BOOL ns_do_open_file = NO;
296 static BOOL ns_last_use_native_fullscreen;
298 /* Non-zero means that a HELP_EVENT has been generated since Emacs
301 static BOOL any_help_event_p = NO;
304 struct input_event *q;
310 static NSString *represented_filename = nil;
311 static struct frame *represented_frame = 0;
315 * State for pending menu activation:
316 * MENU_NONE Normal state
317 * MENU_PENDING A menu has been clicked on, but has been canceled so we can
318 * run lisp to update the menu.
319 * MENU_OPENING Menu is up to date, and the click event is redone so the menu
323 #define MENU_PENDING 1
324 #define MENU_OPENING 2
325 static int menu_will_open_state = MENU_NONE;
327 /* Saved position for menu click. */
328 static CGPoint menu_mouse_point;
331 /* Convert modifiers in a NeXTstep event to emacs style modifiers. */
332 #define NS_FUNCTION_KEY_MASK 0x800000
333 #define NSLeftControlKeyMask (0x000001 | NSControlKeyMask)
334 #define NSRightControlKeyMask (0x002000 | NSControlKeyMask)
335 #define NSLeftCommandKeyMask (0x000008 | NSCommandKeyMask)
336 #define NSRightCommandKeyMask (0x000010 | NSCommandKeyMask)
337 #define NSLeftAlternateKeyMask (0x000020 | NSAlternateKeyMask)
338 #define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
339 #define EV_MODIFIERS2(flags) \
340 (((flags & NSHelpKeyMask) ? \
341 hyper_modifier : 0) \
342 | (!EQ (ns_right_alternate_modifier, Qleft) && \
343 ((flags & NSRightAlternateKeyMask) \
344 == NSRightAlternateKeyMask) ? \
345 parse_solitary_modifier (ns_right_alternate_modifier) : 0) \
346 | ((flags & NSAlternateKeyMask) ? \
347 parse_solitary_modifier (ns_alternate_modifier) : 0) \
348 | ((flags & NSShiftKeyMask) ? \
349 shift_modifier : 0) \
350 | (!EQ (ns_right_control_modifier, Qleft) && \
351 ((flags & NSRightControlKeyMask) \
352 == NSRightControlKeyMask) ? \
353 parse_solitary_modifier (ns_right_control_modifier) : 0) \
354 | ((flags & NSControlKeyMask) ? \
355 parse_solitary_modifier (ns_control_modifier) : 0) \
356 | ((flags & NS_FUNCTION_KEY_MASK) ? \
357 parse_solitary_modifier (ns_function_modifier) : 0) \
358 | (!EQ (ns_right_command_modifier, Qleft) && \
359 ((flags & NSRightCommandKeyMask) \
360 == NSRightCommandKeyMask) ? \
361 parse_solitary_modifier (ns_right_command_modifier) : 0) \
362 | ((flags & NSCommandKeyMask) ? \
363 parse_solitary_modifier (ns_command_modifier):0))
364 #define EV_MODIFIERS(e) EV_MODIFIERS2 ([e modifierFlags])
366 #define EV_UDMODIFIERS(e) \
367 ((([e type] == NSLeftMouseDown) ? down_modifier : 0) \
368 | (([e type] == NSRightMouseDown) ? down_modifier : 0) \
369 | (([e type] == NSOtherMouseDown) ? down_modifier : 0) \
370 | (([e type] == NSLeftMouseDragged) ? down_modifier : 0) \
371 | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
372 | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
373 | (([e type] == NSLeftMouseUp) ? up_modifier : 0) \
374 | (([e type] == NSRightMouseUp) ? up_modifier : 0) \
375 | (([e type] == NSOtherMouseUp) ? up_modifier : 0))
377 #define EV_BUTTON(e) \
378 ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 : \
379 (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
380 [e buttonNumber] - 1)
382 /* Convert the time field to a timestamp in milliseconds. */
383 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
385 /* This is a piece of code which is common to all the event handling
386 methods. Maybe it should even be a function. */
387 #define EV_TRAILER(e) \
389 XSETFRAME (emacs_event->frame_or_window, emacsframe); \
393 #define EV_TRAILER2(e) \
395 if (e) emacs_event->timestamp = EV_TIMESTAMP (e); \
398 Lisp_Object tem = Vinhibit_quit; \
399 Vinhibit_quit = Qt; \
400 n_emacs_events_pending++; \
401 kbd_buffer_store_event_hold (emacs_event, q_event_ptr); \
402 Vinhibit_quit = tem; \
405 hold_event (emacs_event); \
406 EVENT_INIT (*emacs_event); \
407 ns_send_appdefined (-1); \
410 /* TODO: get rid of need for these forward declarations */
411 static void ns_condemn_scroll_bars (struct frame *f);
412 static void ns_judge_scroll_bars (struct frame *f);
413 void x_set_frame_alpha (struct frame *f);
416 /* ==========================================================================
420 ========================================================================== */
423 ns_set_represented_filename (NSString* fstr, struct frame *f)
425 represented_filename = [fstr retain];
426 represented_frame = f;
430 ns_init_events (struct input_event* ev)
443 hold_event (struct input_event *event)
445 if (hold_event_q.nr == hold_event_q.cap)
447 if (hold_event_q.cap == 0) hold_event_q.cap = 10;
448 else hold_event_q.cap *= 2;
450 xrealloc (hold_event_q.q, hold_event_q.cap * sizeof *hold_event_q.q);
453 hold_event_q.q[hold_event_q.nr++] = *event;
454 /* Make sure ns_read_socket is called, i.e. we have input. */
456 send_appdefined = YES;
460 append2 (Lisp_Object list, Lisp_Object item)
461 /* --------------------------------------------------------------------------
462 Utility to append to a list
463 -------------------------------------------------------------------------- */
465 return CALLN (Fnconc, list, list1 (item));
470 ns_etc_directory (void)
471 /* If running as a self-contained app bundle, return as a string the
472 filename of the etc directory, if present; else nil. */
474 NSBundle *bundle = [NSBundle mainBundle];
475 NSString *resourceDir = [bundle resourcePath];
476 NSString *resourcePath;
477 NSFileManager *fileManager = [NSFileManager defaultManager];
480 resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
481 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
483 if (isDir) return [resourcePath UTF8String];
491 /* If running as a self-contained app bundle, return as a path string
492 the filenames of the libexec and bin directories, ie libexec:bin.
493 Otherwise, return nil.
494 Normally, Emacs does not add its own bin/ directory to the PATH.
495 However, a self-contained NS build has a different layout, with
496 bin/ and libexec/ subdirectories in the directory that contains
498 We put libexec first, because init_callproc_1 uses the first
499 element to initialize exec-directory. An alternative would be
500 for init_callproc to check for invocation-directory/libexec.
503 NSBundle *bundle = [NSBundle mainBundle];
504 NSString *resourceDir = [bundle resourcePath];
505 NSString *binDir = [bundle bundlePath];
506 NSString *resourcePath, *resourcePaths;
508 NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
509 NSFileManager *fileManager = [NSFileManager defaultManager];
511 NSEnumerator *pathEnum;
514 range = [resourceDir rangeOfString: @"Contents"];
515 if (range.location != NSNotFound)
517 binDir = [binDir stringByAppendingPathComponent: @"Contents"];
519 binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
523 paths = [binDir stringsByAppendingPaths:
524 [NSArray arrayWithObjects: @"libexec", @"bin", nil]];
525 pathEnum = [paths objectEnumerator];
528 while ((resourcePath = [pathEnum nextObject]))
530 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
533 if ([resourcePaths length] > 0)
535 = [resourcePaths stringByAppendingString: pathSeparator];
537 = [resourcePaths stringByAppendingString: resourcePath];
540 if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
548 /* If running as a self-contained app bundle, return as a path string
549 the filenames of the site-lisp and lisp directories.
550 Ie, site-lisp:lisp. Otherwise, return nil. */
552 NSBundle *bundle = [NSBundle mainBundle];
553 NSString *resourceDir = [bundle resourcePath];
554 NSString *resourcePath, *resourcePaths;
555 NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
556 NSFileManager *fileManager = [NSFileManager defaultManager];
558 NSArray *paths = [resourceDir stringsByAppendingPaths:
559 [NSArray arrayWithObjects:
560 @"site-lisp", @"lisp", nil]];
561 NSEnumerator *pathEnum = [paths objectEnumerator];
564 /* Hack to skip site-lisp. */
565 if (no_site_lisp) resourcePath = [pathEnum nextObject];
567 while ((resourcePath = [pathEnum nextObject]))
569 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
572 if ([resourcePaths length] > 0)
574 = [resourcePaths stringByAppendingString: pathSeparator];
576 = [resourcePaths stringByAppendingString: resourcePath];
579 if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
585 ns_timeout (int usecs)
586 /* --------------------------------------------------------------------------
587 Blocking timer utility used by ns_ring_bell
588 -------------------------------------------------------------------------- */
590 struct timespec wakeup = timespec_add (current_timespec (),
591 make_timespec (0, usecs * 1000));
593 /* Keep waiting until past the time wakeup. */
596 struct timespec timeout, now = current_timespec ();
597 if (timespec_cmp (wakeup, now) <= 0)
599 timeout = timespec_sub (wakeup, now);
601 /* Try to wait that long--but we might wake up sooner. */
602 pselect (0, NULL, NULL, NULL, &timeout, NULL);
608 ns_release_object (void *obj)
609 /* --------------------------------------------------------------------------
610 Release an object (callable from C)
611 -------------------------------------------------------------------------- */
618 ns_retain_object (void *obj)
619 /* --------------------------------------------------------------------------
620 Retain an object (callable from C)
621 -------------------------------------------------------------------------- */
628 ns_alloc_autorelease_pool (void)
629 /* --------------------------------------------------------------------------
630 Allocate a pool for temporary objects (callable from C)
631 -------------------------------------------------------------------------- */
633 return [[NSAutoreleasePool alloc] init];
638 ns_release_autorelease_pool (void *pool)
639 /* --------------------------------------------------------------------------
640 Free a pool and temporary objects it refers to (callable from C)
641 -------------------------------------------------------------------------- */
643 ns_release_object (pool);
647 /* True, if the menu bar should be hidden. */
650 ns_menu_bar_should_be_hidden (void)
652 return !NILP (ns_auto_hide_menu_bar)
653 && [NSApp respondsToSelector:@selector(setPresentationOptions:)];
658 ns_menu_bar_height (NSScreen *screen)
659 /* The height of the menu bar, if visible. */
661 // NSTRACE ("ns_menu_bar_height");
665 if (ns_menu_bar_should_be_hidden())
671 NSRect screenFrame = [screen frame];
672 NSRect screenVisibleFrame = [screen visibleFrame];
674 CGFloat frameTop = screenFrame.origin.y + screenFrame.size.height;
675 CGFloat visibleFrameTop = (screenVisibleFrame.origin.y
676 + screenVisibleFrame.size.height);
678 res = frameTop - visibleFrameTop;
682 // NSTRACE_MSG (NSTRACE_FMT_RETURN "%.0f", res);
688 /* ==========================================================================
690 Focus (clipping) and screen update
692 ========================================================================== */
695 // Window constraining
696 // -------------------
698 // To ensure that the windows are not placed under the menu bar, they
699 // are typically moved by the call-back constrainFrameRect. However,
700 // by overriding it, it's possible to inhibit this, leaving the window
701 // in it's original position.
703 // It's possible to hide the menu bar. However, technically, it's only
704 // possible to hide it when the application is active. To ensure that
705 // this work properly, the menu bar and window constraining are
706 // deferred until the application becomes active.
708 // Even though it's not possible to manually move a window above the
709 // top of the screen, it is allowed if it's done programmatically,
710 // when the menu is hidden. This allows the editable area to cover the
711 // full screen height.
716 // Use the following extra files:
719 // ;; Hide menu and place frame slightly above the top of the screen.
720 // (setq ns-auto-hide-menu-bar t)
721 // (set-frame-position (selected-frame) 0 -20)
725 // emacs -Q -l init.el
727 // Result: No menu bar, and the title bar should be above the screen.
733 // Result: Menu bar visible, frame placed immediately below the menu.
736 static NSRect constrain_frame_rect(NSRect frameRect)
738 NSTRACE ("constrain_frame_rect(" NSTRACE_FMT_RECT ")",
739 NSTRACE_ARG_RECT (frameRect));
741 // --------------------
742 // Collect information about the screen the frame is covering.
745 NSArray *screens = [NSScreen screens];
746 NSUInteger nr_screens = [screens count];
750 // The height of the menu bar, if present in any screen the frame is
752 int menu_bar_height = 0;
754 // A rectangle covering all the screen the frame is displayed in.
755 NSRect multiscreenRect = NSMakeRect(0, 0, 0, 0);
756 for (i = 0; i < nr_screens; ++i )
758 NSScreen *s = [screens objectAtIndex: i];
759 NSRect scrRect = [s frame];
761 NSTRACE_MSG ("Screen %d: " NSTRACE_FMT_RECT,
762 i, NSTRACE_ARG_RECT (scrRect));
764 if (NSIntersectionRect (frameRect, scrRect).size.height != 0)
766 multiscreenRect = NSUnionRect (multiscreenRect, scrRect);
768 menu_bar_height = max(menu_bar_height, ns_menu_bar_height (s));
772 NSTRACE_RECT ("multiscreenRect", multiscreenRect);
774 NSTRACE_MSG ("menu_bar_height: %d", menu_bar_height);
776 if (multiscreenRect.size.width == 0
777 || multiscreenRect.size.height == 0)
779 // Failed to find any monitor, give up.
780 NSTRACE_MSG ("multiscreenRect empty");
781 NSTRACE_RETURN_RECT (frameRect);
786 // --------------------
787 // Find a suitable placement.
790 if (ns_menu_bar_should_be_hidden())
792 // When the menu bar is hidden, the user may place part of the
793 // frame above the top of the screen, for example to hide the
796 // Hence, keep the original position.
800 // Ensure that the frame is below the menu bar, or below the top
803 // This assume that the menu bar is placed at the top in the
804 // rectangle that covers the monitors. (It doesn't have to be,
805 // but if it's not it's hard to do anything useful.)
806 CGFloat topOfWorkArea = (multiscreenRect.origin.y
807 + multiscreenRect.size.height
810 CGFloat topOfFrame = frameRect.origin.y + frameRect.size.height;
811 if (topOfFrame > topOfWorkArea)
813 frameRect.origin.y -= topOfFrame - topOfWorkArea;
814 NSTRACE_RECT ("After placement adjust", frameRect);
818 // Include the following section to restrict frame to the screens.
819 // (If so, update it to allow the frame to stretch down below the
822 // --------------------
823 // Ensure frame doesn't stretch below the screens.
826 CGFloat diff = multiscreenRect.origin.y - frameRect.origin.y;
830 frameRect.origin.y = multiscreenRect.origin.y;
831 frameRect.size.height -= diff;
835 NSTRACE_RETURN_RECT (frameRect);
841 ns_constrain_all_frames (void)
843 Lisp_Object tail, frame;
845 NSTRACE ("ns_constrain_all_frames");
849 FOR_EACH_FRAME (tail, frame)
851 struct frame *f = XFRAME (frame);
854 NSView *view = FRAME_NS_VIEW (f);
856 [[view window] setFrame:constrain_frame_rect([[view window] frame])
865 /* Show or hide the menu bar, based on user setting. */
868 ns_update_auto_hide_menu_bar (void)
871 NSTRACE ("ns_update_auto_hide_menu_bar");
875 if (NSApp != nil && [NSApp isActive])
877 // Note, "setPresentationOptions" triggers an error unless the
878 // application is active.
879 BOOL menu_bar_should_be_hidden = ns_menu_bar_should_be_hidden ();
881 if (menu_bar_should_be_hidden != ns_menu_bar_is_hidden)
883 NSApplicationPresentationOptions options
884 = NSApplicationPresentationDefault;
886 if (menu_bar_should_be_hidden)
887 options |= NSApplicationPresentationAutoHideMenuBar
888 | NSApplicationPresentationAutoHideDock;
890 [NSApp setPresentationOptions: options];
892 ns_menu_bar_is_hidden = menu_bar_should_be_hidden;
894 if (!ns_menu_bar_is_hidden)
896 ns_constrain_all_frames ();
907 ns_update_begin (struct frame *f)
908 /* --------------------------------------------------------------------------
909 Prepare for a grouped sequence of drawing calls
910 external (RIF) call; whole frame, called before update_window_begin
911 -------------------------------------------------------------------------- */
913 EmacsView *view = FRAME_NS_VIEW (f);
914 NSTRACE ("ns_update_begin");
916 ns_update_auto_hide_menu_bar ();
919 if ([view isFullscreen] && [view fsIsNative])
921 // Fix reappearing tool bar in fullscreen for OSX 10.7
922 BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (f) ? YES : NO;
923 NSToolbar *toolbar = [FRAME_NS_VIEW (f) toolbar];
924 if (! tbar_visible != ! [toolbar isVisible])
925 [toolbar setVisible: tbar_visible];
929 ns_updating_frame = f;
932 /* drawRect may have been called for say the minibuffer, and then clip path
933 is for the minibuffer. But the display engine may draw more because
934 we have set the frame as garbaged. So reset clip path to the whole
939 NSRect r = [view frame];
940 NSRect cr = [[view window] frame];
941 /* If a large frame size is set, r may be larger than the window frame
942 before constrained. In that case don't change the clip path, as we
943 will clear in to the tool bar and title bar. */
945 + FRAME_NS_TITLEBAR_HEIGHT (f)
946 + FRAME_TOOLBAR_HEIGHT (f) <= cr.size.height)
948 bp = [[NSBezierPath bezierPathWithRect: r] retain];
955 #ifdef NS_IMPL_GNUSTEP
956 uRect = NSMakeRect (0, 0, 0, 0);
962 ns_update_window_begin (struct window *w)
963 /* --------------------------------------------------------------------------
964 Prepare for a grouped sequence of drawing calls
965 external (RIF) call; for one window, called after update_begin
966 -------------------------------------------------------------------------- */
968 struct frame *f = XFRAME (WINDOW_FRAME (w));
969 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
971 NSTRACE ("ns_update_window_begin");
972 w->output_cursor = w->cursor;
976 if (f == hlinfo->mouse_face_mouse_frame)
978 /* Don't do highlighting for mouse motion during the update. */
979 hlinfo->mouse_face_defer = 1;
981 /* If the frame needs to be redrawn,
982 simply forget about any prior mouse highlighting. */
983 if (FRAME_GARBAGED_P (f))
984 hlinfo->mouse_face_window = Qnil;
986 /* (further code for mouse faces ifdef'd out in other terms elided) */
994 ns_update_window_end (struct window *w, bool cursor_on_p,
995 bool mouse_face_overwritten_p)
996 /* --------------------------------------------------------------------------
997 Finished a grouped sequence of drawing calls
998 external (RIF) call; for one window called before update_end
999 -------------------------------------------------------------------------- */
1001 NSTRACE ("update_window_end");
1003 /* note: this fn is nearly identical in all terms */
1004 if (!w->pseudo_window_p)
1009 display_and_set_cursor (w, 1,
1010 w->output_cursor.hpos, w->output_cursor.vpos,
1011 w->output_cursor.x, w->output_cursor.y);
1013 if (draw_window_fringes (w, 1))
1015 if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
1016 x_draw_right_divider (w);
1018 x_draw_vertical_border (w);
1024 /* If a row with mouse-face was overwritten, arrange for
1025 frame_up_to_date to redisplay the mouse highlight. */
1026 if (mouse_face_overwritten_p)
1027 reset_mouse_highlight (MOUSE_HL_INFO (XFRAME (w->frame)));
1032 ns_update_end (struct frame *f)
1033 /* --------------------------------------------------------------------------
1034 Finished a grouped sequence of drawing calls
1035 external (RIF) call; for whole frame, called after update_window_end
1036 -------------------------------------------------------------------------- */
1038 EmacsView *view = FRAME_NS_VIEW (f);
1040 NSTRACE ("ns_update_end");
1042 /* if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
1043 MOUSE_HL_INFO (f)->mouse_face_defer = 0;
1048 [[view window] flushWindow];
1051 ns_updating_frame = NULL;
1055 ns_focus (struct frame *f, NSRect *r, int n)
1056 /* --------------------------------------------------------------------------
1057 Internal: Focus on given frame. During small local updates this is used to
1058 draw, however during large updates, ns_update_begin and ns_update_end are
1059 called to wrap the whole thing, in which case these calls are stubbed out.
1060 Except, on GNUstep, we accumulate the rectangle being drawn into, because
1061 the back end won't do this automatically, and will just end up flushing
1063 -------------------------------------------------------------------------- */
1065 // NSTRACE ("ns_focus");
1067 fprintf (stderr, "focus: %d", c++);
1068 if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
1069 fprintf (stderr, "\n"); */
1071 if (f != ns_updating_frame)
1073 NSView *view = FRAME_NS_VIEW (f);
1074 if (view != focus_view)
1076 if (focus_view != NULL)
1078 [focus_view unlockFocus];
1079 [[focus_view window] flushWindow];
1086 /*if (view) debug_lock++; */
1093 [[NSGraphicsContext currentContext] saveGraphicsState];
1095 NSRectClipList (r, 2);
1104 ns_unfocus (struct frame *f)
1105 /* --------------------------------------------------------------------------
1106 Internal: Remove focus on given frame
1107 -------------------------------------------------------------------------- */
1109 // NSTRACE ("ns_unfocus");
1113 [[NSGraphicsContext currentContext] restoreGraphicsState];
1117 if (f != ns_updating_frame)
1119 if (focus_view != NULL)
1121 [focus_view unlockFocus];
1122 [[focus_view window] flushWindow];
1131 ns_clip_to_row (struct window *w, struct glyph_row *row,
1132 enum glyph_row_area area, BOOL gc)
1133 /* --------------------------------------------------------------------------
1134 Internal (but parallels other terms): Focus drawing on given row
1135 -------------------------------------------------------------------------- */
1137 struct frame *f = XFRAME (WINDOW_FRAME (w));
1139 int window_x, window_y, window_width;
1141 window_box (w, area, &window_x, &window_y, &window_width, 0);
1143 clip_rect.origin.x = window_x;
1144 clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
1145 clip_rect.origin.y = max (clip_rect.origin.y, window_y);
1146 clip_rect.size.width = window_width;
1147 clip_rect.size.height = row->visible_height;
1149 ns_focus (f, &clip_rect, 1);
1154 ns_ring_bell (struct frame *f)
1155 /* --------------------------------------------------------------------------
1157 -------------------------------------------------------------------------- */
1159 NSTRACE ("ns_ring_bell");
1162 NSAutoreleasePool *pool;
1163 struct frame *frame = SELECTED_FRAME ();
1167 pool = [[NSAutoreleasePool alloc] init];
1169 view = FRAME_NS_VIEW (frame);
1173 NSPoint dim = NSMakePoint (128, 128);
1176 r.origin.x += (r.size.width - dim.x) / 2;
1177 r.origin.y += (r.size.height - dim.y) / 2;
1178 r.size.width = dim.x;
1179 r.size.height = dim.y;
1180 surr = NSInsetRect (r, -2, -2);
1181 ns_focus (frame, &surr, 1);
1182 [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
1183 [ns_lookup_indexed_color (NS_FACE_FOREGROUND
1184 (FRAME_DEFAULT_FACE (frame)), frame) set];
1186 [[view window] flushWindow];
1187 ns_timeout (150000);
1188 [[view window] restoreCachedImage];
1189 [[view window] flushWindow];
1201 /* ==========================================================================
1203 Frame / window manager related functions
1205 ========================================================================== */
1209 ns_raise_frame (struct frame *f)
1210 /* --------------------------------------------------------------------------
1211 Bring window to foreground and make it active
1212 -------------------------------------------------------------------------- */
1215 check_window_system (f);
1216 view = FRAME_NS_VIEW (f);
1218 if (FRAME_VISIBLE_P (f))
1219 [[view window] makeKeyAndOrderFront: NSApp];
1225 ns_lower_frame (struct frame *f)
1226 /* --------------------------------------------------------------------------
1228 -------------------------------------------------------------------------- */
1231 check_window_system (f);
1232 view = FRAME_NS_VIEW (f);
1234 [[view window] orderBack: NSApp];
1240 ns_frame_raise_lower (struct frame *f, bool raise)
1241 /* --------------------------------------------------------------------------
1243 -------------------------------------------------------------------------- */
1245 NSTRACE ("ns_frame_raise_lower");
1255 ns_frame_rehighlight (struct frame *frame)
1256 /* --------------------------------------------------------------------------
1257 External (hook): called on things like window switching within frame
1258 -------------------------------------------------------------------------- */
1260 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
1261 struct frame *old_highlight = dpyinfo->x_highlight_frame;
1263 NSTRACE ("ns_frame_rehighlight");
1264 if (dpyinfo->x_focus_frame)
1266 dpyinfo->x_highlight_frame
1267 = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1268 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1269 : dpyinfo->x_focus_frame);
1270 if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
1272 fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
1273 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
1277 dpyinfo->x_highlight_frame = 0;
1279 if (dpyinfo->x_highlight_frame &&
1280 dpyinfo->x_highlight_frame != old_highlight)
1284 x_update_cursor (old_highlight, 1);
1285 x_set_frame_alpha (old_highlight);
1287 if (dpyinfo->x_highlight_frame)
1289 x_update_cursor (dpyinfo->x_highlight_frame, 1);
1290 x_set_frame_alpha (dpyinfo->x_highlight_frame);
1297 x_make_frame_visible (struct frame *f)
1298 /* --------------------------------------------------------------------------
1299 External: Show the window (X11 semantics)
1300 -------------------------------------------------------------------------- */
1302 NSTRACE ("x_make_frame_visible");
1303 /* XXX: at some points in past this was not needed, as the only place that
1304 called this (frame.c:Fraise_frame ()) also called raise_lower;
1305 if this ends up the case again, comment this out again. */
1306 if (!FRAME_VISIBLE_P (f))
1308 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1310 SET_FRAME_VISIBLE (f, 1);
1313 /* Making a new frame from a fullscreen frame will make the new frame
1314 fullscreen also. So skip handleFS as this will print an error. */
1315 if ([view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH
1316 && [view isFullscreen])
1319 if (f->want_fullscreen != FULLSCREEN_NONE)
1330 x_make_frame_invisible (struct frame *f)
1331 /* --------------------------------------------------------------------------
1332 External: Hide the window (X11 semantics)
1333 -------------------------------------------------------------------------- */
1336 NSTRACE ("x_make_frame_invisible");
1337 check_window_system (f);
1338 view = FRAME_NS_VIEW (f);
1339 [[view window] orderOut: NSApp];
1340 SET_FRAME_VISIBLE (f, 0);
1341 SET_FRAME_ICONIFIED (f, 0);
1346 x_iconify_frame (struct frame *f)
1347 /* --------------------------------------------------------------------------
1348 External: Iconify window
1349 -------------------------------------------------------------------------- */
1352 struct ns_display_info *dpyinfo;
1354 NSTRACE ("x_iconify_frame");
1355 check_window_system (f);
1356 view = FRAME_NS_VIEW (f);
1357 dpyinfo = FRAME_DISPLAY_INFO (f);
1359 if (dpyinfo->x_highlight_frame == f)
1360 dpyinfo->x_highlight_frame = 0;
1362 if ([[view window] windowNumber] <= 0)
1364 /* the window is still deferred. Make it very small, bring it
1365 on screen and order it out. */
1366 NSRect s = { { 100, 100}, {0, 0} };
1368 t = [[view window] frame];
1369 [[view window] setFrame: s display: NO];
1370 [[view window] orderBack: NSApp];
1371 [[view window] orderOut: NSApp];
1372 [[view window] setFrame: t display: NO];
1374 [[view window] miniaturize: NSApp];
1377 /* Free X resources of frame F. */
1380 x_free_frame_resources (struct frame *f)
1383 struct ns_display_info *dpyinfo;
1384 Mouse_HLInfo *hlinfo;
1386 NSTRACE ("x_free_frame_resources");
1387 check_window_system (f);
1388 view = FRAME_NS_VIEW (f);
1389 dpyinfo = FRAME_DISPLAY_INFO (f);
1390 hlinfo = MOUSE_HL_INFO (f);
1392 [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1396 free_frame_menubar (f);
1397 free_frame_faces (f);
1399 if (f == dpyinfo->x_focus_frame)
1400 dpyinfo->x_focus_frame = 0;
1401 if (f == dpyinfo->x_highlight_frame)
1402 dpyinfo->x_highlight_frame = 0;
1403 if (f == hlinfo->mouse_face_mouse_frame)
1404 reset_mouse_highlight (hlinfo);
1406 if (f->output_data.ns->miniimage != nil)
1407 [f->output_data.ns->miniimage release];
1409 [[view window] close];
1412 xfree (f->output_data.ns);
1418 x_destroy_window (struct frame *f)
1419 /* --------------------------------------------------------------------------
1420 External: Delete the window
1421 -------------------------------------------------------------------------- */
1423 NSTRACE ("x_destroy_window");
1424 check_window_system (f);
1425 x_free_frame_resources (f);
1431 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1432 /* --------------------------------------------------------------------------
1433 External: Position the window
1434 -------------------------------------------------------------------------- */
1436 NSView *view = FRAME_NS_VIEW (f);
1437 NSArray *screens = [NSScreen screens];
1438 NSScreen *fscreen = [screens objectAtIndex: 0];
1439 NSScreen *screen = [[view window] screen];
1441 NSTRACE ("x_set_offset");
1448 if (view != nil && screen && fscreen)
1450 f->left_pos = f->size_hint_flags & XNegative
1451 ? [screen visibleFrame].size.width + f->left_pos - FRAME_PIXEL_WIDTH (f)
1453 /* We use visibleFrame here to take menu bar into account.
1454 Ideally we should also adjust left/top with visibleFrame.origin. */
1456 f->top_pos = f->size_hint_flags & YNegative
1457 ? ([screen visibleFrame].size.height + f->top_pos
1458 - FRAME_PIXEL_HEIGHT (f) - FRAME_NS_TITLEBAR_HEIGHT (f)
1459 - FRAME_TOOLBAR_HEIGHT (f))
1461 #ifdef NS_IMPL_GNUSTEP
1462 if (f->left_pos < 100)
1463 f->left_pos = 100; /* don't overlap menu */
1465 /* Constrain the setFrameTopLeftPoint so we don't move behind the
1467 NSPoint pt = NSMakePoint (SCREENMAXBOUND (f->left_pos),
1468 SCREENMAXBOUND ([fscreen frame].size.height
1470 NSTRACE_POINT ("setFrameTopLeftPoint", pt);
1471 [[view window] setFrameTopLeftPoint: pt];
1472 f->size_hint_flags &= ~(XNegative|YNegative);
1480 x_set_window_size (struct frame *f,
1481 bool change_gravity,
1485 /* --------------------------------------------------------------------------
1486 Adjust window pixel size based on given character grid size
1487 Impl is a bit more complex than other terms, need to do some
1489 -------------------------------------------------------------------------- */
1491 EmacsView *view = FRAME_NS_VIEW (f);
1492 NSWindow *window = [view window];
1493 NSRect wr = [window frame];
1494 int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1495 int pixelwidth, pixelheight;
1497 int orig_height = wr.size.height;
1499 NSTRACE ("x_set_window_size");
1504 NSTRACE_RECT ("input", wr);
1506 /*fprintf (stderr, "\tsetWindowSize: %d x %d, pixelwise %d, font size %d x %d\n", width, height, pixelwise, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f));*/
1512 pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
1513 pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
1514 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, pixelwidth);
1515 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, pixelheight);
1519 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, width);
1520 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, height);
1525 /* If we have a toolbar, take its height into account. */
1526 if (tb && ! [view isFullscreen])
1528 /* NOTE: previously this would generate wrong result if toolbar not
1529 yet displayed and fixing toolbar_height=32 helped, but
1530 now (200903) seems no longer needed */
1531 FRAME_TOOLBAR_HEIGHT (f) =
1532 NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1533 - FRAME_NS_TITLEBAR_HEIGHT (f);
1535 /* Only breaks things here, removed by martin 2015-09-30. */
1536 #ifdef NS_IMPL_GNUSTEP
1537 FRAME_TOOLBAR_HEIGHT (f) -= 3;
1542 FRAME_TOOLBAR_HEIGHT (f) = 0;
1544 wr.size.width = pixelwidth + f->border_width;
1545 wr.size.height = pixelheight;
1546 if (! [view isFullscreen])
1547 wr.size.height += FRAME_NS_TITLEBAR_HEIGHT (f)
1548 + FRAME_TOOLBAR_HEIGHT (f);
1550 /* Do not try to constrain to this screen. We may have multiple
1551 screens, and want Emacs to span those. Constraining to screen
1552 prevents that, and that is not nice to the user. */
1553 if (f->output_data.ns->zooming)
1554 f->output_data.ns->zooming = 0;
1556 wr.origin.y += orig_height - wr.size.height;
1558 frame_size_history_add
1559 (f, Qx_set_window_size_1, width, height,
1560 list5 (Fcons (make_number (pixelwidth), make_number (pixelheight)),
1561 Fcons (make_number (wr.size.width), make_number (wr.size.height)),
1562 make_number (f->border_width),
1563 make_number (FRAME_NS_TITLEBAR_HEIGHT (f)),
1564 make_number (FRAME_TOOLBAR_HEIGHT (f))));
1566 [view setRows: rows andColumns: cols];
1567 NSTRACE_RECT ("setFrame", wr);
1568 [window setFrame: wr display: YES];
1570 /* This is a trick to compensate for Emacs' managing the scrollbar area
1571 as a fixed number of standard character columns. Instead of leaving
1572 blank space for the extra, we chopped it off above. Now for
1573 left-hand scrollbars, we shift all rendering to the left by the
1574 difference between the real width and Emacs' imagined one. For
1575 right-hand bars, don't worry about it since the extra is never used.
1576 (Obviously doesn't work for vertically split windows tho..) */
1578 NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1579 ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1580 - NS_SCROLL_BAR_WIDTH (f), 0)
1581 : NSMakePoint (0, 0);
1582 NSTRACE_RECT ("setFrame", wr);
1583 [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1584 [view setBoundsOrigin: origin];
1587 [view updateFrameSize: NO];
1593 ns_fullscreen_hook (struct frame *f)
1595 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1597 NSTRACE ("ns_fullscreen_hook");
1599 if (!FRAME_VISIBLE_P (f))
1602 if (! [view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH)
1604 /* Old style fs don't initiate correctly if created from
1605 init/default-frame alist, so use a timer (not nice...).
1607 [NSTimer scheduledTimerWithTimeInterval: 0.5 target: view
1608 selector: @selector (handleFS)
1609 userInfo: nil repeats: NO];
1618 /* ==========================================================================
1622 ========================================================================== */
1626 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1628 struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1629 if (idx < 1 || idx >= color_table->avail)
1631 return color_table->colors[idx];
1636 ns_index_color (NSColor *color, struct frame *f)
1638 struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1642 if (!color_table->colors)
1644 color_table->size = NS_COLOR_CAPACITY;
1645 color_table->avail = 1; /* skip idx=0 as marker */
1646 color_table->colors = xmalloc (color_table->size * sizeof (NSColor *));
1647 color_table->colors[0] = nil;
1648 color_table->empty_indices = [[NSMutableSet alloc] init];
1651 /* Do we already have this color? */
1652 for (i = 1; i < color_table->avail; i++)
1653 if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1656 if ([color_table->empty_indices count] > 0)
1658 NSNumber *index = [color_table->empty_indices anyObject];
1659 [color_table->empty_indices removeObject: index];
1660 idx = [index unsignedLongValue];
1664 if (color_table->avail == color_table->size)
1665 color_table->colors =
1666 xpalloc (color_table->colors, &color_table->size, 1,
1667 min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1668 idx = color_table->avail++;
1671 color_table->colors[idx] = color;
1673 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1679 ns_free_indexed_color (unsigned long idx, struct frame *f)
1681 struct ns_color_table *color_table;
1688 color_table = FRAME_DISPLAY_INFO (f)->color_table;
1690 if (idx <= 0 || idx >= color_table->size) {
1691 message1 ("ns_free_indexed_color: Color index out of range.\n");
1695 index = [NSNumber numberWithUnsignedInt: idx];
1696 if ([color_table->empty_indices containsObject: index]) {
1697 message1 ("ns_free_indexed_color: attempt to free already freed color.\n");
1701 color = color_table->colors[idx];
1703 color_table->colors[idx] = nil;
1704 [color_table->empty_indices addObject: index];
1705 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1710 ns_get_color (const char *name, NSColor **col)
1711 /* --------------------------------------------------------------------------
1713 -------------------------------------------------------------------------- */
1714 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1715 X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1716 See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1719 static char hex[20];
1721 float r = -1.0, g, b;
1722 NSString *nsname = [NSString stringWithUTF8String: name];
1724 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1727 if ([nsname isEqualToString: @"ns_selection_bg_color"])
1729 #ifdef NS_IMPL_COCOA
1730 NSString *defname = [[NSUserDefaults standardUserDefaults]
1731 stringForKey: @"AppleHighlightColor"];
1736 if ((new = [NSColor selectedTextBackgroundColor]) != nil)
1738 *col = [new colorUsingDefaultColorSpace];
1743 nsname = NS_SELECTION_BG_COLOR_DEFAULT;
1745 name = [nsname UTF8String];
1747 else if ([nsname isEqualToString: @"ns_selection_fg_color"])
1749 /* NOTE: OSX applications normally don't set foreground selection, but
1750 text may be unreadable if we don't.
1752 if ((new = [NSColor selectedTextColor]) != nil)
1754 *col = [new colorUsingDefaultColorSpace];
1759 nsname = NS_SELECTION_FG_COLOR_DEFAULT;
1760 name = [nsname UTF8String];
1763 /* First, check for some sort of numeric specification. */
1766 if (name[0] == '0' || name[0] == '1' || name[0] == '.') /* RGB decimal */
1768 NSScanner *scanner = [NSScanner scannerWithString: nsname];
1769 [scanner scanFloat: &r];
1770 [scanner scanFloat: &g];
1771 [scanner scanFloat: &b];
1773 else if (!strncmp(name, "rgb:", 4)) /* A newer X11 format -- rgb:r/g/b */
1774 scaling = (snprintf (hex, sizeof hex, "%s", name + 4) - 2) / 3;
1775 else if (name[0] == '#') /* An old X11 format; convert to newer */
1777 int len = (strlen(name) - 1);
1778 int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1780 scaling = strlen(name+start) / 3;
1781 for (i = 0; i < 3; i++)
1782 sprintf (hex + i * (scaling + 1), "%.*s/", scaling,
1783 name + start + i * scaling);
1784 hex[3 * (scaling + 1) - 1] = '\0';
1790 float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1791 if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1801 *col = [NSColor colorForEmacsRed: r green: g blue: b alpha: 1.0];
1806 /* Otherwise, color is expected to be from a list */
1808 NSEnumerator *lenum, *cenum;
1812 #ifdef NS_IMPL_GNUSTEP
1813 /* XXX: who is wrong, the requestor or the implementation? */
1814 if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1816 nsname = @"highlightColor";
1819 lenum = [[NSColorList availableColorLists] objectEnumerator];
1820 while ( (clist = [lenum nextObject]) && new == nil)
1822 cenum = [[clist allKeys] objectEnumerator];
1823 while ( (name = [cenum nextObject]) && new == nil )
1825 if ([name compare: nsname
1826 options: NSCaseInsensitiveSearch] == NSOrderedSame )
1827 new = [clist colorWithKey: name];
1833 *col = [new colorUsingDefaultColorSpace];
1840 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1841 /* --------------------------------------------------------------------------
1842 Convert a Lisp string object to a NS color
1843 -------------------------------------------------------------------------- */
1845 NSTRACE ("ns_lisp_to_color");
1846 if (STRINGP (color))
1847 return ns_get_color (SSDATA (color), col);
1848 else if (SYMBOLP (color))
1849 return ns_get_color (SSDATA (SYMBOL_NAME (color)), col);
1855 ns_color_to_lisp (NSColor *col)
1856 /* --------------------------------------------------------------------------
1857 Convert a color to a lisp string with the RGB equivalent
1858 -------------------------------------------------------------------------- */
1860 EmacsCGFloat red, green, blue, alpha, gray;
1863 NSTRACE ("ns_color_to_lisp");
1866 if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1868 if ((str =[[col colorNameComponent] UTF8String]))
1871 return build_string ((char *)str);
1874 [[col colorUsingDefaultColorSpace]
1875 getRed: &red green: &green blue: &blue alpha: &alpha];
1876 if (red == green && red == blue)
1878 [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1879 getWhite: &gray alpha: &alpha];
1880 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1881 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1883 return build_string (buf);
1886 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1887 lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1890 return build_string (buf);
1895 ns_query_color(void *col, XColor *color_def, int setPixel)
1896 /* --------------------------------------------------------------------------
1897 Get ARGB values out of NSColor col and put them into color_def.
1898 If setPixel, set the pixel to a concatenated version.
1899 and set color_def pixel to the resulting index.
1900 -------------------------------------------------------------------------- */
1902 EmacsCGFloat r, g, b, a;
1904 [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1905 color_def->red = r * 65535;
1906 color_def->green = g * 65535;
1907 color_def->blue = b * 65535;
1909 if (setPixel == YES)
1911 = ARGB_TO_ULONG((int)(a*255),
1912 (int)(r*255), (int)(g*255), (int)(b*255));
1917 ns_defined_color (struct frame *f,
1922 /* --------------------------------------------------------------------------
1923 Return true if named color found, and set color_def rgb accordingly.
1924 If makeIndex and alloc are nonzero put the color in the color_table,
1925 and set color_def pixel to the resulting index.
1926 If makeIndex is zero, set color_def pixel to ARGB.
1927 Return false if not found
1928 -------------------------------------------------------------------------- */
1931 NSTRACE ("ns_defined_color");
1934 if (ns_get_color (name, &col) != 0) /* Color not found */
1939 if (makeIndex && alloc)
1940 color_def->pixel = ns_index_color (col, f);
1941 ns_query_color (col, color_def, !makeIndex);
1948 x_set_frame_alpha (struct frame *f)
1949 /* --------------------------------------------------------------------------
1950 change the entire-frame transparency
1951 -------------------------------------------------------------------------- */
1953 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1955 double alpha_min = 1.0;
1957 if (dpyinfo->x_highlight_frame == f)
1958 alpha = f->alpha[0];
1960 alpha = f->alpha[1];
1962 if (FLOATP (Vframe_alpha_lower_limit))
1963 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1964 else if (INTEGERP (Vframe_alpha_lower_limit))
1965 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1969 else if (1.0 < alpha)
1971 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1974 #ifdef NS_IMPL_COCOA
1976 EmacsView *view = FRAME_NS_VIEW (f);
1977 [[view window] setAlphaValue: alpha];
1983 /* ==========================================================================
1987 ========================================================================== */
1991 frame_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1992 /* --------------------------------------------------------------------------
1993 Programmatically reposition mouse pointer in pixel coordinates
1994 -------------------------------------------------------------------------- */
1996 NSTRACE ("frame_set_mouse_pixel_position");
1999 /* FIXME: this does not work, and what about GNUstep? */
2000 #ifdef NS_IMPL_COCOA
2001 [FRAME_NS_VIEW (f) lockFocus];
2002 PSsetmouse ((float)pix_x, (float)pix_y);
2003 [FRAME_NS_VIEW (f) unlockFocus];
2009 note_mouse_movement (struct frame *frame, CGFloat x, CGFloat y)
2010 /* ------------------------------------------------------------------------
2011 Called by EmacsView on mouseMovement events. Passes on
2012 to emacs mainstream code if we moved off of a rect of interest
2013 known as last_mouse_glyph.
2014 ------------------------------------------------------------------------ */
2016 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
2019 // NSTRACE ("note_mouse_movement");
2021 dpyinfo->last_mouse_motion_frame = frame;
2022 r = &dpyinfo->last_mouse_glyph;
2024 /* Note, this doesn't get called for enter/leave, since we don't have a
2025 position. Those are taken care of in the corresponding NSView methods. */
2027 /* has movement gone beyond last rect we were tracking? */
2028 if (x < r->origin.x || x >= r->origin.x + r->size.width
2029 || y < r->origin.y || y >= r->origin.y + r->size.height)
2031 ns_update_begin (frame);
2032 frame->mouse_moved = 1;
2033 note_mouse_highlight (frame, x, y);
2034 remember_mouse_glyph (frame, x, y, r);
2035 ns_update_end (frame);
2044 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
2045 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
2047 /* --------------------------------------------------------------------------
2048 External (hook): inform emacs about mouse position and hit parts.
2049 If a scrollbar is being dragged, set bar_window, part, x, y, time.
2050 x & y should be position in the scrollbar (the whole bar, not the handle)
2051 and length of scrollbar respectively
2052 -------------------------------------------------------------------------- */
2056 Lisp_Object frame, tail;
2058 struct ns_display_info *dpyinfo;
2060 NSTRACE ("ns_mouse_position");
2064 fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
2068 dpyinfo = FRAME_DISPLAY_INFO (*fp);
2072 /* Clear the mouse-moved flag for every frame on this display. */
2073 FOR_EACH_FRAME (tail, frame)
2074 if (FRAME_NS_P (XFRAME (frame))
2075 && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
2076 XFRAME (frame)->mouse_moved = 0;
2078 dpyinfo->last_mouse_scroll_bar = nil;
2079 if (dpyinfo->last_mouse_frame
2080 && FRAME_LIVE_P (dpyinfo->last_mouse_frame))
2081 f = dpyinfo->last_mouse_frame;
2083 f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame : SELECTED_FRAME ();
2085 if (f && FRAME_NS_P (f))
2087 view = FRAME_NS_VIEW (*fp);
2089 position = [[view window] mouseLocationOutsideOfEventStream];
2090 position = [view convertPoint: position fromView: nil];
2091 remember_mouse_glyph (f, position.x, position.y,
2092 &dpyinfo->last_mouse_glyph);
2093 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
2095 if (bar_window) *bar_window = Qnil;
2096 if (part) *part = scroll_bar_above_handle;
2098 if (x) XSETINT (*x, lrint (position.x));
2099 if (y) XSETINT (*y, lrint (position.y));
2101 *time = dpyinfo->last_mouse_movement_time;
2110 ns_frame_up_to_date (struct frame *f)
2111 /* --------------------------------------------------------------------------
2112 External (hook): Fix up mouse highlighting right after a full update.
2113 Can't use FRAME_MOUSE_UPDATE due to ns_frame_begin and ns_frame_end calls.
2114 -------------------------------------------------------------------------- */
2116 NSTRACE ("ns_frame_up_to_date");
2120 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
2121 if (f == hlinfo->mouse_face_mouse_frame)
2125 note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
2126 hlinfo->mouse_face_mouse_x,
2127 hlinfo->mouse_face_mouse_y);
2136 ns_define_frame_cursor (struct frame *f, Cursor cursor)
2137 /* --------------------------------------------------------------------------
2138 External (RIF): set frame mouse pointer type.
2139 -------------------------------------------------------------------------- */
2141 NSTRACE ("ns_define_frame_cursor");
2142 if (FRAME_POINTER_TYPE (f) != cursor)
2144 EmacsView *view = FRAME_NS_VIEW (f);
2145 FRAME_POINTER_TYPE (f) = cursor;
2146 [[view window] invalidateCursorRectsForView: view];
2147 /* Redisplay assumes this function also draws the changed frame
2148 cursor, but this function doesn't, so do it explicitly. */
2149 x_update_cursor (f, 1);
2155 /* ==========================================================================
2159 ========================================================================== */
2163 ns_convert_key (unsigned code)
2164 /* --------------------------------------------------------------------------
2165 Internal call used by NSView-keyDown.
2166 -------------------------------------------------------------------------- */
2168 const unsigned last_keysym = ARRAYELTS (convert_ns_to_X_keysym);
2170 /* An array would be faster, but less easy to read. */
2171 for (keysym = 0; keysym < last_keysym; keysym += 2)
2172 if (code == convert_ns_to_X_keysym[keysym])
2173 return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
2175 /* if decide to use keyCode and Carbon table, use this line:
2176 return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
2181 x_get_keysym_name (int keysym)
2182 /* --------------------------------------------------------------------------
2183 Called by keyboard.c. Not sure if the return val is important, except
2185 -------------------------------------------------------------------------- */
2187 static char value[16];
2188 NSTRACE ("x_get_keysym_name");
2189 sprintf (value, "%d", keysym);
2195 /* ==========================================================================
2197 Block drawing operations
2199 ========================================================================== */
2203 ns_redraw_scroll_bars (struct frame *f)
2207 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
2208 NSTRACE ("ns_redraw_scroll_bars");
2209 for (i =[subviews count]-1; i >= 0; i--)
2211 view = [subviews objectAtIndex: i];
2212 if (![view isKindOfClass: [EmacsScroller class]]) continue;
2219 ns_clear_frame (struct frame *f)
2220 /* --------------------------------------------------------------------------
2221 External (hook): Erase the entire frame
2222 -------------------------------------------------------------------------- */
2224 NSView *view = FRAME_NS_VIEW (f);
2227 NSTRACE ("ns_clear_frame");
2229 /* comes on initial frame because we have
2230 after-make-frame-functions = select-frame */
2231 if (!FRAME_DEFAULT_FACE (f))
2234 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2239 ns_focus (f, &r, 1);
2240 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
2244 /* as of 2006/11 or so this is now needed */
2245 ns_redraw_scroll_bars (f);
2251 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2252 /* --------------------------------------------------------------------------
2253 External (RIF): Clear section of frame
2254 -------------------------------------------------------------------------- */
2256 NSRect r = NSMakeRect (x, y, width, height);
2257 NSView *view = FRAME_NS_VIEW (f);
2258 struct face *face = FRAME_DEFAULT_FACE (f);
2263 NSTRACE ("ns_clear_frame_area");
2265 r = NSIntersectionRect (r, [view frame]);
2266 ns_focus (f, &r, 1);
2267 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2276 ns_copy_bits (struct frame *f, NSRect src, NSRect dest)
2278 if (FRAME_NS_VIEW (f))
2280 ns_focus (f, &dest, 1);
2281 [FRAME_NS_VIEW (f) scrollRect: src
2282 by: NSMakeSize (dest.origin.x - src.origin.x,
2283 dest.origin.y - src.origin.y)];
2289 ns_scroll_run (struct window *w, struct run *run)
2290 /* --------------------------------------------------------------------------
2291 External (RIF): Insert or delete n lines at line vpos
2292 -------------------------------------------------------------------------- */
2294 struct frame *f = XFRAME (w->frame);
2295 int x, y, width, height, from_y, to_y, bottom_y;
2297 NSTRACE ("ns_scroll_run");
2299 /* begin copy from other terms */
2300 /* Get frame-relative bounding box of the text display area of W,
2301 without mode lines. Include in this box the left and right
2303 window_box (w, ANY_AREA, &x, &y, &width, &height);
2305 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2306 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2307 bottom_y = y + height;
2311 /* Scrolling up. Make sure we don't copy part of the mode
2312 line at the bottom. */
2313 if (from_y + run->height > bottom_y)
2314 height = bottom_y - from_y;
2316 height = run->height;
2320 /* Scrolling down. Make sure we don't copy over the mode line.
2322 if (to_y + run->height > bottom_y)
2323 height = bottom_y - to_y;
2325 height = run->height;
2327 /* end copy from other terms */
2337 NSRect srcRect = NSMakeRect (x, from_y, width, height);
2338 NSRect dstRect = NSMakeRect (x, to_y, width, height);
2340 ns_copy_bits (f, srcRect , dstRect);
2348 ns_after_update_window_line (struct window *w, struct glyph_row *desired_row)
2349 /* --------------------------------------------------------------------------
2350 External (RIF): preparatory to fringe update after text was updated
2351 -------------------------------------------------------------------------- */
2356 NSTRACE ("ns_after_update_window_line");
2358 /* begin copy from other terms */
2361 if (!desired_row->mode_line_p && !w->pseudo_window_p)
2362 desired_row->redraw_fringe_bitmaps_p = 1;
2364 /* When a window has disappeared, make sure that no rest of
2365 full-width rows stays visible in the internal border. */
2366 if (windows_or_buffers_changed
2367 && desired_row->full_width_p
2368 && (f = XFRAME (w->frame),
2369 width = FRAME_INTERNAL_BORDER_WIDTH (f),
2371 && (height = desired_row->visible_height,
2374 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2377 ns_clear_frame_area (f, 0, y, width, height);
2378 ns_clear_frame_area (f,
2379 FRAME_PIXEL_WIDTH (f) - width,
2387 ns_shift_glyphs_for_insert (struct frame *f,
2388 int x, int y, int width, int height,
2390 /* --------------------------------------------------------------------------
2391 External (RIF): copy an area horizontally, don't worry about clearing src
2392 -------------------------------------------------------------------------- */
2394 NSRect srcRect = NSMakeRect (x, y, width, height);
2395 NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2397 NSTRACE ("ns_shift_glyphs_for_insert");
2399 ns_copy_bits (f, srcRect, dstRect);
2404 /* ==========================================================================
2406 Character encoding and metrics
2408 ========================================================================== */
2412 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2413 /* --------------------------------------------------------------------------
2414 External (RIF); compute left/right overhang of whole string and set in s
2415 -------------------------------------------------------------------------- */
2417 struct font *font = s->font;
2421 struct font_metrics metrics;
2422 unsigned int codes[2];
2423 codes[0] = *(s->char2b);
2424 codes[1] = *(s->char2b + s->nchars - 1);
2426 font->driver->text_extents (font, codes, 2, &metrics);
2427 s->left_overhang = -metrics.lbearing;
2429 = metrics.rbearing > metrics.width
2430 ? metrics.rbearing - metrics.width : 0;
2434 s->left_overhang = 0;
2435 if (EQ (font->driver->type, Qns))
2436 s->right_overhang = ((struct nsfont_info *)font)->ital ?
2437 FONT_HEIGHT (font) * 0.2 : 0;
2439 s->right_overhang = 0;
2445 /* ==========================================================================
2447 Fringe and cursor drawing
2449 ========================================================================== */
2452 extern int max_used_fringe_bitmap;
2454 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2455 struct draw_fringe_bitmap_params *p)
2456 /* --------------------------------------------------------------------------
2457 External (RIF); fringe-related
2458 -------------------------------------------------------------------------- */
2460 struct frame *f = XFRAME (WINDOW_FRAME (w));
2461 struct face *face = p->face;
2462 static EmacsImage **bimgs = NULL;
2463 static int nBimgs = 0;
2465 /* grow bimgs if needed */
2466 if (nBimgs < max_used_fringe_bitmap)
2468 bimgs = xrealloc (bimgs, max_used_fringe_bitmap * sizeof *bimgs);
2469 memset (bimgs + nBimgs, 0,
2470 (max_used_fringe_bitmap - nBimgs) * sizeof *bimgs);
2471 nBimgs = max_used_fringe_bitmap;
2474 /* Must clip because of partially visible lines. */
2475 ns_clip_to_row (w, row, ANY_AREA, YES);
2479 int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
2481 if (bx >= 0 && nx > 0)
2483 NSRect r = NSMakeRect (bx, by, nx, ny);
2485 [ns_lookup_indexed_color (face->background, f) set];
2492 NSRect r = NSMakeRect (p->x, p->y, p->wd, p->h);
2493 EmacsImage *img = bimgs[p->which - 1];
2497 unsigned short *bits = p->bits + p->dh;
2500 unsigned char *cbits = xmalloc (len);
2502 for (i = 0; i < len; i++)
2503 cbits[i] = ~(bits[i] & 0xff);
2504 img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2506 bimgs[p->which - 1] = img;
2511 /* Since we composite the bitmap instead of just blitting it, we need
2512 to erase the whole background. */
2513 [ns_lookup_indexed_color(face->background, f) set];
2519 bm_color = ns_lookup_indexed_color(face->foreground, f);
2520 else if (p->overlay_p)
2521 bm_color = ns_lookup_indexed_color(face->background, f);
2523 bm_color = f->output_data.ns->cursor_color;
2524 [img setXBMColor: bm_color];
2527 #ifdef NS_IMPL_COCOA
2529 fromRect: NSZeroRect
2530 operation: NSCompositeSourceOver
2536 NSPoint pt = r.origin;
2538 [img compositeToPoint: pt operation: NSCompositeSourceOver];
2547 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2548 int x, int y, enum text_cursor_kinds cursor_type,
2549 int cursor_width, bool on_p, bool active_p)
2550 /* --------------------------------------------------------------------------
2551 External call (RIF): draw cursor.
2552 Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2553 -------------------------------------------------------------------------- */
2556 int fx, fy, h, cursor_height;
2557 struct frame *f = WINDOW_XFRAME (w);
2558 struct glyph *phys_cursor_glyph;
2559 struct glyph *cursor_glyph;
2561 NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2563 /* If cursor is out of bounds, don't draw garbage. This can happen
2564 in mini-buffer windows when switching between echo area glyphs
2567 NSTRACE ("dumpcursor");
2572 w->phys_cursor_type = cursor_type;
2573 w->phys_cursor_on_p = on_p;
2575 if (cursor_type == NO_CURSOR)
2577 w->phys_cursor_width = 0;
2581 if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2583 if (glyph_row->exact_window_width_line_p
2584 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2586 glyph_row->cursor_in_fringe_p = 1;
2587 draw_fringe_bitmap (w, glyph_row, 0);
2592 /* We draw the cursor (with NSRectFill), then draw the glyph on top
2593 (other terminals do it the other way round). We must set
2594 w->phys_cursor_width to the cursor width. For bar cursors, that
2595 is CURSOR_WIDTH; for box cursors, it is the glyph width. */
2596 get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2598 /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2599 to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2600 if (cursor_type == BAR_CURSOR)
2602 if (cursor_width < 1)
2603 cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2604 w->phys_cursor_width = cursor_width;
2606 /* If we have an HBAR, "cursor_width" MAY specify height. */
2607 else if (cursor_type == HBAR_CURSOR)
2609 cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2610 if (cursor_height > glyph_row->height)
2611 cursor_height = glyph_row->height;
2612 if (h > cursor_height) // Cursor smaller than line height, move down
2613 fy += h - cursor_height;
2617 r.origin.x = fx, r.origin.y = fy;
2619 r.size.width = w->phys_cursor_width;
2621 /* TODO: only needed in rare cases with last-resort font in HELLO..
2622 should we do this more efficiently? */
2623 ns_clip_to_row (w, glyph_row, ANY_AREA, NO); /* do ns_focus(f, &r, 1); if remove */
2626 face = FACE_FROM_ID (f, phys_cursor_glyph->face_id);
2627 if (face && NS_FACE_BACKGROUND (face)
2628 == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2630 [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2631 hollow_color = FRAME_CURSOR_COLOR (f);
2634 [FRAME_CURSOR_COLOR (f) set];
2636 #ifdef NS_IMPL_COCOA
2637 /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2638 atomic. Cleaner ways of doing this should be investigated.
2639 One way would be to set a global variable DRAWING_CURSOR
2640 when making the call to draw_phys..(), don't focus in that
2641 case, then move the ns_unfocus() here after that call. */
2642 NSDisableScreenUpdates ();
2645 switch (cursor_type)
2647 case DEFAULT_CURSOR:
2650 case FILLED_BOX_CURSOR:
2653 case HOLLOW_BOX_CURSOR:
2656 NSRectFill (NSInsetRect (r, 1, 1));
2657 [FRAME_CURSOR_COLOR (f) set];
2664 /* If the character under cursor is R2L, draw the bar cursor
2665 on the right of its glyph, rather than on the left. */
2666 cursor_glyph = get_phys_cursor_glyph (w);
2667 if ((cursor_glyph->resolved_level & 1) != 0)
2668 s.origin.x += cursor_glyph->pixel_width - s.size.width;
2675 /* draw the character under the cursor */
2676 if (cursor_type != NO_CURSOR)
2677 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2679 #ifdef NS_IMPL_COCOA
2680 NSEnableScreenUpdates ();
2687 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2688 /* --------------------------------------------------------------------------
2689 External (RIF): Draw a vertical line.
2690 -------------------------------------------------------------------------- */
2692 struct frame *f = XFRAME (WINDOW_FRAME (w));
2694 NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2696 NSTRACE ("ns_draw_vertical_window_border");
2698 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2700 [ns_lookup_indexed_color(face->foreground, f) set];
2702 ns_focus (f, &r, 1);
2709 ns_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
2710 /* --------------------------------------------------------------------------
2711 External (RIF): Draw a window divider.
2712 -------------------------------------------------------------------------- */
2714 struct frame *f = XFRAME (WINDOW_FRAME (w));
2716 NSRect r = NSMakeRect (x0, y0, x1-x0, y1-y0);
2718 NSTRACE ("ns_draw_window_divider");
2720 face = FACE_FROM_ID (f, WINDOW_DIVIDER_FACE_ID);
2722 [ns_lookup_indexed_color(face->foreground, f) set];
2724 ns_focus (f, &r, 1);
2730 ns_show_hourglass (struct frame *f)
2732 /* TODO: add NSProgressIndicator to all frames. */
2736 ns_hide_hourglass (struct frame *f)
2738 /* TODO: remove NSProgressIndicator from all frames. */
2741 /* ==========================================================================
2743 Glyph drawing operations
2745 ========================================================================== */
2748 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2749 /* --------------------------------------------------------------------------
2750 Wrapper utility to account for internal border width on full-width lines,
2751 and allow top full-width rows to hit the frame top. nr should be pointer
2752 to two successive NSRects. Number of rects actually used is returned.
2753 -------------------------------------------------------------------------- */
2755 int n = get_glyph_string_clip_rects (s, nr, 2);
2759 /* --------------------------------------------------------------------
2760 Draw a wavy line under glyph string s. The wave fills wave_height
2767 wave_height = 3 | * * * *
2768 --------------------------------------------------------------------- */
2771 ns_draw_underwave (struct glyph_string *s, EmacsCGFloat width, EmacsCGFloat x)
2773 int wave_height = 3, wave_length = 2;
2774 int y, dx, dy, odd, xmax;
2779 dy = wave_height - 1;
2780 y = s->ybase - wave_height + 3;
2783 /* Find and set clipping rectangle */
2784 waveClip = NSMakeRect (x, y, width, wave_height);
2785 [[NSGraphicsContext currentContext] saveGraphicsState];
2786 NSRectClip (waveClip);
2788 /* Draw the waves */
2789 a.x = x - ((int)(x) % dx) + (EmacsCGFloat) 0.5;
2791 odd = (int)(a.x/dx) % 2;
2792 a.y = b.y = y + 0.5;
2801 [NSBezierPath strokeLineFromPoint:a toPoint:b];
2802 a.x = b.x, a.y = b.y;
2803 b.x += dx, b.y = y + 0.5 + odd*dy;
2807 /* Restore previous clipping rectangle(s) */
2808 [[NSGraphicsContext currentContext] restoreGraphicsState];
2814 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
2815 NSColor *defaultCol, CGFloat width, CGFloat x)
2816 /* --------------------------------------------------------------------------
2817 Draw underline, overline, and strike-through on glyph string s.
2818 -------------------------------------------------------------------------- */
2820 if (s->for_overlaps)
2824 if (face->underline_p)
2826 if (s->face->underline_type == FACE_UNDER_WAVE)
2828 if (face->underline_defaulted_p)
2831 [ns_lookup_indexed_color (face->underline_color, s->f) set];
2833 ns_draw_underwave (s, width, x);
2835 else if (s->face->underline_type == FACE_UNDER_LINE)
2839 unsigned long thickness, position;
2841 /* If the prev was underlined, match its appearance. */
2842 if (s->prev && s->prev->face->underline_p
2843 && s->prev->face->underline_type == FACE_UNDER_LINE
2844 && s->prev->underline_thickness > 0)
2846 thickness = s->prev->underline_thickness;
2847 position = s->prev->underline_position;
2852 unsigned long descent;
2855 descent = s->y + s->height - s->ybase;
2857 /* Use underline thickness of font, defaulting to 1. */
2858 thickness = (font && font->underline_thickness > 0)
2859 ? font->underline_thickness : 1;
2861 /* Determine the offset of underlining from the baseline. */
2862 if (x_underline_at_descent_line)
2863 position = descent - thickness;
2864 else if (x_use_underline_position_properties
2865 && font && font->underline_position >= 0)
2866 position = font->underline_position;
2868 position = lround (font->descent / 2);
2870 position = underline_minimum_offset;
2872 position = max (position, underline_minimum_offset);
2874 /* Ensure underlining is not cropped. */
2875 if (descent <= position)
2877 position = descent - 1;
2880 else if (descent < position + thickness)
2884 s->underline_thickness = thickness;
2885 s->underline_position = position;
2887 r = NSMakeRect (x, s->ybase + position, width, thickness);
2889 if (face->underline_defaulted_p)
2892 [ns_lookup_indexed_color (face->underline_color, s->f) set];
2896 /* Do overline. We follow other terms in using a thickness of 1
2897 and ignoring overline_margin. */
2898 if (face->overline_p)
2901 r = NSMakeRect (x, s->y, width, 1);
2903 if (face->overline_color_defaulted_p)
2906 [ns_lookup_indexed_color (face->overline_color, s->f) set];
2910 /* Do strike-through. We follow other terms for thickness and
2911 vertical position.*/
2912 if (face->strike_through_p)
2917 dy = lrint ((s->height - 1) / 2);
2918 r = NSMakeRect (x, s->y + dy, width, 1);
2920 if (face->strike_through_color_defaulted_p)
2923 [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
2929 ns_draw_box (NSRect r, CGFloat thickness, NSColor *col,
2930 char left_p, char right_p)
2931 /* --------------------------------------------------------------------------
2932 Draw an unfilled rect inside r, optionally leaving left and/or right open.
2933 Note we can't just use an NSDrawRect command, because of the possibility
2934 of some sides not being drawn, and because the rect will be filled.
2935 -------------------------------------------------------------------------- */
2941 s.size.height = thickness;
2943 s.origin.y += r.size.height - thickness;
2946 s.size.height = r.size.height;
2947 s.origin.y = r.origin.y;
2949 /* left, right (optional) */
2950 s.size.width = thickness;
2955 s.origin.x += r.size.width - thickness;
2962 ns_draw_relief (NSRect r, int thickness, char raised_p,
2963 char top_p, char bottom_p, char left_p, char right_p,
2964 struct glyph_string *s)
2965 /* --------------------------------------------------------------------------
2966 Draw a relief rect inside r, optionally leaving some sides open.
2967 Note we can't just use an NSDrawBezel command, because of the possibility
2968 of some sides not being drawn, and because the rect will be filled.
2969 -------------------------------------------------------------------------- */
2971 static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2972 NSColor *newBaseCol = nil;
2975 NSTRACE ("ns_draw_relief");
2979 if (s->face->use_box_color_for_shadows_p)
2981 newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2983 /* else if (s->first_glyph->type == IMAGE_GLYPH
2985 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2987 newBaseCol = IMAGE_BACKGROUND (s->img, s->f, 0);
2991 newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2994 if (newBaseCol == nil)
2995 newBaseCol = [NSColor grayColor];
2997 if (newBaseCol != baseCol) /* TODO: better check */
3000 baseCol = [newBaseCol retain];
3002 lightCol = [[baseCol highlightWithLevel: 0.2] retain];
3004 darkCol = [[baseCol shadowWithLevel: 0.3] retain];
3007 [(raised_p ? lightCol : darkCol) set];
3009 /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
3012 sr.size.height = thickness;
3013 if (top_p) NSRectFill (sr);
3016 sr.size.height = r.size.height;
3017 sr.size.width = thickness;
3018 if (left_p) NSRectFill (sr);
3020 [(raised_p ? darkCol : lightCol) set];
3023 sr.size.width = r.size.width;
3024 sr.size.height = thickness;
3025 sr.origin.y += r.size.height - thickness;
3026 if (bottom_p) NSRectFill (sr);
3029 sr.size.height = r.size.height;
3030 sr.origin.y = r.origin.y;
3031 sr.size.width = thickness;
3032 sr.origin.x += r.size.width - thickness;
3033 if (right_p) NSRectFill (sr);
3038 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
3039 /* --------------------------------------------------------------------------
3040 Function modeled after x_draw_glyph_string_box ().
3041 Sets up parameters for drawing.
3042 -------------------------------------------------------------------------- */
3044 int right_x, last_x;
3045 char left_p, right_p;
3046 struct glyph *last_glyph;
3051 if (s->hl == DRAW_MOUSE_FACE)
3053 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3055 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3060 thickness = face->box_line_width;
3062 NSTRACE ("ns_dumpglyphs_box_or_relief");
3064 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
3065 ? WINDOW_RIGHT_EDGE_X (s->w)
3066 : window_box_right (s->w, s->area));
3067 last_glyph = (s->cmp || s->img
3068 ? s->first_glyph : s->first_glyph + s->nchars-1);
3070 right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
3071 ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
3073 left_p = (s->first_glyph->left_box_line_p
3074 || (s->hl == DRAW_MOUSE_FACE
3075 && (s->prev == NULL || s->prev->hl != s->hl)));
3076 right_p = (last_glyph->right_box_line_p
3077 || (s->hl == DRAW_MOUSE_FACE
3078 && (s->next == NULL || s->next->hl != s->hl)));
3080 r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
3082 /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
3083 if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
3085 ns_draw_box (r, abs (thickness),
3086 ns_lookup_indexed_color (face->box_color, s->f),
3091 ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
3092 1, 1, left_p, right_p, s);
3098 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
3099 /* --------------------------------------------------------------------------
3100 Modeled after x_draw_glyph_string_background, which draws BG in
3101 certain cases. Others are left to the text rendering routine.
3102 -------------------------------------------------------------------------- */
3104 NSTRACE ("ns_maybe_dumpglyphs_background");
3106 if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
3108 int box_line_width = max (s->face->box_line_width, 0);
3109 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
3110 /* When xdisp.c ignores FONT_HEIGHT, we cannot trust font
3111 dimensions, since the actual glyphs might be much
3112 smaller. So in that case we always clear the rectangle
3113 with background color. */
3114 || FONT_TOO_HIGH (s->font)
3115 || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
3118 if (s->hl == DRAW_MOUSE_FACE)
3120 face = FACE_FROM_ID (s->f,
3121 MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3123 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3126 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3128 [(NS_FACE_BACKGROUND (face) != 0
3129 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
3130 : FRAME_BACKGROUND_COLOR (s->f)) set];
3133 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (s->f);
3134 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
3137 if (s->hl != DRAW_CURSOR)
3139 NSRect r = NSMakeRect (s->x, s->y + box_line_width,
3140 s->background_width,
3141 s->height-2*box_line_width);
3145 s->background_filled_p = 1;
3152 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
3153 /* --------------------------------------------------------------------------
3154 Renders an image and associated borders.
3155 -------------------------------------------------------------------------- */
3157 EmacsImage *img = s->img->pixmap;
3158 int box_line_vwidth = max (s->face->box_line_width, 0);
3159 int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3160 int bg_x, bg_y, bg_height;
3167 NSTRACE ("ns_dumpglyphs_image");
3169 if (s->face->box != FACE_NO_BOX
3170 && s->first_glyph->left_box_line_p && s->slice.x == 0)
3171 x += abs (s->face->box_line_width);
3174 bg_y = s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
3175 bg_height = s->height;
3176 /* other terms have this, but was causing problems w/tabbar mode */
3177 /* - 2 * box_line_vwidth; */
3179 if (s->slice.x == 0) x += s->img->hmargin;
3180 if (s->slice.y == 0) y += s->img->vmargin;
3182 /* Draw BG: if we need larger area than image itself cleared, do that,
3183 otherwise, since we composite the image under NS (instead of mucking
3184 with its background color), we must clear just the image area. */
3185 if (s->hl == DRAW_MOUSE_FACE)
3187 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3189 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3192 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3194 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
3196 if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
3197 || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
3199 br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
3200 s->background_filled_p = 1;
3204 br = NSMakeRect (x, y, s->slice.width, s->slice.height);
3209 /* Draw the image.. do we need to draw placeholder if img ==nil? */
3212 #ifdef NS_IMPL_COCOA
3213 NSRect dr = NSMakeRect (x, y, s->slice.width, s->slice.height);
3214 NSRect ir = NSMakeRect (s->slice.x, s->slice.y,
3215 s->slice.width, s->slice.height);
3218 operation: NSCompositeSourceOver
3223 [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3224 operation: NSCompositeSourceOver];
3228 if (s->hl == DRAW_CURSOR)
3230 [FRAME_CURSOR_COLOR (s->f) set];
3231 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3232 tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3234 /* Currently on NS img->mask is always 0. Since
3235 get_window_cursor_type specifies a hollow box cursor when on
3236 a non-masked image we never reach this clause. But we put it
3237 in in anticipation of better support for image masks on
3239 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3243 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3246 /* Draw underline, overline, strike-through. */
3247 ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3249 /* Draw relief, if requested */
3250 if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3252 if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3254 th = tool_bar_button_relief >= 0 ?
3255 tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3256 raised_p = (s->hl == DRAW_IMAGE_RAISED);
3260 th = abs (s->img->relief);
3261 raised_p = (s->img->relief > 0);
3264 r.origin.x = x - th;
3265 r.origin.y = y - th;
3266 r.size.width = s->slice.width + 2*th-1;
3267 r.size.height = s->slice.height + 2*th-1;
3268 ns_draw_relief (r, th, raised_p,
3270 s->slice.y + s->slice.height == s->img->height,
3272 s->slice.x + s->slice.width == s->img->width, s);
3275 /* If there is no mask, the background won't be seen,
3276 so draw a rectangle on the image for the cursor.
3277 Do this for all images, getting transparency right is not reliable. */
3278 if (s->hl == DRAW_CURSOR)
3280 int thickness = abs (s->img->relief);
3281 if (thickness == 0) thickness = 1;
3282 ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3288 ns_dumpglyphs_stretch (struct glyph_string *s)
3293 NSColor *fgCol, *bgCol;
3295 if (!s->background_filled_p)
3297 n = ns_get_glyph_string_clip_rect (s, r);
3298 *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3300 ns_focus (s->f, r, n);
3302 if (s->hl == DRAW_MOUSE_FACE)
3304 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3306 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3309 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3311 bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3312 fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3314 for (i = 0; i < n; ++i)
3316 if (!s->row->full_width_p)
3318 int overrun, leftoverrun;
3320 /* truncate to avoid overwriting fringe and/or scrollbar */
3321 overrun = max (0, (s->x + s->background_width)
3322 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3323 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3324 r[i].size.width -= overrun;
3326 /* truncate to avoid overwriting to left of the window box */
3327 leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3328 + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3330 if (leftoverrun > 0)
3332 r[i].origin.x += leftoverrun;
3333 r[i].size.width -= leftoverrun;
3336 /* XXX: Try to work between problem where a stretch glyph on
3337 a partially-visible bottom row will clear part of the
3338 modeline, and another where list-buffers headers and similar
3339 rows erroneously have visible_height set to 0. Not sure
3340 where this is coming from as other terms seem not to show. */
3341 r[i].size.height = min (s->height, s->row->visible_height);
3346 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3347 overwriting cursor (usually when cursor on a tab) */
3348 if (s->hl == DRAW_CURSOR)
3353 width = s->w->phys_cursor_width;
3354 r[i].size.width -= width;
3355 r[i].origin.x += width;
3359 /* Draw overlining, etc. on the cursor. */
3360 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3361 ns_draw_text_decoration (s, face, bgCol, width, x);
3363 ns_draw_text_decoration (s, face, fgCol, width, x);
3370 /* Draw overlining, etc. on the stretch glyph (or the part
3371 of the stretch glyph after the cursor). */
3372 ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3376 s->background_filled_p = 1;
3382 ns_draw_composite_glyph_string_foreground (struct glyph_string *s)
3385 struct font *font = s->font;
3387 /* If first glyph of S has a left box line, start drawing the text
3388 of S to the right of that box line. */
3389 if (s->face && s->face->box != FACE_NO_BOX
3390 && s->first_glyph->left_box_line_p)
3391 x = s->x + eabs (s->face->box_line_width);
3395 /* S is a glyph string for a composition. S->cmp_from is the index
3396 of the first character drawn for glyphs of this composition.
3397 S->cmp_from == 0 means we are drawing the very first character of
3398 this composition. */
3400 /* Draw a rectangle for the composition if the font for the very
3401 first character of the composition could not be loaded. */
3402 if (s->font_not_found_p)
3404 if (s->cmp_from == 0)
3406 NSRect r = NSMakeRect (s->x, s->y, s->width-1, s->height -1);
3407 ns_draw_box (r, 1, FRAME_CURSOR_COLOR (s->f), 1, 1);
3410 else if (! s->first_glyph->u.cmp.automatic)
3414 for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
3415 /* TAB in a composition means display glyphs with padding
3416 space on the left or right. */
3417 if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
3419 int xx = x + s->cmp->offsets[j * 2];
3420 int yy = y - s->cmp->offsets[j * 2 + 1];
3422 font->driver->draw (s, j, j + 1, xx, yy, false);
3423 if (s->face->overstrike)
3424 font->driver->draw (s, j, j + 1, xx + 1, yy, false);
3429 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
3434 for (i = j = s->cmp_from; i < s->cmp_to; i++)
3436 glyph = LGSTRING_GLYPH (gstring, i);
3437 if (NILP (LGLYPH_ADJUSTMENT (glyph)))
3438 width += LGLYPH_WIDTH (glyph);
3441 int xoff, yoff, wadjust;
3445 font->driver->draw (s, j, i, x, y, false);
3446 if (s->face->overstrike)
3447 font->driver->draw (s, j, i, x + 1, y, false);
3450 xoff = LGLYPH_XOFF (glyph);
3451 yoff = LGLYPH_YOFF (glyph);
3452 wadjust = LGLYPH_WADJUST (glyph);
3453 font->driver->draw (s, i, i + 1, x + xoff, y + yoff, false);
3454 if (s->face->overstrike)
3455 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff,
3464 font->driver->draw (s, j, i, x, y, false);
3465 if (s->face->overstrike)
3466 font->driver->draw (s, j, i, x + 1, y, false);
3472 ns_draw_glyph_string (struct glyph_string *s)
3473 /* --------------------------------------------------------------------------
3474 External (RIF): Main draw-text call.
3475 -------------------------------------------------------------------------- */
3477 /* TODO (optimize): focus for box and contents draw */
3480 char box_drawn_p = 0;
3481 struct font *font = s->face->font;
3482 if (! font) font = FRAME_FONT (s->f);
3484 NSTRACE ("ns_draw_glyph_string");
3486 if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3489 struct glyph_string *next;
3491 for (width = 0, next = s->next;
3492 next && width < s->right_overhang;
3493 width += next->width, next = next->next)
3494 if (next->first_glyph->type != IMAGE_GLYPH)
3496 if (next->first_glyph->type != STRETCH_GLYPH)
3498 n = ns_get_glyph_string_clip_rect (s->next, r);
3499 ns_focus (s->f, r, n);
3500 ns_maybe_dumpglyphs_background (s->next, 1);
3505 ns_dumpglyphs_stretch (s->next);
3507 next->num_clips = 0;
3511 if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3512 && (s->first_glyph->type == CHAR_GLYPH
3513 || s->first_glyph->type == COMPOSITE_GLYPH))
3515 n = ns_get_glyph_string_clip_rect (s, r);
3516 ns_focus (s->f, r, n);
3517 ns_maybe_dumpglyphs_background (s, 1);
3518 ns_dumpglyphs_box_or_relief (s);
3523 switch (s->first_glyph->type)
3527 n = ns_get_glyph_string_clip_rect (s, r);
3528 ns_focus (s->f, r, n);
3529 ns_dumpglyphs_image (s, r[0]);
3534 ns_dumpglyphs_stretch (s);
3538 case COMPOSITE_GLYPH:
3539 n = ns_get_glyph_string_clip_rect (s, r);
3540 ns_focus (s->f, r, n);
3542 if (s->for_overlaps || (s->cmp_from > 0
3543 && ! s->first_glyph->u.cmp.automatic))
3544 s->background_filled_p = 1;
3546 ns_maybe_dumpglyphs_background
3547 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3549 flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3550 (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3551 (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3552 NS_DUMPGLYPH_NORMAL));
3554 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3556 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3557 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3558 NS_FACE_FOREGROUND (s->face) = tmp;
3562 BOOL isComposite = s->first_glyph->type == COMPOSITE_GLYPH;
3565 ns_draw_composite_glyph_string_foreground (s);
3568 (s, s->cmp_from, s->nchars, s->x, s->ybase,
3569 (flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3570 || flags == NS_DUMPGLYPH_MOUSEFACE);
3574 NSColor *col = (NS_FACE_FOREGROUND (s->face) != 0
3575 ? ns_lookup_indexed_color (NS_FACE_FOREGROUND (s->face),
3577 : FRAME_FOREGROUND_COLOR (s->f));
3580 /* Draw underline, overline, strike-through. */
3581 ns_draw_text_decoration (s, s->face, col, s->width, s->x);
3584 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3586 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3587 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3588 NS_FACE_FOREGROUND (s->face) = tmp;
3594 case GLYPHLESS_GLYPH:
3595 n = ns_get_glyph_string_clip_rect (s, r);
3596 ns_focus (s->f, r, n);
3598 if (s->for_overlaps || (s->cmp_from > 0
3599 && ! s->first_glyph->u.cmp.automatic))
3600 s->background_filled_p = 1;
3602 ns_maybe_dumpglyphs_background
3603 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3605 /* Not yet implemented. */
3614 /* Draw box if not done already. */
3615 if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3617 n = ns_get_glyph_string_clip_rect (s, r);
3618 ns_focus (s->f, r, n);
3619 ns_dumpglyphs_box_or_relief (s);
3628 /* ==========================================================================
3632 ========================================================================== */
3636 ns_send_appdefined (int value)
3637 /* --------------------------------------------------------------------------
3638 Internal: post an appdefined event which EmacsApp-sendEvent will
3639 recognize and take as a command to halt the event loop.
3640 -------------------------------------------------------------------------- */
3642 NSTRACE ("ns_send_appdefined");
3644 #ifdef NS_IMPL_GNUSTEP
3645 // GNUstep needs postEvent to happen on the main thread.
3646 if (! [[NSThread currentThread] isMainThread])
3648 EmacsApp *app = (EmacsApp *)NSApp;
3649 app->nextappdefined = value;
3650 [app performSelectorOnMainThread:@selector (sendFromMainThread:)
3657 /* Only post this event if we haven't already posted one. This will end
3658 the [NXApp run] main loop after having processed all events queued at
3661 #ifdef NS_IMPL_COCOA
3662 if (! send_appdefined)
3664 /* OSX 10.10.1 swallows the AppDefined event we are sending ourselves
3665 in certain situations (rapid incoming events).
3666 So check if we have one, if not add one. */
3667 NSEvent *appev = [NSApp nextEventMatchingMask:NSApplicationDefinedMask
3668 untilDate:[NSDate distantPast]
3669 inMode:NSDefaultRunLoopMode
3671 if (! appev) send_appdefined = YES;
3675 if (send_appdefined)
3679 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
3680 send_appdefined = NO;
3682 /* Don't need wakeup timer any more */
3685 [timed_entry invalidate];
3686 [timed_entry release];
3690 nxev = [NSEvent otherEventWithType: NSApplicationDefined
3691 location: NSMakePoint (0, 0)
3694 windowNumber: [[NSApp mainWindow] windowNumber]
3695 context: [NSApp context]
3700 /* Post an application defined event on the event queue. When this is
3701 received the [NXApp run] will return, thus having processed all
3702 events which are currently queued. */
3703 [NSApp postEvent: nxev atStart: NO];
3707 #ifdef HAVE_NATIVE_FS
3711 Lisp_Object frame, tail;
3713 if (ns_last_use_native_fullscreen == ns_use_native_fullscreen)
3716 ns_last_use_native_fullscreen = ns_use_native_fullscreen;
3718 FOR_EACH_FRAME (tail, frame)
3720 struct frame *f = XFRAME (frame);
3723 EmacsView *view = FRAME_NS_VIEW (f);
3724 [view updateCollectionBehavior];
3730 /* GNUstep does not have cancelTracking. */
3731 #ifdef NS_IMPL_COCOA
3732 /* Check if menu open should be canceled or continued as normal. */
3734 ns_check_menu_open (NSMenu *menu)
3736 /* Click in menu bar? */
3737 NSArray *a = [[NSApp mainMenu] itemArray];
3741 if (menu == nil) // Menu tracking ended.
3743 if (menu_will_open_state == MENU_OPENING)
3744 menu_will_open_state = MENU_NONE;
3748 for (i = 0; ! found && i < [a count]; i++)
3749 found = menu == [[a objectAtIndex:i] submenu];
3752 if (menu_will_open_state == MENU_NONE && emacs_event)
3754 NSEvent *theEvent = [NSApp currentEvent];
3755 struct frame *emacsframe = SELECTED_FRAME ();
3757 [menu cancelTracking];
3758 menu_will_open_state = MENU_PENDING;
3759 emacs_event->kind = MENU_BAR_ACTIVATE_EVENT;
3760 EV_TRAILER (theEvent);
3762 CGEventRef ourEvent = CGEventCreate (NULL);
3763 menu_mouse_point = CGEventGetLocation (ourEvent);
3764 CFRelease (ourEvent);
3766 else if (menu_will_open_state == MENU_OPENING)
3768 menu_will_open_state = MENU_NONE;
3773 /* Redo saved menu click if state is MENU_PENDING. */
3775 ns_check_pending_open_menu ()
3777 if (menu_will_open_state == MENU_PENDING)
3779 CGEventSourceRef source
3780 = CGEventSourceCreate (kCGEventSourceStateHIDSystemState);
3782 CGEventRef event = CGEventCreateMouseEvent (source,
3783 kCGEventLeftMouseDown,
3785 kCGMouseButtonLeft);
3786 CGEventSetType (event, kCGEventLeftMouseDown);
3787 CGEventPost (kCGHIDEventTap, event);
3791 menu_will_open_state = MENU_OPENING;
3794 #endif /* NS_IMPL_COCOA */
3797 unwind_apploopnr (Lisp_Object not_used)
3800 n_emacs_events_pending = 0;
3801 ns_finish_events ();
3806 ns_read_socket (struct terminal *terminal, struct input_event *hold_quit)
3807 /* --------------------------------------------------------------------------
3808 External (hook): Post an event to ourself and keep reading events until
3809 we read it back again. In effect process all events which were waiting.
3810 From 21+ we have to manage the event buffer ourselves.
3811 -------------------------------------------------------------------------- */
3813 struct input_event ev;
3816 /* NSTRACE ("ns_read_socket"); */
3818 #ifdef HAVE_NATIVE_FS
3822 if ([NSApp modalWindow] != nil)
3825 if (hold_event_q.nr > 0)
3828 for (i = 0; i < hold_event_q.nr; ++i)
3829 kbd_buffer_store_event_hold (&hold_event_q.q[i], hold_quit);
3830 hold_event_q.nr = 0;
3835 n_emacs_events_pending = 0;
3836 ns_init_events (&ev);
3837 q_event_ptr = hold_quit;
3839 /* we manage autorelease pools by allocate/reallocate each time around
3840 the loop; strict nesting is occasionally violated but seems not to
3841 matter.. earlier methods using full nesting caused major memory leaks */
3842 [outerpool release];
3843 outerpool = [[NSAutoreleasePool alloc] init];
3845 /* If have pending open-file requests, attend to the next one of those. */
3846 if (ns_pending_files && [ns_pending_files count] != 0
3847 && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3849 [ns_pending_files removeObjectAtIndex: 0];
3851 /* Deal with pending service requests. */
3852 else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3854 NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3855 withArg: [ns_pending_service_args objectAtIndex: 0]])
3857 [ns_pending_service_names removeObjectAtIndex: 0];
3858 [ns_pending_service_args removeObjectAtIndex: 0];
3862 ptrdiff_t specpdl_count = SPECPDL_INDEX ();
3863 /* Run and wait for events. We must always send one NX_APPDEFINED event
3864 to ourself, otherwise [NXApp run] will never exit. */
3865 send_appdefined = YES;
3866 ns_send_appdefined (-1);
3868 if (++apploopnr != 1)
3872 record_unwind_protect (unwind_apploopnr, Qt);
3874 unbind_to (specpdl_count, Qnil); /* calls unwind_apploopnr */
3877 nevents = n_emacs_events_pending;
3878 n_emacs_events_pending = 0;
3879 ns_finish_events ();
3888 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3889 fd_set *exceptfds, struct timespec const *timeout,
3890 sigset_t const *sigmask)
3891 /* --------------------------------------------------------------------------
3892 Replacement for select, checking for events
3893 -------------------------------------------------------------------------- */
3897 struct input_event event;
3900 /* NSTRACE ("ns_select"); */
3902 #ifdef HAVE_NATIVE_FS
3906 if (hold_event_q.nr > 0)
3908 /* We already have events pending. */
3914 for (k = 0; k < nfds+1; k++)
3916 if (readfds && FD_ISSET(k, readfds)) ++nr;
3917 if (writefds && FD_ISSET(k, writefds)) ++nr;
3921 || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0))
3922 return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
3924 [outerpool release];
3925 outerpool = [[NSAutoreleasePool alloc] init];
3928 send_appdefined = YES;
3931 pthread_mutex_lock (&select_mutex);
3936 select_readfds = *readfds;
3937 select_valid += SELECT_HAVE_READ;
3941 select_writefds = *writefds;
3942 select_valid += SELECT_HAVE_WRITE;
3947 select_timeout = *timeout;
3948 select_valid += SELECT_HAVE_TMO;
3951 pthread_mutex_unlock (&select_mutex);
3953 /* Inform fd_handler that select should be called */
3955 emacs_write_sig (selfds[1], &c, 1);
3957 else if (nr == 0 && timeout)
3959 /* No file descriptor, just a timeout, no need to wake fd_handler */
3960 double time = timespectod (*timeout);
3961 timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3964 @selector (timeout_handler:)
3969 else /* No timeout and no file descriptors, can this happen? */
3971 /* Send appdefined so we exit from the loop */
3972 ns_send_appdefined (-1);
3976 ns_init_events (&event);
3977 if (++apploopnr != 1)
3983 ptrdiff_t specpdl_count = SPECPDL_INDEX ();
3984 record_unwind_protect (unwind_apploopnr, Qt);
3986 unbind_to (specpdl_count, Qnil); /* calls unwind_apploopnr */
3989 ns_finish_events ();
3990 if (nr > 0 && readfds)
3993 emacs_write_sig (selfds[1], &c, 1);
3997 t = last_appdefined_event_data;
3999 if (t != NO_APPDEFINED_DATA)
4001 last_appdefined_event_data = NO_APPDEFINED_DATA;
4005 /* The NX_APPDEFINED event we received was a timeout. */
4010 /* The NX_APPDEFINED event we received was the result of
4011 at least one real input event arriving. */
4017 /* Received back from select () in fd_handler; copy the results */
4018 pthread_mutex_lock (&select_mutex);
4019 if (readfds) *readfds = select_readfds;
4020 if (writefds) *writefds = select_writefds;
4021 pthread_mutex_unlock (&select_mutex);
4036 /* ==========================================================================
4040 ========================================================================== */
4044 ns_set_vertical_scroll_bar (struct window *window,
4045 int portion, int whole, int position)
4046 /* --------------------------------------------------------------------------
4047 External (hook): Update or add scrollbar
4048 -------------------------------------------------------------------------- */
4052 struct frame *f = XFRAME (WINDOW_FRAME (window));
4053 EmacsView *view = FRAME_NS_VIEW (f);
4055 int window_y, window_height;
4056 int top, left, height, width;
4057 BOOL update_p = YES;
4059 /* optimization; display engine sends WAY too many of these.. */
4060 if (!NILP (window->vertical_scroll_bar))
4062 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4063 if ([bar checkSamePosition: position portion: portion whole: whole])
4065 if (view->scrollbarsNeedingUpdate == 0)
4067 if (!windows_or_buffers_changed)
4071 view->scrollbarsNeedingUpdate--;
4076 NSTRACE ("ns_set_vertical_scroll_bar");
4078 /* Get dimensions. */
4079 window_box (window, ANY_AREA, 0, &window_y, 0, &window_height);
4081 height = window_height;
4082 width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
4083 left = WINDOW_SCROLL_BAR_AREA_X (window);
4085 r = NSMakeRect (left, top, width, height);
4086 /* the parent view is flipped, so we need to flip y value */
4088 r.origin.y = (v.size.height - r.size.height - r.origin.y);
4090 XSETWINDOW (win, window);
4093 /* we want at least 5 lines to display a scrollbar */
4094 if (WINDOW_TOTAL_LINES (window) < 5)
4096 if (!NILP (window->vertical_scroll_bar))
4098 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4099 [bar removeFromSuperview];
4100 wset_vertical_scroll_bar (window, Qnil);
4103 ns_clear_frame_area (f, left, top, width, height);
4108 if (NILP (window->vertical_scroll_bar))
4110 if (width > 0 && height > 0)
4111 ns_clear_frame_area (f, left, top, width, height);
4113 bar = [[EmacsScroller alloc] initFrame: r window: win];
4114 wset_vertical_scroll_bar (window, make_save_ptr (bar));
4120 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4121 oldRect = [bar frame];
4122 r.size.width = oldRect.size.width;
4123 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4125 if (oldRect.origin.x != r.origin.x)
4126 ns_clear_frame_area (f, left, top, width, height);
4132 [bar setPosition: position portion: portion whole: whole];
4138 ns_set_horizontal_scroll_bar (struct window *window,
4139 int portion, int whole, int position)
4140 /* --------------------------------------------------------------------------
4141 External (hook): Update or add scrollbar
4142 -------------------------------------------------------------------------- */
4146 struct frame *f = XFRAME (WINDOW_FRAME (window));
4147 EmacsView *view = FRAME_NS_VIEW (f);
4149 int top, height, left, width;
4150 int window_x, window_width;
4151 BOOL update_p = YES;
4153 /* optimization; display engine sends WAY too many of these.. */
4154 if (!NILP (window->horizontal_scroll_bar))
4156 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4157 if ([bar checkSamePosition: position portion: portion whole: whole])
4159 if (view->scrollbarsNeedingUpdate == 0)
4161 if (!windows_or_buffers_changed)
4165 view->scrollbarsNeedingUpdate--;
4170 NSTRACE ("ns_set_horizontal_scroll_bar");
4172 /* Get dimensions. */
4173 window_box (window, ANY_AREA, 0, &window_x, &window_width, 0);
4175 width = window_width;
4176 height = WINDOW_CONFIG_SCROLL_BAR_LINES (window) * FRAME_LINE_HEIGHT (f);
4177 top = WINDOW_SCROLL_BAR_AREA_Y (window);
4179 r = NSMakeRect (left, top, width, height);
4180 /* the parent view is flipped, so we need to flip y value */
4182 /* ??????? PXW/scrollbars !!!!!!!!!!!!!!!!!!!! */
4183 r.origin.y = (v.size.height - r.size.height - r.origin.y);
4185 XSETWINDOW (win, window);
4188 if (WINDOW_TOTAL_COLS (window) < 5)
4190 if (!NILP (window->horizontal_scroll_bar))
4192 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4193 [bar removeFromSuperview];
4194 wset_horizontal_scroll_bar (window, Qnil);
4196 ns_clear_frame_area (f, left, top, width, height);
4201 if (NILP (window->horizontal_scroll_bar))
4203 if (width > 0 && height > 0)
4204 ns_clear_frame_area (f, left, top, width, height);
4206 bar = [[EmacsScroller alloc] initFrame: r window: win];
4207 wset_horizontal_scroll_bar (window, make_save_ptr (bar));
4213 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4214 oldRect = [bar frame];
4215 r.size.width = oldRect.size.width;
4216 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4218 if (oldRect.origin.x != r.origin.x)
4219 ns_clear_frame_area (f, left, top, width, height);
4226 [bar setPosition: position portion: portion whole: whole];
4232 ns_condemn_scroll_bars (struct frame *f)
4233 /* --------------------------------------------------------------------------
4234 External (hook): arrange for all frame's scrollbars to be removed
4235 at next call to judge_scroll_bars, except for those redeemed.
4236 -------------------------------------------------------------------------- */
4240 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
4242 NSTRACE ("ns_condemn_scroll_bars");
4244 for (i =[subviews count]-1; i >= 0; i--)
4246 view = [subviews objectAtIndex: i];
4247 if ([view isKindOfClass: [EmacsScroller class]])
4254 ns_redeem_scroll_bar (struct window *window)
4255 /* --------------------------------------------------------------------------
4256 External (hook): arrange to spare this window's scrollbar
4257 at next call to judge_scroll_bars.
4258 -------------------------------------------------------------------------- */
4261 NSTRACE ("ns_redeem_scroll_bar");
4262 if (!NILP (window->vertical_scroll_bar))
4264 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4268 if (!NILP (window->horizontal_scroll_bar))
4270 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4277 ns_judge_scroll_bars (struct frame *f)
4278 /* --------------------------------------------------------------------------
4279 External (hook): destroy all scrollbars on frame that weren't
4280 redeemed after call to condemn_scroll_bars.
4281 -------------------------------------------------------------------------- */
4285 EmacsView *eview = FRAME_NS_VIEW (f);
4286 NSArray *subviews = [[eview superview] subviews];
4289 NSTRACE ("ns_judge_scroll_bars");
4290 for (i = [subviews count]-1; i >= 0; --i)
4292 view = [subviews objectAtIndex: i];
4293 if (![view isKindOfClass: [EmacsScroller class]]) continue;
4299 [eview updateFrameSize: NO];
4302 /* ==========================================================================
4306 ========================================================================== */
4309 x_display_pixel_height (struct ns_display_info *dpyinfo)
4311 NSArray *screens = [NSScreen screens];
4312 NSEnumerator *enumerator = [screens objectEnumerator];
4317 while ((screen = [enumerator nextObject]) != nil)
4318 frame = NSUnionRect (frame, [screen frame]);
4320 return NSHeight (frame);
4324 x_display_pixel_width (struct ns_display_info *dpyinfo)
4326 NSArray *screens = [NSScreen screens];
4327 NSEnumerator *enumerator = [screens objectEnumerator];
4332 while ((screen = [enumerator nextObject]) != nil)
4333 frame = NSUnionRect (frame, [screen frame]);
4335 return NSWidth (frame);
4339 static Lisp_Object ns_string_to_lispmod (const char *s)
4340 /* --------------------------------------------------------------------------
4341 Convert modifier name to lisp symbol
4342 -------------------------------------------------------------------------- */
4344 if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
4346 else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
4348 else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
4350 else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
4352 else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
4354 else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
4362 ns_default (const char *parameter, Lisp_Object *result,
4363 Lisp_Object yesval, Lisp_Object noval,
4364 BOOL is_float, BOOL is_modstring)
4365 /* --------------------------------------------------------------------------
4366 Check a parameter value in user's preferences
4367 -------------------------------------------------------------------------- */
4369 const char *value = ns_get_defaults_value (parameter);
4375 if (c_strcasecmp (value, "YES") == 0)
4377 else if (c_strcasecmp (value, "NO") == 0)
4379 else if (is_float && (f = strtod (value, &pos), pos != value))
4380 *result = make_float (f);
4381 else if (is_modstring && value)
4382 *result = ns_string_to_lispmod (value);
4383 else fprintf (stderr,
4384 "Bad value for default \"%s\": \"%s\"\n", parameter, value);
4390 ns_initialize_display_info (struct ns_display_info *dpyinfo)
4391 /* --------------------------------------------------------------------------
4392 Initialize global info and storage for display.
4393 -------------------------------------------------------------------------- */
4395 NSScreen *screen = [NSScreen mainScreen];
4396 NSWindowDepth depth = [screen depth];
4398 dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
4399 dpyinfo->resy = 72.27;
4400 dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
4401 NSColorSpaceFromDepth (depth)]
4402 && ![NSCalibratedWhiteColorSpace isEqualToString:
4403 NSColorSpaceFromDepth (depth)];
4404 dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
4405 dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
4406 dpyinfo->color_table->colors = NULL;
4407 dpyinfo->root_window = 42; /* a placeholder.. */
4408 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
4409 dpyinfo->n_fonts = 0;
4410 dpyinfo->smallest_font_height = 1;
4411 dpyinfo->smallest_char_width = 1;
4413 reset_mouse_highlight (&dpyinfo->mouse_highlight);
4417 /* This and next define (many of the) public functions in this file. */
4418 /* x_... are generic versions in xdisp.c that we, and other terms, get away
4419 with using despite presence in the "system dependent" redisplay
4420 interface. In addition, many of the ns_ methods have code that is
4421 shared with all terms, indicating need for further refactoring. */
4422 extern frame_parm_handler ns_frame_parm_handlers[];
4423 static struct redisplay_interface ns_redisplay_interface =
4425 ns_frame_parm_handlers,
4429 x_clear_end_of_line,
4431 ns_after_update_window_line,
4432 ns_update_window_begin,
4433 ns_update_window_end,
4434 0, /* flush_display */
4435 x_clear_window_mouse_face,
4436 x_get_glyph_overhangs,
4437 x_fix_overlapping_area,
4438 ns_draw_fringe_bitmap,
4439 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
4440 0, /* destroy_fringe_bitmap */
4441 ns_compute_glyph_string_overhangs,
4442 ns_draw_glyph_string,
4443 ns_define_frame_cursor,
4444 ns_clear_frame_area,
4445 ns_draw_window_cursor,
4446 ns_draw_vertical_window_border,
4447 ns_draw_window_divider,
4448 ns_shift_glyphs_for_insert,
4455 ns_delete_display (struct ns_display_info *dpyinfo)
4461 /* This function is called when the last frame on a display is deleted. */
4463 ns_delete_terminal (struct terminal *terminal)
4465 struct ns_display_info *dpyinfo = terminal->display_info.ns;
4467 NSTRACE ("ns_delete_terminal");
4469 /* Protect against recursive calls. delete_frame in
4470 delete_terminal calls us back when it deletes our last frame. */
4471 if (!terminal->name)
4476 x_destroy_all_bitmaps (dpyinfo);
4477 ns_delete_display (dpyinfo);
4482 static struct terminal *
4483 ns_create_terminal (struct ns_display_info *dpyinfo)
4484 /* --------------------------------------------------------------------------
4485 Set up use of NS before we make the first connection.
4486 -------------------------------------------------------------------------- */
4488 struct terminal *terminal;
4490 NSTRACE ("ns_create_terminal");
4492 terminal = create_terminal (output_ns, &ns_redisplay_interface);
4494 terminal->display_info.ns = dpyinfo;
4495 dpyinfo->terminal = terminal;
4497 terminal->clear_frame_hook = ns_clear_frame;
4498 terminal->ring_bell_hook = ns_ring_bell;
4499 terminal->update_begin_hook = ns_update_begin;
4500 terminal->update_end_hook = ns_update_end;
4501 terminal->read_socket_hook = ns_read_socket;
4502 terminal->frame_up_to_date_hook = ns_frame_up_to_date;
4503 terminal->mouse_position_hook = ns_mouse_position;
4504 terminal->frame_rehighlight_hook = ns_frame_rehighlight;
4505 terminal->frame_raise_lower_hook = ns_frame_raise_lower;
4506 terminal->fullscreen_hook = ns_fullscreen_hook;
4507 terminal->menu_show_hook = ns_menu_show;
4508 terminal->popup_dialog_hook = ns_popup_dialog;
4509 terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
4510 terminal->set_horizontal_scroll_bar_hook = ns_set_horizontal_scroll_bar;
4511 terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
4512 terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
4513 terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
4514 terminal->delete_frame_hook = x_destroy_window;
4515 terminal->delete_terminal_hook = ns_delete_terminal;
4516 /* Other hooks are NULL by default. */
4522 struct ns_display_info *
4523 ns_term_init (Lisp_Object display_name)
4524 /* --------------------------------------------------------------------------
4525 Start the Application and get things rolling.
4526 -------------------------------------------------------------------------- */
4528 struct terminal *terminal;
4529 struct ns_display_info *dpyinfo;
4530 static int ns_initialized = 0;
4533 if (ns_initialized) return x_display_list;
4538 NSTRACE ("ns_term_init");
4540 [outerpool release];
4541 outerpool = [[NSAutoreleasePool alloc] init];
4543 /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4544 /*GSDebugAllocationActive (YES); */
4548 Fset_input_interrupt_mode (Qnil);
4550 if (selfds[0] == -1)
4552 if (emacs_pipe (selfds) != 0)
4554 fprintf (stderr, "Failed to create pipe: %s\n",
4555 emacs_strerror (errno));
4559 fcntl (selfds[0], F_SETFL, O_NONBLOCK|fcntl (selfds[0], F_GETFL));
4560 FD_ZERO (&select_readfds);
4561 FD_ZERO (&select_writefds);
4562 pthread_mutex_init (&select_mutex, NULL);
4565 ns_pending_files = [[NSMutableArray alloc] init];
4566 ns_pending_service_names = [[NSMutableArray alloc] init];
4567 ns_pending_service_args = [[NSMutableArray alloc] init];
4569 /* Start app and create the main menu, window, view.
4570 Needs to be here because ns_initialize_display_info () uses AppKit classes.
4571 The view will then ask the NSApp to stop and return to Emacs. */
4572 [EmacsApp sharedApplication];
4575 [NSApp setDelegate: NSApp];
4577 /* Start the select thread. */
4578 [NSThread detachNewThreadSelector:@selector (fd_handler:)
4582 /* debugging: log all notifications */
4583 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
4584 selector: @selector (logNotification:)
4585 name: nil object: nil]; */
4587 dpyinfo = xzalloc (sizeof *dpyinfo);
4589 ns_initialize_display_info (dpyinfo);
4590 terminal = ns_create_terminal (dpyinfo);
4592 terminal->kboard = allocate_kboard (Qns);
4593 /* Don't let the initial kboard remain current longer than necessary.
4594 That would cause problems if a file loaded on startup tries to
4595 prompt in the mini-buffer. */
4596 if (current_kboard == initial_kboard)
4597 current_kboard = terminal->kboard;
4598 terminal->kboard->reference_count++;
4600 dpyinfo->next = x_display_list;
4601 x_display_list = dpyinfo;
4603 dpyinfo->name_list_element = Fcons (display_name, Qnil);
4605 terminal->name = xlispstrdup (display_name);
4609 if (!inhibit_x_resources)
4611 ns_default ("GSFontAntiAlias", &ns_antialias_text,
4614 /* this is a standard variable */
4615 ns_default ("AppleAntiAliasingThreshold", &tmp,
4616 make_float (10.0), make_float (6.0), YES, NO);
4617 ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4620 NSTRACE_MSG ("Colors");
4623 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4627 Lisp_Object color_file, color_map, color;
4631 color_file = Fexpand_file_name (build_string ("rgb.txt"),
4632 Fsymbol_value (intern ("data-directory")));
4634 color_map = Fx_load_color_file (color_file);
4635 if (NILP (color_map))
4636 fatal ("Could not read %s.\n", SDATA (color_file));
4638 cl = [[NSColorList alloc] initWithName: @"Emacs"];
4639 for ( ; CONSP (color_map); color_map = XCDR (color_map))
4641 color = XCAR (color_map);
4642 name = SSDATA (XCAR (color));
4643 c = XINT (XCDR (color));
4645 [NSColor colorForEmacsRed: RED_FROM_ULONG (c) / 255.0
4646 green: GREEN_FROM_ULONG (c) / 255.0
4647 blue: BLUE_FROM_ULONG (c) / 255.0
4649 forKey: [NSString stringWithUTF8String: name]];
4651 [cl writeToFile: nil];
4655 NSTRACE_MSG ("Versions");
4658 #ifdef NS_IMPL_GNUSTEP
4659 Vwindow_system_version = build_string (gnustep_base_version);
4661 /*PSnextrelease (128, c); */
4662 char c[DBL_BUFSIZE_BOUND];
4663 int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4664 Vwindow_system_version = make_unibyte_string (c, len);
4668 delete_keyboard_wait_descriptor (0);
4670 ns_app_name = [[NSProcessInfo processInfo] processName];
4672 /* Set up OS X app menu */
4674 NSTRACE_MSG ("Menu init");
4676 #ifdef NS_IMPL_COCOA
4680 /* set up the application menu */
4681 svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4682 [svcsMenu setAutoenablesItems: NO];
4683 appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4684 [appMenu setAutoenablesItems: NO];
4685 mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4686 dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4688 [appMenu insertItemWithTitle: @"About Emacs"
4689 action: @selector (orderFrontStandardAboutPanel:)
4692 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4693 [appMenu insertItemWithTitle: @"Preferences..."
4694 action: @selector (showPreferencesWindow:)
4697 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4698 item = [appMenu insertItemWithTitle: @"Services"
4699 action: @selector (menuDown:)
4702 [appMenu setSubmenu: svcsMenu forItem: item];
4703 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4704 [appMenu insertItemWithTitle: @"Hide Emacs"
4705 action: @selector (hide:)
4708 item = [appMenu insertItemWithTitle: @"Hide Others"
4709 action: @selector (hideOtherApplications:)
4712 [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4713 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4714 [appMenu insertItemWithTitle: @"Quit Emacs"
4715 action: @selector (terminate:)
4719 item = [mainMenu insertItemWithTitle: ns_app_name
4720 action: @selector (menuDown:)
4723 [mainMenu setSubmenu: appMenu forItem: item];
4724 [dockMenu insertItemWithTitle: @"New Frame"
4725 action: @selector (newFrame:)
4729 [NSApp setMainMenu: mainMenu];
4730 [NSApp setAppleMenu: appMenu];
4731 [NSApp setServicesMenu: svcsMenu];
4732 /* Needed at least on Cocoa, to get dock menu to show windows */
4733 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4735 [[NSNotificationCenter defaultCenter]
4736 addObserver: mainMenu
4737 selector: @selector (trackingNotification:)
4738 name: NSMenuDidBeginTrackingNotification object: mainMenu];
4739 [[NSNotificationCenter defaultCenter]
4740 addObserver: mainMenu
4741 selector: @selector (trackingNotification:)
4742 name: NSMenuDidEndTrackingNotification object: mainMenu];
4744 #endif /* MAC OS X menu setup */
4746 /* Register our external input/output types, used for determining
4747 applicable services and also drag/drop eligibility. */
4749 NSTRACE_MSG ("Input/output types");
4751 ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
4752 ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
4754 ns_drag_types = [[NSArray arrayWithObjects:
4756 NSTabularTextPboardType,
4757 NSFilenamesPboardType,
4758 NSURLPboardType, nil] retain];
4760 /* If fullscreen is in init/default-frame-alist, focus isn't set
4761 right for fullscreen windows, so set this. */
4762 [NSApp activateIgnoringOtherApps:YES];
4764 NSTRACE_MSG ("Call NSApp run");
4767 ns_do_open_file = YES;
4769 #ifdef NS_IMPL_GNUSTEP
4770 /* GNUstep steals SIGCHLD for use in NSTask, but we don't use NSTask.
4771 We must re-catch it so subprocess works. */
4772 catch_child_signal ();
4775 NSTRACE_MSG ("ns_term_init done");
4784 ns_term_shutdown (int sig)
4786 [[NSUserDefaults standardUserDefaults] synchronize];
4788 /* code not reached in emacs.c after this is called by shut_down_emacs: */
4789 if (STRINGP (Vauto_save_list_file_name))
4790 unlink (SSDATA (Vauto_save_list_file_name));
4792 if (sig == 0 || sig == SIGTERM)
4794 [NSApp terminate: NSApp];
4796 else // force a stack trace to happen
4803 /* ==========================================================================
4805 EmacsApp implementation
4807 ========================================================================== */
4810 @implementation EmacsApp
4814 NSTRACE ("[EmacsApp init]");
4816 if ((self = [super init]))
4818 #ifdef NS_IMPL_COCOA
4819 self->isFirst = YES;
4821 #ifdef NS_IMPL_GNUSTEP
4822 self->applicationDidFinishLaunchingCalled = NO;
4829 #ifdef NS_IMPL_COCOA
4832 NSTRACE ("[EmacsApp run]");
4834 #ifndef NSAppKitVersionNumber10_9
4835 #define NSAppKitVersionNumber10_9 1265
4838 if ((int)NSAppKitVersionNumber != NSAppKitVersionNumber10_9)
4844 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
4846 if (isFirst) [self finishLaunching];
4849 shouldKeepRunning = YES;
4853 pool = [[NSAutoreleasePool alloc] init];
4856 [self nextEventMatchingMask:NSAnyEventMask
4857 untilDate:[NSDate distantFuture]
4858 inMode:NSDefaultRunLoopMode
4861 [self sendEvent:event];
4862 [self updateWindows];
4863 } while (shouldKeepRunning);
4868 - (void)stop: (id)sender
4870 NSTRACE ("[EmacsApp stop]");
4872 shouldKeepRunning = NO;
4873 // Stop possible dialog also. Noop if no dialog present.
4874 // The file dialog still leaks 7k - 10k on 10.9 though.
4875 [super stop:sender];
4877 #endif /* NS_IMPL_COCOA */
4879 - (void)logNotification: (NSNotification *)notification
4881 NSTRACE ("[EmacsApp logNotification]");
4883 const char *name = [[notification name] UTF8String];
4884 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4885 && !strstr (name, "WindowNumber"))
4886 NSLog (@"notification: '%@'", [notification name]);
4890 - (void)sendEvent: (NSEvent *)theEvent
4891 /* --------------------------------------------------------------------------
4892 Called when NSApp is running for each event received. Used to stop
4893 the loop when we choose, since there's no way to just run one iteration.
4894 -------------------------------------------------------------------------- */
4896 int type = [theEvent type];
4897 NSWindow *window = [theEvent window];
4899 NSTRACE ("[EmacsApp sendEvent]");
4900 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4902 #ifdef NS_IMPL_GNUSTEP
4903 // Keyboard events aren't propagated to file dialogs for some reason.
4904 if ([NSApp modalWindow] != nil &&
4905 (type == NSKeyDown || type == NSKeyUp || type == NSFlagsChanged))
4907 [[NSApp modalWindow] sendEvent: theEvent];
4912 if (represented_filename != nil && represented_frame)
4914 NSString *fstr = represented_filename;
4915 NSView *view = FRAME_NS_VIEW (represented_frame);
4916 #ifdef NS_IMPL_COCOA
4917 /* work around a bug observed on 10.3 and later where
4918 setTitleWithRepresentedFilename does not clear out previous state
4919 if given filename does not exist */
4920 if (! [[NSFileManager defaultManager] fileExistsAtPath: fstr])
4921 [[view window] setRepresentedFilename: @""];
4923 [[view window] setRepresentedFilename: fstr];
4924 [represented_filename release];
4925 represented_filename = nil;
4926 represented_frame = NULL;
4929 if (type == NSApplicationDefined)
4931 switch ([theEvent data2])
4933 #ifdef NS_IMPL_COCOA
4934 case NSAPP_DATA2_RUNASSCRIPT:
4939 case NSAPP_DATA2_RUNFILEDIALOG:
4940 ns_run_file_dialog ();
4946 if (type == NSCursorUpdate && window == nil)
4948 fprintf (stderr, "Dropping external cursor update event.\n");
4952 if (type == NSApplicationDefined)
4954 /* Events posted by ns_send_appdefined interrupt the run loop here.
4955 But, if a modal window is up, an appdefined can still come through,
4956 (e.g., from a makeKeyWindow event) but stopping self also stops the
4957 modal loop. Just defer it until later. */
4958 if ([NSApp modalWindow] == nil)
4960 last_appdefined_event_data = [theEvent data1];
4965 send_appdefined = YES;
4970 #ifdef NS_IMPL_COCOA
4971 /* If no dialog and none of our frames have focus and it is a move, skip it.
4972 It is a mouse move in an auxiliary menu, i.e. on the top right on OSX,
4973 such as Wifi, sound, date or similar.
4974 This prevents "spooky" highlighting in the frame under the menu. */
4975 if (type == NSMouseMoved && [NSApp modalWindow] == nil)
4977 struct ns_display_info *di;
4978 BOOL has_focus = NO;
4979 for (di = x_display_list; ! has_focus && di; di = di->next)
4980 has_focus = di->x_focus_frame != 0;
4986 [super sendEvent: theEvent];
4990 - (void)showPreferencesWindow: (id)sender
4992 struct frame *emacsframe = SELECTED_FRAME ();
4993 NSEvent *theEvent = [NSApp currentEvent];
4997 emacs_event->kind = NS_NONKEY_EVENT;
4998 emacs_event->code = KEY_NS_SHOW_PREFS;
4999 emacs_event->modifiers = 0;
5000 EV_TRAILER (theEvent);
5004 - (void)newFrame: (id)sender
5006 NSTRACE ("[EmacsApp newFrame]");
5008 struct frame *emacsframe = SELECTED_FRAME ();
5009 NSEvent *theEvent = [NSApp currentEvent];
5013 emacs_event->kind = NS_NONKEY_EVENT;
5014 emacs_event->code = KEY_NS_NEW_FRAME;
5015 emacs_event->modifiers = 0;
5016 EV_TRAILER (theEvent);
5020 /* Open a file (used by below, after going into queue read by ns_read_socket) */
5021 - (BOOL) openFile: (NSString *)fileName
5023 NSTRACE ("[EmacsApp openFile]");
5025 struct frame *emacsframe = SELECTED_FRAME ();
5026 NSEvent *theEvent = [NSApp currentEvent];
5031 emacs_event->kind = NS_NONKEY_EVENT;
5032 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
5033 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
5034 ns_input_line = Qnil; /* can be start or cons start,end */
5035 emacs_event->modifiers =0;
5036 EV_TRAILER (theEvent);
5042 /* **************************************************************************
5044 EmacsApp delegate implementation
5046 ************************************************************************** */
5048 - (void)applicationDidFinishLaunching: (NSNotification *)notification
5049 /* --------------------------------------------------------------------------
5050 When application is loaded, terminate event loop in ns_term_init
5051 -------------------------------------------------------------------------- */
5053 NSTRACE ("[EmacsApp applicationDidFinishLaunching]");
5055 #ifdef NS_IMPL_GNUSTEP
5056 ((EmacsApp *)self)->applicationDidFinishLaunchingCalled = YES;
5058 [NSApp setServicesProvider: NSApp];
5060 [self antialiasThresholdDidChange:nil];
5061 #ifdef NS_IMPL_COCOA
5062 [[NSNotificationCenter defaultCenter]
5064 selector:@selector(antialiasThresholdDidChange:)
5065 name:NSAntialiasThresholdChangedNotification
5069 ns_send_appdefined (-2);
5072 - (void)antialiasThresholdDidChange:(NSNotification *)notification
5074 #ifdef NS_IMPL_COCOA
5075 macfont_update_antialias_threshold ();
5080 /* Termination sequences:
5083 MenuBar | File | Exit:
5084 Select Quit from App menubar:
5086 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5089 Select Quit from Dock menu:
5092 Cancel -> Nothing else
5096 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5101 - (void) terminate: (id)sender
5103 NSTRACE ("[EmacsApp terminate]");
5105 struct frame *emacsframe = SELECTED_FRAME ();
5110 emacs_event->kind = NS_NONKEY_EVENT;
5111 emacs_event->code = KEY_NS_POWER_OFF;
5112 emacs_event->arg = Qt; /* mark as non-key event */
5113 EV_TRAILER ((id)nil);
5117 runAlertPanel(NSString *title,
5118 NSString *msgFormat,
5119 NSString *defaultButton,
5120 NSString *alternateButton)
5122 #if !defined (NS_IMPL_COCOA) || \
5123 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
5124 return NSRunAlertPanel(title, msgFormat, defaultButton, alternateButton, nil)
5125 == NSAlertDefaultReturn;
5127 NSAlert *alert = [[NSAlert alloc] init];
5128 [alert setAlertStyle: NSCriticalAlertStyle];
5129 [alert setMessageText: msgFormat];
5130 [alert addButtonWithTitle: defaultButton];
5131 [alert addButtonWithTitle: alternateButton];
5132 NSInteger ret = [alert runModal];
5134 return ret == NSAlertFirstButtonReturn;
5139 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
5141 NSTRACE ("[EmacsApp applicationShouldTerminate]");
5145 if (NILP (ns_confirm_quit)) // || ns_shutdown_properly --> TO DO
5146 return NSTerminateNow;
5148 ret = runAlertPanel(ns_app_name,
5149 @"Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?",
5150 @"Save Buffers and Exit", @"Cancel");
5153 return NSTerminateNow;
5155 return NSTerminateCancel;
5156 return NSTerminateNow; /* just in case */
5160 not_in_argv (NSString *arg)
5163 const char *a = [arg UTF8String];
5164 for (k = 1; k < initial_argc; ++k)
5165 if (strcmp (a, initial_argv[k]) == 0) return 0;
5169 /* Notification from the Workspace to open a file */
5170 - (BOOL)application: sender openFile: (NSString *)file
5172 if (ns_do_open_file || not_in_argv (file))
5173 [ns_pending_files addObject: file];
5178 /* Open a file as a temporary file */
5179 - (BOOL)application: sender openTempFile: (NSString *)file
5181 if (ns_do_open_file || not_in_argv (file))
5182 [ns_pending_files addObject: file];
5187 /* Notification from the Workspace to open a file noninteractively (?) */
5188 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
5190 if (ns_do_open_file || not_in_argv (file))
5191 [ns_pending_files addObject: file];
5195 /* Notification from the Workspace to open multiple files */
5196 - (void)application: sender openFiles: (NSArray *)fileList
5198 NSEnumerator *files = [fileList objectEnumerator];
5200 /* Don't open files from the command line unconditionally,
5201 Cocoa parses the command line wrong, --option value tries to open value
5202 if --option is the last option. */
5203 while ((file = [files nextObject]) != nil)
5204 if (ns_do_open_file || not_in_argv (file))
5205 [ns_pending_files addObject: file];
5207 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
5212 /* Handle dock menu requests. */
5213 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
5219 /* TODO: these may help w/IO switching btwn terminal and NSApp */
5220 - (void)applicationWillBecomeActive: (NSNotification *)notification
5222 NSTRACE ("[EmacsApp applicationWillBecomeActive]");
5223 //ns_app_active=YES;
5226 - (void)applicationDidBecomeActive: (NSNotification *)notification
5228 NSTRACE ("[EmacsApp applicationDidBecomeActive]");
5230 #ifdef NS_IMPL_GNUSTEP
5231 if (! applicationDidFinishLaunchingCalled)
5232 [self applicationDidFinishLaunching:notification];
5234 //ns_app_active=YES;
5236 ns_update_auto_hide_menu_bar ();
5237 // No constraining takes place when the application is not active.
5238 ns_constrain_all_frames ();
5240 - (void)applicationDidResignActive: (NSNotification *)notification
5242 NSTRACE ("[EmacsApp applicationDidResignActive]");
5245 ns_send_appdefined (-1);
5250 /* ==========================================================================
5252 EmacsApp aux handlers for managing event loop
5254 ========================================================================== */
5257 - (void)timeout_handler: (NSTimer *)timedEntry
5258 /* --------------------------------------------------------------------------
5259 The timeout specified to ns_select has passed.
5260 -------------------------------------------------------------------------- */
5262 /*NSTRACE ("timeout_handler"); */
5263 ns_send_appdefined (-2);
5266 #ifdef NS_IMPL_GNUSTEP
5267 - (void)sendFromMainThread:(id)unused
5269 ns_send_appdefined (nextappdefined);
5273 - (void)fd_handler:(id)unused
5274 /* --------------------------------------------------------------------------
5275 Check data waiting on file descriptors and terminate if so
5276 -------------------------------------------------------------------------- */
5279 int waiting = 1, nfds;
5282 fd_set readfds, writefds, *wfds;
5283 struct timespec timeout, *tmo;
5284 NSAutoreleasePool *pool = nil;
5286 /* NSTRACE ("fd_handler"); */
5291 pool = [[NSAutoreleasePool alloc] init];
5297 FD_SET (selfds[0], &fds);
5298 result = select (selfds[0]+1, &fds, NULL, NULL, NULL);
5299 if (result > 0 && read (selfds[0], &c, 1) == 1 && c == 'g')
5304 pthread_mutex_lock (&select_mutex);
5307 if (select_valid & SELECT_HAVE_READ)
5308 readfds = select_readfds;
5312 if (select_valid & SELECT_HAVE_WRITE)
5314 writefds = select_writefds;
5319 if (select_valid & SELECT_HAVE_TMO)
5321 timeout = select_timeout;
5327 pthread_mutex_unlock (&select_mutex);
5329 FD_SET (selfds[0], &readfds);
5330 if (selfds[0] >= nfds) nfds = selfds[0]+1;
5332 result = pselect (nfds, &readfds, wfds, NULL, tmo, NULL);
5335 ns_send_appdefined (-2);
5336 else if (result > 0)
5338 if (FD_ISSET (selfds[0], &readfds))
5340 if (read (selfds[0], &c, 1) == 1 && c == 's')
5345 pthread_mutex_lock (&select_mutex);
5346 if (select_valid & SELECT_HAVE_READ)
5347 select_readfds = readfds;
5348 if (select_valid & SELECT_HAVE_WRITE)
5349 select_writefds = writefds;
5350 if (select_valid & SELECT_HAVE_TMO)
5351 select_timeout = timeout;
5352 pthread_mutex_unlock (&select_mutex);
5354 ns_send_appdefined (result);
5364 /* ==========================================================================
5368 ========================================================================== */
5370 /* called from system: queue for next pass through event loop */
5371 - (void)requestService: (NSPasteboard *)pboard
5372 userData: (NSString *)userData
5373 error: (NSString **)error
5375 [ns_pending_service_names addObject: userData];
5376 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
5377 SSDATA (ns_string_from_pasteboard (pboard))]];
5381 /* called from ns_read_socket to clear queue */
5382 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
5384 struct frame *emacsframe = SELECTED_FRAME ();
5385 NSEvent *theEvent = [NSApp currentEvent];
5390 emacs_event->kind = NS_NONKEY_EVENT;
5391 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
5392 ns_input_spi_name = build_string ([name UTF8String]);
5393 ns_input_spi_arg = build_string ([arg UTF8String]);
5394 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5395 EV_TRAILER (theEvent);
5405 /* ==========================================================================
5407 EmacsView implementation
5409 ========================================================================== */
5412 @implementation EmacsView
5414 /* needed to inform when window closed from LISP */
5415 - (void) setWindowClosing: (BOOL)closing
5417 windowClosing = closing;
5423 NSTRACE ("EmacsView_dealloc");
5425 if (fs_state == FULLSCREEN_BOTH)
5426 [nonfs_window release];
5431 /* called on font panel selection */
5432 - (void)changeFont: (id)sender
5434 NSEvent *e = [[self window] currentEvent];
5435 struct face *face = FRAME_DEFAULT_FACE (emacsframe);
5436 struct font *font = face->font;
5441 NSTRACE ("changeFont");
5446 #ifdef NS_IMPL_GNUSTEP
5447 nsfont = ((struct nsfont_info *)font)->nsfont;
5449 #ifdef NS_IMPL_COCOA
5450 nsfont = (NSFont *) macfont_get_nsctfont (font);
5453 if ((newFont = [sender convertFont: nsfont]))
5455 SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
5457 emacs_event->kind = NS_NONKEY_EVENT;
5458 emacs_event->modifiers = 0;
5459 emacs_event->code = KEY_NS_CHANGE_FONT;
5461 size = [newFont pointSize];
5462 ns_input_fontsize = make_number (lrint (size));
5463 ns_input_font = build_string ([[newFont familyName] UTF8String]);
5469 - (BOOL)acceptsFirstResponder
5471 NSTRACE ("acceptsFirstResponder");
5476 - (void)resetCursorRects
5478 NSRect visible = [self visibleRect];
5479 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
5480 NSTRACE ("resetCursorRects");
5482 if (currentCursor == nil)
5483 currentCursor = [NSCursor arrowCursor];
5485 if (!NSIsEmptyRect (visible))
5486 [self addCursorRect: visible cursor: currentCursor];
5487 [currentCursor setOnMouseEntered: YES];
5492 /*****************************************************************************/
5493 /* Keyboard handling. */
5496 - (void)keyDown: (NSEvent *)theEvent
5498 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5500 unsigned fnKeysym = 0;
5501 static NSMutableArray *nsEvArray;
5503 unsigned int flags = [theEvent modifierFlags];
5505 NSTRACE ("keyDown");
5507 /* Rhapsody and OS X give up and down events for the arrow keys */
5508 if (ns_fake_keydown == YES)
5509 ns_fake_keydown = NO;
5510 else if ([theEvent type] != NSKeyDown)
5516 if (![[self window] isKeyWindow]
5517 && [[theEvent window] isKindOfClass: [EmacsWindow class]]
5518 /* we must avoid an infinite loop here. */
5519 && (EmacsView *)[[theEvent window] delegate] != self)
5521 /* XXX: There is an occasional condition in which, when Emacs display
5522 updates a different frame from the current one, and temporarily
5523 selects it, then processes some interrupt-driven input
5524 (dispnew.c:3878), OS will send the event to the correct NSWindow, but
5525 for some reason that window has its first responder set to the NSView
5526 most recently updated (I guess), which is not the correct one. */
5527 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
5531 if (nsEvArray == nil)
5532 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
5534 [NSCursor setHiddenUntilMouseMoves: YES];
5536 if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
5538 clear_mouse_face (hlinfo);
5539 hlinfo->mouse_face_hidden = 1;
5542 if (!processingCompose)
5544 /* When using screen sharing, no left or right information is sent,
5545 so use Left key in those cases. */
5546 int is_left_key, is_right_key;
5548 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
5549 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
5551 /* (Carbon way: [theEvent keyCode]) */
5553 /* is it a "function key"? */
5554 /* Note: Sometimes a plain key will have the NSNumericPadKeyMask
5555 flag set (this is probably a bug in the OS).
5557 if (code < 0x00ff && (flags&NSNumericPadKeyMask))
5559 fnKeysym = ns_convert_key ([theEvent keyCode] | NSNumericPadKeyMask);
5563 fnKeysym = ns_convert_key (code);
5568 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
5569 because Emacs treats Delete and KP-Delete same (in simple.el). */
5570 if ((fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
5571 #ifdef NS_IMPL_GNUSTEP
5572 /* GNUstep uses incompatible keycodes, even for those that are
5573 supposed to be hardware independent. Just check for delete.
5574 Keypad delete does not have keysym 0xFFFF.
5575 See http://savannah.gnu.org/bugs/?25395
5577 || (fnKeysym == 0xFFFF && code == 127)
5580 code = 0xFF08; /* backspace */
5585 /* are there modifiers? */
5586 emacs_event->modifiers = 0;
5588 if (flags & NSHelpKeyMask)
5589 emacs_event->modifiers |= hyper_modifier;
5591 if (flags & NSShiftKeyMask)
5592 emacs_event->modifiers |= shift_modifier;
5594 is_right_key = (flags & NSRightCommandKeyMask) == NSRightCommandKeyMask;
5595 is_left_key = (flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask
5596 || (! is_right_key && (flags & NSCommandKeyMask) == NSCommandKeyMask);
5599 emacs_event->modifiers |= parse_solitary_modifier
5600 (EQ (ns_right_command_modifier, Qleft)
5601 ? ns_command_modifier
5602 : ns_right_command_modifier);
5606 emacs_event->modifiers |= parse_solitary_modifier
5607 (ns_command_modifier);
5609 /* if super (default), take input manager's word so things like
5610 dvorak / qwerty layout work */
5611 if (EQ (ns_command_modifier, Qsuper)
5613 && [[theEvent characters] length] != 0)
5615 /* XXX: the code we get will be unshifted, so if we have
5616 a shift modifier, must convert ourselves */
5617 if (!(flags & NSShiftKeyMask))
5618 code = [[theEvent characters] characterAtIndex: 0];
5620 /* this is ugly and also requires linking w/Carbon framework
5621 (for LMGetKbdType) so for now leave this rare (?) case
5622 undealt with.. in future look into CGEvent methods */
5625 long smv = GetScriptManagerVariable (smKeyScript);
5626 Handle uchrHandle = GetResource
5627 ('uchr', GetScriptVariable (smv, smScriptKeys));
5629 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
5630 [[theEvent characters] characterAtIndex: 0],
5631 kUCKeyActionDisplay,
5632 (flags & ~NSCommandKeyMask) >> 8,
5633 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
5634 &dummy, 1, &dummy, &code);
5641 is_right_key = (flags & NSRightControlKeyMask) == NSRightControlKeyMask;
5642 is_left_key = (flags & NSLeftControlKeyMask) == NSLeftControlKeyMask
5643 || (! is_right_key && (flags & NSControlKeyMask) == NSControlKeyMask);
5646 emacs_event->modifiers |= parse_solitary_modifier
5647 (EQ (ns_right_control_modifier, Qleft)
5648 ? ns_control_modifier
5649 : ns_right_control_modifier);
5652 emacs_event->modifiers |= parse_solitary_modifier
5653 (ns_control_modifier);
5655 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
5656 emacs_event->modifiers |=
5657 parse_solitary_modifier (ns_function_modifier);
5659 left_is_none = NILP (ns_alternate_modifier)
5660 || EQ (ns_alternate_modifier, Qnone);
5662 is_right_key = (flags & NSRightAlternateKeyMask)
5663 == NSRightAlternateKeyMask;
5664 is_left_key = (flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask
5666 && (flags & NSAlternateKeyMask) == NSAlternateKeyMask);
5670 if ((NILP (ns_right_alternate_modifier)
5671 || EQ (ns_right_alternate_modifier, Qnone)
5672 || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
5674 { /* accept pre-interp alt comb */
5675 if ([[theEvent characters] length] > 0)
5676 code = [[theEvent characters] characterAtIndex: 0];
5677 /*HACK: clear lone shift modifier to stop next if from firing */
5678 if (emacs_event->modifiers == shift_modifier)
5679 emacs_event->modifiers = 0;
5682 emacs_event->modifiers |= parse_solitary_modifier
5683 (EQ (ns_right_alternate_modifier, Qleft)
5684 ? ns_alternate_modifier
5685 : ns_right_alternate_modifier);
5688 if (is_left_key) /* default = meta */
5690 if (left_is_none && !fnKeysym)
5691 { /* accept pre-interp alt comb */
5692 if ([[theEvent characters] length] > 0)
5693 code = [[theEvent characters] characterAtIndex: 0];
5694 /*HACK: clear lone shift modifier to stop next if from firing */
5695 if (emacs_event->modifiers == shift_modifier)
5696 emacs_event->modifiers = 0;
5699 emacs_event->modifiers |=
5700 parse_solitary_modifier (ns_alternate_modifier);
5704 fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
5705 code, fnKeysym, flags, emacs_event->modifiers);
5707 /* if it was a function key or had modifiers, pass it directly to emacs */
5708 if (fnKeysym || (emacs_event->modifiers
5709 && (emacs_event->modifiers != shift_modifier)
5710 && [[theEvent charactersIgnoringModifiers] length] > 0))
5711 /*[[theEvent characters] length] */
5713 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5715 code |= (1<<28)|(3<<16);
5716 else if (code == 0x7f)
5717 code |= (1<<28)|(3<<16);
5719 emacs_event->kind = code > 0xFF
5720 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5722 emacs_event->code = code;
5723 EV_TRAILER (theEvent);
5724 processingCompose = NO;
5730 if (NS_KEYLOG && !processingCompose)
5731 fprintf (stderr, "keyDown: Begin compose sequence.\n");
5733 processingCompose = YES;
5734 [nsEvArray addObject: theEvent];
5735 [self interpretKeyEvents: nsEvArray];
5736 [nsEvArray removeObject: theEvent];
5740 #ifdef NS_IMPL_COCOA
5741 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
5742 decided not to send key-down for.
5743 See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
5744 This only applies on Tiger and earlier.
5745 If it matches one of these, send it on to keyDown. */
5746 -(void)keyUp: (NSEvent *)theEvent
5748 int flags = [theEvent modifierFlags];
5749 int code = [theEvent keyCode];
5750 if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
5751 code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
5754 fprintf (stderr, "keyUp: passed test");
5755 ns_fake_keydown = YES;
5756 [self keyDown: theEvent];
5762 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
5765 /* <NSTextInput>: called when done composing;
5766 NOTE: also called when we delete over working text, followed immed.
5767 by doCommandBySelector: deleteBackward: */
5768 - (void)insertText: (id)aString
5771 int len = [(NSString *)aString length];
5775 NSLog (@"insertText '%@'\tlen = %d", aString, len);
5776 processingCompose = NO;
5781 /* first, clear any working text */
5782 if (workingText != nil)
5783 [self deleteWorkingText];
5785 /* now insert the string as keystrokes */
5786 for (i =0; i<len; i++)
5788 code = [aString characterAtIndex: i];
5789 /* TODO: still need this? */
5791 code = '~'; /* 0x7E */
5792 if (code != 32) /* Space */
5793 emacs_event->modifiers = 0;
5795 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5796 emacs_event->code = code;
5797 EV_TRAILER ((id)nil);
5802 /* <NSTextInput>: inserts display of composing characters */
5803 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
5805 NSString *str = [aString respondsToSelector: @selector (string)] ?
5806 [aString string] : aString;
5808 NSLog (@"setMarkedText '%@' len =%lu range %lu from %lu",
5809 str, (unsigned long)[str length],
5810 (unsigned long)selRange.length,
5811 (unsigned long)selRange.location);
5813 if (workingText != nil)
5814 [self deleteWorkingText];
5815 if ([str length] == 0)
5821 processingCompose = YES;
5822 workingText = [str copy];
5823 ns_working_text = build_string ([workingText UTF8String]);
5825 emacs_event->kind = NS_TEXT_EVENT;
5826 emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
5827 EV_TRAILER ((id)nil);
5831 /* delete display of composing characters [not in <NSTextInput>] */
5832 - (void)deleteWorkingText
5834 if (workingText == nil)
5837 NSLog(@"deleteWorkingText len =%lu\n", (unsigned long)[workingText length]);
5838 [workingText release];
5840 processingCompose = NO;
5845 emacs_event->kind = NS_TEXT_EVENT;
5846 emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
5847 EV_TRAILER ((id)nil);
5851 - (BOOL)hasMarkedText
5853 return workingText != nil;
5857 - (NSRange)markedRange
5859 NSRange rng = workingText != nil
5860 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
5862 NSLog (@"markedRange request");
5870 NSLog (@"unmark (accept) text");
5871 [self deleteWorkingText];
5872 processingCompose = NO;
5876 /* used to position char selection windows, etc. */
5877 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
5881 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
5883 NSLog (@"firstRectForCharRange request");
5885 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
5886 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
5887 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
5888 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
5889 +FRAME_LINE_HEIGHT (emacsframe));
5891 pt = [self convertPoint: pt toView: nil];
5892 pt = [[self window] convertBaseToScreen: pt];
5898 - (NSInteger)conversationIdentifier
5900 return (NSInteger)self;
5904 - (void)doCommandBySelector: (SEL)aSelector
5907 NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
5909 processingCompose = NO;
5910 if (aSelector == @selector (deleteBackward:))
5912 /* happens when user backspaces over an ongoing composition:
5913 throw a 'delete' into the event queue */
5916 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5917 emacs_event->code = 0xFF08;
5918 EV_TRAILER ((id)nil);
5922 - (NSArray *)validAttributesForMarkedText
5924 static NSArray *arr = nil;
5925 if (arr == nil) arr = [NSArray new];
5926 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
5930 - (NSRange)selectedRange
5933 NSLog (@"selectedRange request");
5934 return NSMakeRange (NSNotFound, 0);
5937 #if defined (NS_IMPL_COCOA) || GNUSTEP_GUI_MAJOR_VERSION > 0 || \
5938 GNUSTEP_GUI_MINOR_VERSION > 22
5939 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
5941 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
5945 NSLog (@"characterIndexForPoint request");
5949 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
5951 static NSAttributedString *str = nil;
5952 if (str == nil) str = [NSAttributedString new];
5954 NSLog (@"attributedSubstringFromRange request");
5958 /* End <NSTextInput> impl. */
5959 /*****************************************************************************/
5962 /* This is what happens when the user presses a mouse button. */
5963 - (void)mouseDown: (NSEvent *)theEvent
5965 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
5966 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5968 NSTRACE ("mouseDown");
5970 [self deleteWorkingText];
5975 dpyinfo->last_mouse_frame = emacsframe;
5976 /* appears to be needed to prevent spurious movement events generated on
5978 emacsframe->mouse_moved = 0;
5980 if ([theEvent type] == NSScrollWheel)
5982 CGFloat delta = [theEvent deltaY];
5983 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
5986 delta = [theEvent deltaX];
5989 NSTRACE ("deltaIsZero");
5992 emacs_event->kind = HORIZ_WHEEL_EVENT;
5995 emacs_event->kind = WHEEL_EVENT;
5997 emacs_event->code = 0;
5998 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
5999 ((delta > 0) ? up_modifier : down_modifier);
6003 emacs_event->kind = MOUSE_CLICK_EVENT;
6004 emacs_event->code = EV_BUTTON (theEvent);
6005 emacs_event->modifiers = EV_MODIFIERS (theEvent)
6006 | EV_UDMODIFIERS (theEvent);
6008 XSETINT (emacs_event->x, lrint (p.x));
6009 XSETINT (emacs_event->y, lrint (p.y));
6010 EV_TRAILER (theEvent);
6014 - (void)rightMouseDown: (NSEvent *)theEvent
6016 NSTRACE ("rightMouseDown");
6017 [self mouseDown: theEvent];
6021 - (void)otherMouseDown: (NSEvent *)theEvent
6023 NSTRACE ("otherMouseDown");
6024 [self mouseDown: theEvent];
6028 - (void)mouseUp: (NSEvent *)theEvent
6030 NSTRACE ("mouseUp");
6031 [self mouseDown: theEvent];
6035 - (void)rightMouseUp: (NSEvent *)theEvent
6037 NSTRACE ("rightMouseUp");
6038 [self mouseDown: theEvent];
6042 - (void)otherMouseUp: (NSEvent *)theEvent
6044 NSTRACE ("otherMouseUp");
6045 [self mouseDown: theEvent];
6049 - (void) scrollWheel: (NSEvent *)theEvent
6051 NSTRACE ("scrollWheel");
6052 [self mouseDown: theEvent];
6056 /* Tell emacs the mouse has moved. */
6057 - (void)mouseMoved: (NSEvent *)e
6059 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
6060 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6064 // NSTRACE ("mouseMoved");
6066 dpyinfo->last_mouse_movement_time = EV_TIMESTAMP (e);
6067 pt = [self convertPoint: [e locationInWindow] fromView: nil];
6068 dpyinfo->last_mouse_motion_x = pt.x;
6069 dpyinfo->last_mouse_motion_y = pt.y;
6071 /* update any mouse face */
6072 if (hlinfo->mouse_face_hidden)
6074 hlinfo->mouse_face_hidden = 0;
6075 clear_mouse_face (hlinfo);
6078 /* tooltip handling */
6079 previous_help_echo_string = help_echo_string;
6080 help_echo_string = Qnil;
6082 if (!NILP (Vmouse_autoselect_window))
6084 NSTRACE ("mouse_autoselect_window");
6085 static Lisp_Object last_mouse_window;
6087 = window_from_coordinates (emacsframe, pt.x, pt.y, 0, 0);
6089 if (WINDOWP (window)
6090 && !EQ (window, last_mouse_window)
6091 && !EQ (window, selected_window)
6092 && (focus_follows_mouse
6093 || (EQ (XWINDOW (window)->frame,
6094 XWINDOW (selected_window)->frame))))
6096 NSTRACE ("in_window");
6097 emacs_event->kind = SELECT_WINDOW_EVENT;
6098 emacs_event->frame_or_window = window;
6101 /* Remember the last window where we saw the mouse. */
6102 last_mouse_window = window;
6105 if (!note_mouse_movement (emacsframe, pt.x, pt.y))
6106 help_echo_string = previous_help_echo_string;
6108 XSETFRAME (frame, emacsframe);
6109 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
6111 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
6112 (note_mouse_highlight), which is called through the
6113 note_mouse_movement () call above */
6114 any_help_event_p = YES;
6115 gen_help_event (help_echo_string, frame, help_echo_window,
6116 help_echo_object, help_echo_pos);
6119 if (emacsframe->mouse_moved && send_appdefined)
6120 ns_send_appdefined (-1);
6124 - (void)mouseDragged: (NSEvent *)e
6126 NSTRACE ("mouseDragged");
6127 [self mouseMoved: e];
6131 - (void)rightMouseDragged: (NSEvent *)e
6133 NSTRACE ("rightMouseDragged");
6134 [self mouseMoved: e];
6138 - (void)otherMouseDragged: (NSEvent *)e
6140 NSTRACE ("otherMouseDragged");
6141 [self mouseMoved: e];
6145 - (BOOL)windowShouldClose: (id)sender
6147 NSEvent *e =[[self window] currentEvent];
6149 NSTRACE ("windowShouldClose");
6150 windowClosing = YES;
6153 emacs_event->kind = DELETE_WINDOW_EVENT;
6154 emacs_event->modifiers = 0;
6155 emacs_event->code = 0;
6157 /* Don't close this window, let this be done from lisp code. */
6161 - (void) updateFrameSize: (BOOL) delay;
6163 NSWindow *window = [self window];
6164 NSRect wr = [window frame];
6166 int oldc = cols, oldr = rows;
6167 int oldw = FRAME_PIXEL_WIDTH (emacsframe);
6168 int oldh = FRAME_PIXEL_HEIGHT (emacsframe);
6171 NSTRACE ("updateFrameSize");
6172 NSTRACE_SIZE ("Original size", NSMakeSize (oldw, oldh));
6173 NSTRACE_RECT ("Original frame", wr);
6175 if (! [self isFullscreen])
6177 #ifdef NS_IMPL_GNUSTEP
6178 // GNUstep does not always update the tool bar height. Force it.
6179 if (toolbar && [toolbar isVisible])
6180 update_frame_tool_bar (emacsframe);
6183 extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6184 + FRAME_TOOLBAR_HEIGHT (emacsframe);
6187 if (wait_for_tool_bar)
6189 if (FRAME_TOOLBAR_HEIGHT (emacsframe) == 0)
6191 wait_for_tool_bar = NO;
6194 neww = (int)wr.size.width - emacsframe->border_width;
6195 newh = (int)wr.size.height - extra;
6197 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, neww);
6198 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, newh);
6200 if (cols < MINWIDTH)
6203 if (rows < MINHEIGHT)
6206 if (oldr != rows || oldc != cols || neww != oldw || newh != oldh)
6208 NSView *view = FRAME_NS_VIEW (emacsframe);
6209 NSWindow *win = [view window];
6211 change_frame_size (emacsframe,
6212 FRAME_PIXEL_TO_TEXT_WIDTH (emacsframe, neww),
6213 FRAME_PIXEL_TO_TEXT_HEIGHT (emacsframe, newh),
6215 SET_FRAME_GARBAGED (emacsframe);
6216 cancel_mouse_face (emacsframe);
6218 wr = NSMakeRect (0, 0, neww, newh);
6219 NSTRACE_RECT ("setFrame", wr);
6220 [view setFrame: wr];
6221 [self windowDidMove:nil]; // Update top/left.
6225 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
6226 /* normalize frame to gridded text size */
6230 NSTRACE ("windowWillResize: toSize: " NSTRACE_FMT_SIZE,
6231 NSTRACE_ARG_SIZE (frameSize));
6232 NSTRACE_RECT ("[sender frame]", [sender frame]);
6233 NSTRACE_FSTYPE ("fs_state", fs_state);
6235 if (fs_state == FULLSCREEN_MAXIMIZED
6236 && (maximized_width != (int)frameSize.width
6237 || maximized_height != (int)frameSize.height))
6238 [self setFSValue: FULLSCREEN_NONE];
6239 else if (fs_state == FULLSCREEN_WIDTH
6240 && maximized_width != (int)frameSize.width)
6241 [self setFSValue: FULLSCREEN_NONE];
6242 else if (fs_state == FULLSCREEN_HEIGHT
6243 && maximized_height != (int)frameSize.height)
6244 [self setFSValue: FULLSCREEN_NONE];
6246 if (fs_state == FULLSCREEN_NONE)
6247 maximized_width = maximized_height = -1;
6249 if (! [self isFullscreen])
6251 extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6252 + FRAME_TOOLBAR_HEIGHT (emacsframe);
6255 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, frameSize.width);
6256 if (cols < MINWIDTH)
6259 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe,
6260 frameSize.height - extra);
6261 if (rows < MINHEIGHT)
6263 #ifdef NS_IMPL_COCOA
6265 /* this sets window title to have size in it; the wm does this under GS */
6266 NSRect r = [[self window] frame];
6267 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
6275 else if (fs_state == FULLSCREEN_NONE && ! maximizing_resize)
6278 NSWindow *window = [self window];
6281 char *t = strdup ([[[self window] title] UTF8String]);
6282 char *pos = strstr (t, " — ");
6287 size_title = xmalloc (strlen (old_title) + 40);
6288 esprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
6289 [window setTitle: [NSString stringWithUTF8String: size_title]];
6294 #endif /* NS_IMPL_COCOA */
6296 NSTRACE_MSG ("cols: %d rows: %d", cols, rows);
6298 /* Restrict the new size to the text gird.
6300 Don't restict the width if the user only adjusted the height, and
6301 vice versa. (Without this, the frame would shrink, and move
6302 slightly, if the window was resized by dragging one of its
6304 if (!frame_resize_pixelwise)
6306 NSRect r = [[self window] frame];
6308 if (r.size.width != frameSize.width)
6311 FRAME_TEXT_COLS_TO_PIXEL_WIDTH (emacsframe, cols);
6314 if (r.size.height != frameSize.height)
6317 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows) + extra;
6321 NSTRACE_RETURN_SIZE (frameSize);
6327 - (void)windowDidResize: (NSNotification *)notification
6329 NSTRACE ("windowDidResize");
6331 if (! [self fsIsNative])
6333 NSWindow *theWindow = [notification object];
6334 /* We can get notification on the non-FS window when in
6336 if ([self window] != theWindow) return;
6339 NSTRACE_RECT ("frame", [[notification object] frame]);
6341 #ifdef NS_IMPL_GNUSTEP
6342 NSWindow *theWindow = [notification object];
6344 /* In GNUstep, at least currently, it's possible to get a didResize
6345 without getting a willResize.. therefore we need to act as if we got
6346 the willResize now */
6347 NSSize sz = [theWindow frame].size;
6348 sz = [self windowWillResize: theWindow toSize: sz];
6349 #endif /* NS_IMPL_GNUSTEP */
6351 if (cols > 0 && rows > 0)
6353 [self updateFrameSize: YES];
6356 ns_send_appdefined (-1);
6359 #ifdef NS_IMPL_COCOA
6360 - (void)viewDidEndLiveResize
6362 [super viewDidEndLiveResize];
6365 [[self window] setTitle: [NSString stringWithUTF8String: old_title]];
6369 maximizing_resize = NO;
6371 #endif /* NS_IMPL_COCOA */
6374 - (void)windowDidBecomeKey: (NSNotification *)notification
6375 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6377 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6378 struct frame *old_focus = dpyinfo->x_focus_frame;
6380 NSTRACE ("windowDidBecomeKey");
6382 if (emacsframe != old_focus)
6383 dpyinfo->x_focus_frame = emacsframe;
6385 ns_frame_rehighlight (emacsframe);
6389 emacs_event->kind = FOCUS_IN_EVENT;
6390 EV_TRAILER ((id)nil);
6395 - (void)windowDidResignKey: (NSNotification *)notification
6396 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6398 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6399 BOOL is_focus_frame = dpyinfo->x_focus_frame == emacsframe;
6400 NSTRACE ("windowDidResignKey");
6403 dpyinfo->x_focus_frame = 0;
6405 emacsframe->mouse_moved = 0;
6406 ns_frame_rehighlight (emacsframe);
6408 /* FIXME: for some reason needed on second and subsequent clicks away
6409 from sole-frame Emacs to get hollow box to show */
6410 if (!windowClosing && [[self window] isVisible] == YES)
6412 x_update_cursor (emacsframe, 1);
6413 x_set_frame_alpha (emacsframe);
6416 if (any_help_event_p)
6419 XSETFRAME (frame, emacsframe);
6420 help_echo_string = Qnil;
6421 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
6424 if (emacs_event && is_focus_frame)
6426 [self deleteWorkingText];
6427 emacs_event->kind = FOCUS_OUT_EVENT;
6428 EV_TRAILER ((id)nil);
6433 - (void)windowWillMiniaturize: sender
6435 NSTRACE ("windowWillMiniaturize");
6451 - initFrameFromEmacs: (struct frame *)f
6459 NSTRACE ("initFrameFromEmacs");
6462 processingCompose = NO;
6463 scrollbarsNeedingUpdate = 0;
6464 fs_state = FULLSCREEN_NONE;
6465 fs_before_fs = next_maximized = -1;
6466 #ifdef HAVE_NATIVE_FS
6467 fs_is_native = ns_use_native_fullscreen;
6471 maximized_width = maximized_height = -1;
6474 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
6476 ns_userRect = NSMakeRect (0, 0, 0, 0);
6477 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
6478 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
6479 [self initWithFrame: r];
6480 [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
6482 FRAME_NS_VIEW (f) = self;
6484 #ifdef NS_IMPL_COCOA
6486 maximizing_resize = NO;
6489 win = [[EmacsWindow alloc]
6490 initWithContentRect: r
6491 styleMask: (NSResizableWindowMask |
6492 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6493 NSTitledWindowMask |
6495 NSMiniaturizableWindowMask |
6496 NSClosableWindowMask)
6497 backing: NSBackingStoreBuffered
6500 #ifdef HAVE_NATIVE_FS
6501 [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
6505 bwidth = f->border_width = wr.size.width - r.size.width;
6506 tibar_height = FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
6508 [win setAcceptsMouseMovedEvents: YES];
6509 [win setDelegate: self];
6510 #if !defined (NS_IMPL_COCOA) || \
6511 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6512 [win useOptimizedDrawing: YES];
6515 [[win contentView] addSubview: self];
6518 [self registerForDraggedTypes: ns_drag_types];
6521 name = [NSString stringWithUTF8String:
6522 NILP (tem) ? "Emacs" : SSDATA (tem)];
6523 [win setTitle: name];
6525 /* toolbar support */
6526 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
6527 [NSString stringWithFormat: @"Emacs Frame %d",
6529 [win setToolbar: toolbar];
6530 [toolbar setVisible: NO];
6532 /* Don't set frame garbaged until tool bar is up to date?
6533 This avoids an extra clear and redraw (flicker) at frame creation. */
6534 if (FRAME_EXTERNAL_TOOL_BAR (f)) wait_for_tool_bar = YES;
6535 else wait_for_tool_bar = NO;
6538 #ifdef NS_IMPL_COCOA
6540 NSButton *toggleButton;
6541 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
6542 [toggleButton setTarget: self];
6543 [toggleButton setAction: @selector (toggleToolbar: )];
6546 FRAME_TOOLBAR_HEIGHT (f) = 0;
6550 [win setMiniwindowTitle:
6551 [NSString stringWithUTF8String: SSDATA (tem)]];
6554 NSScreen *screen = [win screen];
6558 NSPoint pt = NSMakePoint
6559 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
6560 IN_BOUND (-SCREENMAX,
6561 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX));
6563 NSTRACE_POINT ("setFrameTopLeftPoint", pt);
6565 [win setFrameTopLeftPoint: pt];
6567 NSTRACE_RECT ("new frame", [win frame]);
6571 [win makeFirstResponder: self];
6573 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6574 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
6575 [win setBackgroundColor: col];
6576 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6577 [win setOpaque: NO];
6579 #if !defined (NS_IMPL_COCOA) || \
6580 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6581 [self allocateGState];
6583 [NSApp registerServicesMenuSendTypes: ns_send_types
6591 - (void)windowDidMove: sender
6593 NSWindow *win = [self window];
6594 NSRect r = [win frame];
6595 NSArray *screens = [NSScreen screens];
6596 NSScreen *screen = [screens objectAtIndex: 0];
6598 NSTRACE ("windowDidMove");
6600 if (!emacsframe->output_data.ns)
6604 emacsframe->left_pos = r.origin.x;
6605 emacsframe->top_pos =
6606 [screen frame].size.height - (r.origin.y + r.size.height);
6611 /* Called AFTER method below, but before our windowWillResize call there leads
6612 to windowDidResize -> x_set_window_size. Update emacs' notion of frame
6613 location so set_window_size moves the frame. */
6614 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
6616 NSTRACE (("[windowShouldZoom:win toFrame:" NSTRACE_FMT_RECT "]"
6617 NSTRACE_FMT_RETURN "YES"),
6618 NSTRACE_ARG_RECT (newFrame));
6620 emacsframe->output_data.ns->zooming = 1;
6625 /* Override to do something slightly nonstandard, but nice. First click on
6626 zoom button will zoom vertically. Second will zoom completely. Third
6627 returns to original. */
6628 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
6629 defaultFrame:(NSRect)defaultFrame
6631 // TODO: Rename to "currentFrame" and assign "result" properly in
6633 NSRect result = [sender frame];
6635 NSTRACE (("[windowWillUseStandardFrame: defaultFrame:"
6636 NSTRACE_FMT_RECT "]"),
6637 NSTRACE_ARG_RECT (defaultFrame));
6638 NSTRACE_FSTYPE ("fs_state", fs_state);
6639 NSTRACE_FSTYPE ("fs_before_fs", fs_before_fs);
6640 NSTRACE_FSTYPE ("next_maximized", next_maximized);
6641 NSTRACE_RECT ("ns_userRect", ns_userRect);
6642 NSTRACE_RECT ("[sender frame]", [sender frame]);
6644 if (fs_before_fs != -1) /* Entering fullscreen */
6646 NSTRACE_MSG ("Entering fullscreen");
6647 result = defaultFrame;
6651 // Save the window size and position (frame) before the resize.
6652 if (fs_state != FULLSCREEN_MAXIMIZED
6653 && fs_state != FULLSCREEN_WIDTH)
6655 ns_userRect.size.width = result.size.width;
6656 ns_userRect.origin.x = result.origin.x;
6659 if (fs_state != FULLSCREEN_MAXIMIZED
6660 && fs_state != FULLSCREEN_HEIGHT)
6662 ns_userRect.size.height = result.size.height;
6663 ns_userRect.origin.y = result.origin.y;
6666 NSTRACE_RECT ("ns_userRect (2)", ns_userRect);
6668 if (next_maximized == FULLSCREEN_HEIGHT
6669 || (next_maximized == -1
6670 && abs ((int)(defaultFrame.size.height - result.size.height))
6671 > FRAME_LINE_HEIGHT (emacsframe)))
6674 NSTRACE_MSG ("FULLSCREEN_HEIGHT");
6675 maximized_height = result.size.height = defaultFrame.size.height;
6676 maximized_width = -1;
6677 result.origin.y = defaultFrame.origin.y;
6678 if (ns_userRect.size.height != 0)
6680 result.origin.x = ns_userRect.origin.x;
6681 result.size.width = ns_userRect.size.width;
6683 [self setFSValue: FULLSCREEN_HEIGHT];
6684 #ifdef NS_IMPL_COCOA
6685 maximizing_resize = YES;
6688 else if (next_maximized == FULLSCREEN_WIDTH)
6690 NSTRACE_MSG ("FULLSCREEN_WIDTH");
6691 maximized_width = result.size.width = defaultFrame.size.width;
6692 maximized_height = -1;
6693 result.origin.x = defaultFrame.origin.x;
6694 if (ns_userRect.size.width != 0)
6696 result.origin.y = ns_userRect.origin.y;
6697 result.size.height = ns_userRect.size.height;
6699 [self setFSValue: FULLSCREEN_WIDTH];
6701 else if (next_maximized == FULLSCREEN_MAXIMIZED
6702 || (next_maximized == -1
6703 && abs ((int)(defaultFrame.size.width - result.size.width))
6704 > FRAME_COLUMN_WIDTH (emacsframe)))
6706 NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
6708 result = defaultFrame; /* second click */
6709 maximized_width = result.size.width;
6710 maximized_height = result.size.height;
6711 [self setFSValue: FULLSCREEN_MAXIMIZED];
6712 #ifdef NS_IMPL_COCOA
6713 maximizing_resize = YES;
6719 NSTRACE_MSG ("Restore");
6720 result = ns_userRect.size.height ? ns_userRect : result;
6721 NSTRACE_RECT ("restore (2)", result);
6722 ns_userRect = NSMakeRect (0, 0, 0, 0);
6723 #ifdef NS_IMPL_COCOA
6724 maximizing_resize = fs_state != FULLSCREEN_NONE;
6726 [self setFSValue: FULLSCREEN_NONE];
6727 maximized_width = maximized_height = -1;
6731 if (fs_before_fs == -1) next_maximized = -1;
6733 NSTRACE_RECT ("Final ns_userRect", ns_userRect);
6734 NSTRACE_MSG ("Final maximized_width: %d", maximized_width);
6735 NSTRACE_MSG ("Final maximized_height: %d", maximized_height);
6736 NSTRACE_FSTYPE ("Final next_maximized", next_maximized);
6738 [self windowWillResize: sender toSize: result.size];
6740 NSTRACE_RETURN_RECT (result);
6746 - (void)windowDidDeminiaturize: sender
6748 NSTRACE ("windowDidDeminiaturize");
6749 if (!emacsframe->output_data.ns)
6752 SET_FRAME_ICONIFIED (emacsframe, 0);
6753 SET_FRAME_VISIBLE (emacsframe, 1);
6754 windows_or_buffers_changed = 63;
6758 emacs_event->kind = DEICONIFY_EVENT;
6759 EV_TRAILER ((id)nil);
6764 - (void)windowDidExpose: sender
6766 NSTRACE ("windowDidExpose");
6767 if (!emacsframe->output_data.ns)
6770 SET_FRAME_VISIBLE (emacsframe, 1);
6771 SET_FRAME_GARBAGED (emacsframe);
6773 if (send_appdefined)
6774 ns_send_appdefined (-1);
6778 - (void)windowDidMiniaturize: sender
6780 NSTRACE ("windowDidMiniaturize");
6781 if (!emacsframe->output_data.ns)
6784 SET_FRAME_ICONIFIED (emacsframe, 1);
6785 SET_FRAME_VISIBLE (emacsframe, 0);
6789 emacs_event->kind = ICONIFY_EVENT;
6790 EV_TRAILER ((id)nil);
6794 #ifdef HAVE_NATIVE_FS
6795 - (NSApplicationPresentationOptions)window:(NSWindow *)window
6796 willUseFullScreenPresentationOptions:
6797 (NSApplicationPresentationOptions)proposedOptions
6799 return proposedOptions|NSApplicationPresentationAutoHideToolbar;
6803 - (void)windowWillEnterFullScreen:(NSNotification *)notification
6805 NSTRACE ("windowWillEnterFullScreen");
6806 fs_before_fs = fs_state;
6809 - (void)windowDidEnterFullScreen:(NSNotification *)notification
6811 NSTRACE ("windowDidEnterFullScreen");
6812 [self setFSValue: FULLSCREEN_BOTH];
6813 if (! [self fsIsNative])
6815 [self windowDidBecomeKey:notification];
6816 [nonfs_window orderOut:self];
6820 BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (emacsframe) ? YES : NO;
6821 #ifdef NS_IMPL_COCOA
6822 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6823 unsigned val = (unsigned)[NSApp presentationOptions];
6825 // OSX 10.7 bug fix, the menu won't appear without this.
6826 // val is non-zero on other OSX versions.
6829 NSApplicationPresentationOptions options
6830 = NSApplicationPresentationAutoHideDock
6831 | NSApplicationPresentationAutoHideMenuBar
6832 | NSApplicationPresentationFullScreen
6833 | NSApplicationPresentationAutoHideToolbar;
6835 [NSApp setPresentationOptions: options];
6839 [toolbar setVisible:tbar_visible];
6843 - (void)windowWillExitFullScreen:(NSNotification *)notification
6845 NSTRACE ("windowWillExitFullScreen");
6847 if (next_maximized != -1)
6848 fs_before_fs = next_maximized;
6851 - (void)windowDidExitFullScreen:(NSNotification *)notification
6853 NSTRACE ("windowDidExitFullScreen");
6855 [self setFSValue: fs_before_fs];
6857 #ifdef HAVE_NATIVE_FS
6858 [self updateCollectionBehavior];
6860 if (FRAME_EXTERNAL_TOOL_BAR (emacsframe))
6862 [toolbar setVisible:YES];
6863 update_frame_tool_bar (emacsframe);
6864 [self updateFrameSize:YES];
6865 [[self window] display];
6868 [toolbar setVisible:NO];
6870 if (next_maximized != -1)
6871 [[self window] performZoom:self];
6876 return fs_is_native;
6879 - (BOOL)isFullscreen
6881 if (! fs_is_native) return nonfs_window != nil;
6882 #ifdef HAVE_NATIVE_FS
6883 return ([[self window] styleMask] & NSFullScreenWindowMask) != 0;
6889 #ifdef HAVE_NATIVE_FS
6890 - (void)updateCollectionBehavior
6892 if (! [self isFullscreen])
6894 NSWindow *win = [self window];
6895 NSWindowCollectionBehavior b = [win collectionBehavior];
6896 if (ns_use_native_fullscreen)
6897 b |= NSWindowCollectionBehaviorFullScreenPrimary;
6899 b &= ~NSWindowCollectionBehaviorFullScreenPrimary;
6901 [win setCollectionBehavior: b];
6902 fs_is_native = ns_use_native_fullscreen;
6907 - (void)toggleFullScreen: (id)sender
6915 NSTRACE ("toggleFullScreen");
6919 #ifdef HAVE_NATIVE_FS
6920 [[self window] toggleFullScreen:sender];
6926 onFirstScreen = [[w screen] isEqual:[[NSScreen screens] objectAtIndex:0]];
6929 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6930 (FRAME_DEFAULT_FACE (f)),
6933 if (fs_state != FULLSCREEN_BOTH)
6935 NSScreen *screen = [w screen];
6937 #if defined (NS_IMPL_COCOA) && \
6938 MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
6939 /* Hide ghost menu bar on secondary monitor? */
6940 if (! onFirstScreen)
6941 onFirstScreen = [NSScreen screensHaveSeparateSpaces];
6943 /* Hide dock and menubar if we are on the primary screen. */
6946 #ifdef NS_IMPL_COCOA
6947 NSApplicationPresentationOptions options
6948 = NSApplicationPresentationAutoHideDock
6949 | NSApplicationPresentationAutoHideMenuBar;
6951 [NSApp setPresentationOptions: options];
6953 [NSMenu setMenuBarVisible:NO];
6957 fw = [[EmacsFSWindow alloc]
6958 initWithContentRect:[w contentRectForFrameRect:wr]
6959 styleMask:NSBorderlessWindowMask
6960 backing:NSBackingStoreBuffered
6964 [fw setContentView:[w contentView]];
6965 [fw setTitle:[w title]];
6966 [fw setDelegate:self];
6967 [fw setAcceptsMouseMovedEvents: YES];
6968 #if !defined (NS_IMPL_COCOA) || \
6969 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6970 [fw useOptimizedDrawing: YES];
6972 [fw setBackgroundColor: col];
6973 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6976 f->border_width = 0;
6977 FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
6978 tobar_height = FRAME_TOOLBAR_HEIGHT (f);
6979 FRAME_TOOLBAR_HEIGHT (f) = 0;
6983 [self windowWillEnterFullScreen:nil];
6984 [fw makeKeyAndOrderFront:NSApp];
6985 [fw makeFirstResponder:self];
6987 r = [fw frameRectForContentRect:[screen frame]];
6988 [fw setFrame: r display:YES animate:ns_use_fullscreen_animation];
6989 [self windowDidEnterFullScreen:nil];
7000 #ifdef NS_IMPL_COCOA
7001 [NSApp setPresentationOptions: NSApplicationPresentationDefault];
7003 [NSMenu setMenuBarVisible:YES];
7007 [w setContentView:[fw contentView]];
7008 [w setBackgroundColor: col];
7009 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
7012 f->border_width = bwidth;
7013 FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
7014 if (FRAME_EXTERNAL_TOOL_BAR (f))
7015 FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
7017 [self windowWillExitFullScreen:nil];
7018 [fw setFrame: [w frame] display:YES animate:ns_use_fullscreen_animation];
7020 [w makeKeyAndOrderFront:NSApp];
7021 [self windowDidExitFullScreen:nil];
7022 [self updateFrameSize:YES];
7028 NSTRACE ("handleFS");
7030 if (fs_state != emacsframe->want_fullscreen)
7032 if (fs_state == FULLSCREEN_BOTH)
7034 NSTRACE_MSG ("fs_state == FULLSCREEN_BOTH");
7035 [self toggleFullScreen:self];
7038 switch (emacsframe->want_fullscreen)
7040 case FULLSCREEN_BOTH:
7041 NSTRACE_MSG ("FULLSCREEN_BOTH");
7042 [self toggleFullScreen:self];
7044 case FULLSCREEN_WIDTH:
7045 NSTRACE_MSG ("FULLSCREEN_WIDTH");
7046 next_maximized = FULLSCREEN_WIDTH;
7047 if (fs_state != FULLSCREEN_BOTH)
7048 [[self window] performZoom:self];
7050 case FULLSCREEN_HEIGHT:
7051 NSTRACE_MSG ("FULLSCREEN_HEIGHT");
7052 next_maximized = FULLSCREEN_HEIGHT;
7053 if (fs_state != FULLSCREEN_BOTH)
7054 [[self window] performZoom:self];
7056 case FULLSCREEN_MAXIMIZED:
7057 NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
7058 next_maximized = FULLSCREEN_MAXIMIZED;
7059 if (fs_state != FULLSCREEN_BOTH)
7060 [[self window] performZoom:self];
7062 case FULLSCREEN_NONE:
7063 NSTRACE_MSG ("FULLSCREEN_NONE");
7064 if (fs_state != FULLSCREEN_BOTH)
7066 next_maximized = FULLSCREEN_NONE;
7067 [[self window] performZoom:self];
7072 emacsframe->want_fullscreen = FULLSCREEN_NONE;
7077 - (void) setFSValue: (int)value
7079 NSTRACE ("setFSValue");
7080 NSTRACE_FSTYPE ("value", value);
7082 Lisp_Object lval = Qnil;
7085 case FULLSCREEN_BOTH:
7088 case FULLSCREEN_WIDTH:
7091 case FULLSCREEN_HEIGHT:
7094 case FULLSCREEN_MAXIMIZED:
7098 store_frame_param (emacsframe, Qfullscreen, lval);
7102 - (void)mouseEntered: (NSEvent *)theEvent
7104 NSTRACE ("mouseEntered");
7106 FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7107 = EV_TIMESTAMP (theEvent);
7111 - (void)mouseExited: (NSEvent *)theEvent
7113 Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
7115 NSTRACE ("mouseExited");
7120 FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7121 = EV_TIMESTAMP (theEvent);
7123 if (emacsframe == hlinfo->mouse_face_mouse_frame)
7125 clear_mouse_face (hlinfo);
7126 hlinfo->mouse_face_mouse_frame = 0;
7133 NSTRACE ("menuDown");
7134 if (context_menu_value == -1)
7135 context_menu_value = [sender tag];
7138 NSInteger tag = [sender tag];
7139 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
7140 emacsframe->menu_bar_vector,
7144 ns_send_appdefined (-1);
7149 - (EmacsToolbar *)toolbar
7155 /* this gets called on toolbar button click */
7156 - toolbarClicked: (id)item
7159 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
7161 NSTRACE ("toolbarClicked");
7166 /* send first event (for some reason two needed) */
7167 theEvent = [[self window] currentEvent];
7168 emacs_event->kind = TOOL_BAR_EVENT;
7169 XSETFRAME (emacs_event->arg, emacsframe);
7170 EV_TRAILER (theEvent);
7172 emacs_event->kind = TOOL_BAR_EVENT;
7173 /* XSETINT (emacs_event->code, 0); */
7174 emacs_event->arg = AREF (emacsframe->tool_bar_items,
7175 idx + TOOL_BAR_ITEM_KEY);
7176 emacs_event->modifiers = EV_MODIFIERS (theEvent);
7177 EV_TRAILER (theEvent);
7182 - toggleToolbar: (id)sender
7187 emacs_event->kind = NS_NONKEY_EVENT;
7188 emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
7189 EV_TRAILER ((id)nil);
7194 - (void)drawRect: (NSRect)rect
7196 int x = NSMinX (rect), y = NSMinY (rect);
7197 int width = NSWidth (rect), height = NSHeight (rect);
7199 NSTRACE ("drawRect");
7200 NSTRACE_RECT ("input", rect);
7202 if (!emacsframe || !emacsframe->output_data.ns)
7205 ns_clear_frame_area (emacsframe, x, y, width, height);
7207 expose_frame (emacsframe, x, y, width, height);
7211 drawRect: may be called (at least in OS X 10.5) for invisible
7212 views as well for some reason. Thus, do not infer visibility
7215 emacsframe->async_visible = 1;
7216 emacsframe->async_iconified = 0;
7221 /* NSDraggingDestination protocol methods. Actually this is not really a
7222 protocol, but a category of Object. O well... */
7224 -(NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
7226 NSTRACE ("draggingEntered");
7227 return NSDragOperationGeneric;
7231 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
7237 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
7242 NSEvent *theEvent = [[self window] currentEvent];
7244 NSDragOperation op = [sender draggingSourceOperationMask];
7247 NSTRACE ("performDragOperation");
7252 position = [self convertPoint: [sender draggingLocation] fromView: nil];
7253 x = lrint (position.x); y = lrint (position.y);
7255 pb = [sender draggingPasteboard];
7256 type = [pb availableTypeFromArray: ns_drag_types];
7258 if (! (op & (NSDragOperationMove|NSDragOperationDelete)) &&
7259 // URL drags contain all operations (0xf), don't allow all to be set.
7262 if (op & NSDragOperationLink)
7263 modifiers |= NSControlKeyMask;
7264 if (op & NSDragOperationCopy)
7265 modifiers |= NSAlternateKeyMask;
7266 if (op & NSDragOperationGeneric)
7267 modifiers |= NSCommandKeyMask;
7270 modifiers = EV_MODIFIERS2 (modifiers);
7275 else if ([type isEqualToString: NSFilenamesPboardType])
7278 NSEnumerator *fenum;
7281 if (!(files = [pb propertyListForType: type]))
7284 fenum = [files objectEnumerator];
7285 while ( (file = [fenum nextObject]) )
7287 emacs_event->kind = DRAG_N_DROP_EVENT;
7288 XSETINT (emacs_event->x, x);
7289 XSETINT (emacs_event->y, y);
7290 ns_input_file = append2 (ns_input_file,
7291 build_string ([file UTF8String]));
7292 emacs_event->modifiers = modifiers;
7293 emacs_event->arg = list2 (Qfile, build_string ([file UTF8String]));
7294 EV_TRAILER (theEvent);
7298 else if ([type isEqualToString: NSURLPboardType])
7300 NSURL *url = [NSURL URLFromPasteboard: pb];
7301 if (url == nil) return NO;
7303 emacs_event->kind = DRAG_N_DROP_EVENT;
7304 XSETINT (emacs_event->x, x);
7305 XSETINT (emacs_event->y, y);
7306 emacs_event->modifiers = modifiers;
7307 emacs_event->arg = list2 (Qurl,
7308 build_string ([[url absoluteString]
7310 EV_TRAILER (theEvent);
7312 if ([url isFileURL] != NO)
7314 NSString *file = [url path];
7315 ns_input_file = append2 (ns_input_file,
7316 build_string ([file UTF8String]));
7320 else if ([type isEqualToString: NSStringPboardType]
7321 || [type isEqualToString: NSTabularTextPboardType])
7325 if (! (data = [pb stringForType: type]))
7328 emacs_event->kind = DRAG_N_DROP_EVENT;
7329 XSETINT (emacs_event->x, x);
7330 XSETINT (emacs_event->y, y);
7331 emacs_event->modifiers = modifiers;
7332 emacs_event->arg = list2 (Qnil, build_string ([data UTF8String]));
7333 EV_TRAILER (theEvent);
7338 fprintf (stderr, "Invalid data type in dragging pasteboard");
7344 - (id) validRequestorForSendType: (NSString *)typeSent
7345 returnType: (NSString *)typeReturned
7347 NSTRACE ("validRequestorForSendType");
7348 if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
7349 && typeReturned == nil)
7351 if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
7355 return [super validRequestorForSendType: typeSent
7356 returnType: typeReturned];
7360 /* The next two methods are part of NSServicesRequests informal protocol,
7361 supposedly called when a services menu item is chosen from this app.
7362 But this should not happen because we override the services menu with our
7363 own entries which call ns-perform-service.
7364 Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
7365 So let's at least stub them out until further investigation can be done. */
7367 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
7369 /* we could call ns_string_from_pasteboard(pboard) here but then it should
7370 be written into the buffer in place of the existing selection..
7371 ordinary service calls go through functions defined in ns-win.el */
7375 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
7377 NSArray *typesDeclared;
7380 /* We only support NSStringPboardType */
7381 if ([types containsObject:NSStringPboardType] == NO) {
7385 val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7386 if (CONSP (val) && SYMBOLP (XCAR (val)))
7389 if (CONSP (val) && NILP (XCDR (val)))
7392 if (! STRINGP (val))
7395 typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
7396 [pb declareTypes:typesDeclared owner:nil];
7397 ns_string_to_pasteboard (pb, val);
7402 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
7403 (gives a miniaturized version of the window); currently we use the latter for
7404 frames whose active buffer doesn't correspond to any file
7405 (e.g., '*scratch*') */
7406 - setMiniwindowImage: (BOOL) setMini
7408 id image = [[self window] miniwindowImage];
7409 NSTRACE ("setMiniwindowImage");
7411 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
7412 about "AppleDockIconEnabled" notwithstanding, however the set message
7413 below has its effect nonetheless. */
7414 if (image != emacsframe->output_data.ns->miniimage)
7416 if (image && [image isKindOfClass: [EmacsImage class]])
7418 [[self window] setMiniwindowImage:
7419 setMini ? emacsframe->output_data.ns->miniimage : nil];
7426 - (void) setRows: (int) r andColumns: (int) c
7432 - (int) fullscreenState
7437 @end /* EmacsView */
7441 /* ==========================================================================
7443 EmacsWindow implementation
7445 ========================================================================== */
7447 @implementation EmacsWindow
7449 #ifdef NS_IMPL_COCOA
7450 - (id)accessibilityAttributeValue:(NSString *)attribute
7452 Lisp_Object str = Qnil;
7453 struct frame *f = SELECTED_FRAME ();
7454 struct buffer *curbuf = XBUFFER (XWINDOW (f->selected_window)->contents);
7456 if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
7457 return NSAccessibilityTextFieldRole;
7459 if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]
7460 && curbuf && ! NILP (BVAR (curbuf, mark_active)))
7462 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7464 else if (curbuf && [attribute isEqualToString:NSAccessibilityValueAttribute])
7466 if (! NILP (BVAR (curbuf, mark_active)))
7467 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7471 ptrdiff_t start_byte = BUF_BEGV_BYTE (curbuf);
7472 ptrdiff_t byte_range = BUF_ZV_BYTE (curbuf) - start_byte;
7473 ptrdiff_t range = BUF_ZV (curbuf) - BUF_BEGV (curbuf);
7475 if (! NILP (BVAR (curbuf, enable_multibyte_characters)))
7476 str = make_uninit_multibyte_string (range, byte_range);
7478 str = make_uninit_string (range);
7479 /* To check: This returns emacs-utf-8, which is a superset of utf-8.
7480 Is this a problem? */
7481 memcpy (SDATA (str), BYTE_POS_ADDR (start_byte), byte_range);
7488 if (CONSP (str) && SYMBOLP (XCAR (str)))
7491 if (CONSP (str) && NILP (XCDR (str)))
7496 const char *utfStr = SSDATA (str);
7497 NSString *nsStr = [NSString stringWithUTF8String: utfStr];
7502 return [super accessibilityAttributeValue:attribute];
7504 #endif /* NS_IMPL_COCOA */
7506 /* Constrain size and placement of a frame.
7508 By returning the original "frameRect", the frame is not
7509 contrained. This can lead to unwanted situations where, for
7510 example, the menu bar covers the frame.
7512 The default implementation (accessed using "super") constrains the
7513 frame to the visible area of SCREEN, minus the menu bar (if
7514 present) and the Dock. Note that default implementation also calls
7515 windowWillResize, with the frame it thinks should have. (This can
7516 make the frame exit maximized mode.)
7518 Note that this should work in situations where multiple monitors
7519 are present. Common configurations are side-by-side monitors and a
7520 monitor on top of another (e.g. when a laptop is placed under a
7522 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
7524 NSTRACE ("constrainFrameRect:" NSTRACE_FMT_RECT " toScreen:",
7525 NSTRACE_ARG_RECT (frameRect));
7527 #ifdef NS_IMPL_COCOA
7528 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7529 // If separate spaces is on, it is like each screen is independent. There is
7530 // no spanning of frames across screens.
7531 if ([NSScreen screensHaveSeparateSpaces])
7533 NSTRACE_MSG ("Screens have separate spaces");
7534 frameRect = [super constrainFrameRect:frameRect toScreen:screen];
7535 NSTRACE_RETURN_RECT (frameRect);
7541 return constrain_frame_rect(frameRect);
7545 - (void)performZoom:(id)sender
7547 NSTRACE ("performZoom");
7549 return [super performZoom:sender];
7552 - (void)zoom:(id)sender
7554 struct frame * f = SELECTED_FRAME ();
7558 ns_update_auto_hide_menu_bar();
7560 // Below are three zoom implementations. In the final commit, the
7561 // idea is that the last should be included.
7564 // Native zoom done using the standard zoom animation. Size of the
7565 // resulting frame reduced to accomodate the Dock and, if present,
7567 [super zoom:sender];
7570 // Native zoom done using the standard zoom animation, plus an
7571 // explicit resize to cover the full screen.
7572 [super zoom:sender];
7574 // After the native zoom, resize the resulting frame to fill the
7575 // entire screen, except the menu-bar.
7577 // This works for all practical purposes. (The only minor oddity is
7578 // when transiting from full-height frame to a maximized, the
7579 // animation reduces the height of the frame slighty (to the 4
7580 // pixels needed to accomodate the Doc) before it snaps back into
7581 // full height. The user would need a very trained eye to spot
7583 NSScreen * screen = [self screen];
7586 int fs_state = [(EmacsView *)[self delegate] fullscreenState];
7588 NSTRACE_FSTYPE ("fullscreenState", fs_state);
7590 NSRect sr = [screen frame];
7591 NSRect wr = [self frame];
7592 NSTRACE_RECT ("Rect after zoom", wr);
7596 if (fs_state == FULLSCREEN_MAXIMIZED
7597 || fs_state == FULLSCREEN_HEIGHT)
7600 newWr.size.height = sr.size.height - ns_menu_bar_height(screen);
7603 if (fs_state == FULLSCREEN_MAXIMIZED
7604 || fs_state == FULLSCREEN_WIDTH)
7607 newWr.size.width = sr.size.width;
7610 if (newWr.size.width != wr.size.width
7611 || newWr.size.height != wr.size.height
7612 || newWr.origin.x != wr.origin.x
7613 || newWr.origin.y != wr.origin.y)
7615 NSTRACE_RECT ("Corrected rect", newWr);
7616 [self setFrame: newWr display: NO];
7620 // Non-native zoom which is done instantaneous. The resulting frame
7621 // covert the entire scrren, except the menu-bar, if present.
7622 NSScreen * screen = [self screen];
7625 NSRect sr = [screen frame];
7626 sr.size.height -= ns_menu_bar_height (screen);
7628 sr = [[self delegate] windowWillUseStandardFrame:self
7630 [self setFrame: sr display: NO];
7635 @end /* EmacsWindow */
7638 @implementation EmacsFSWindow
7640 - (BOOL)canBecomeKeyWindow
7645 - (BOOL)canBecomeMainWindow
7652 /* ==========================================================================
7654 EmacsScroller implementation
7656 ========================================================================== */
7659 @implementation EmacsScroller
7661 /* for repeat button push */
7662 #define SCROLL_BAR_FIRST_DELAY 0.5
7663 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
7665 + (CGFloat) scrollerWidth
7667 /* TODO: if we want to allow variable widths, this is the place to do it,
7668 however neither GNUstep nor Cocoa support it very well */
7670 #if !defined (NS_IMPL_COCOA) || \
7671 MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
7672 r = [NSScroller scrollerWidth];
7674 r = [NSScroller scrollerWidthForControlSize: NSRegularControlSize
7675 scrollerStyle: NSScrollerStyleLegacy];
7681 - initFrame: (NSRect )r window: (Lisp_Object)nwin
7683 NSTRACE ("EmacsScroller_initFrame");
7685 r.size.width = [EmacsScroller scrollerWidth];
7686 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
7687 [self setContinuous: YES];
7688 [self setEnabled: YES];
7690 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
7691 locked against the top and bottom edges, and right edge on OS X, where
7692 scrollers are on right. */
7693 #ifdef NS_IMPL_GNUSTEP
7694 [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
7696 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
7699 window = XWINDOW (nwin);
7701 pixel_height = NSHeight (r);
7702 if (pixel_height == 0) pixel_height = 1;
7703 min_portion = 20 / pixel_height;
7705 frame = XFRAME (window->frame);
7706 if (FRAME_LIVE_P (frame))
7709 EmacsView *view = FRAME_NS_VIEW (frame);
7710 NSView *sview = [[view window] contentView];
7711 NSArray *subs = [sview subviews];
7713 /* disable optimization stopping redraw of other scrollbars */
7714 view->scrollbarsNeedingUpdate = 0;
7715 for (i =[subs count]-1; i >= 0; i--)
7716 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
7717 view->scrollbarsNeedingUpdate++;
7718 [sview addSubview: self];
7721 /* [self setFrame: r]; */
7727 - (void)setFrame: (NSRect)newRect
7729 NSTRACE ("EmacsScroller_setFrame");
7730 /* block_input (); */
7731 pixel_height = NSHeight (newRect);
7732 if (pixel_height == 0) pixel_height = 1;
7733 min_portion = 20 / pixel_height;
7734 [super setFrame: newRect];
7735 /* unblock_input (); */
7741 NSTRACE ("EmacsScroller_dealloc");
7743 wset_vertical_scroll_bar (window, Qnil);
7751 NSTRACE ("condemn");
7759 NSTRACE ("reprieve");
7768 bool ret = condemned;
7773 /* ensure other scrollbar updates after deletion */
7774 view = (EmacsView *)FRAME_NS_VIEW (frame);
7776 view->scrollbarsNeedingUpdate++;
7778 wset_vertical_scroll_bar (window, Qnil);
7780 [self removeFromSuperview];
7788 - (void)resetCursorRects
7790 NSRect visible = [self visibleRect];
7791 NSTRACE ("resetCursorRects");
7793 if (!NSIsEmptyRect (visible))
7794 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
7795 [[NSCursor arrowCursor] setOnMouseEntered: YES];
7799 - (int) checkSamePosition: (int) position portion: (int) portion
7802 return em_position ==position && em_portion ==portion && em_whole ==whole
7803 && portion != whole; /* needed for resize empty buf */
7807 - setPosition: (int)position portion: (int)portion whole: (int)whole
7809 NSTRACE ("setPosition");
7811 em_position = position;
7812 em_portion = portion;
7815 if (portion >= whole)
7817 #ifdef NS_IMPL_COCOA
7818 [self setKnobProportion: 1.0];
7819 [self setDoubleValue: 1.0];
7821 [self setFloatValue: 0.0 knobProportion: 1.0];
7828 portion = max ((float)whole*min_portion/pixel_height, portion);
7829 pos = (float)position / (whole - portion);
7830 por = (CGFloat)portion/whole;
7831 #ifdef NS_IMPL_COCOA
7832 [self setKnobProportion: por];
7833 [self setDoubleValue: pos];
7835 [self setFloatValue: pos knobProportion: por];
7842 /* set up emacs_event */
7843 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
7849 emacs_event->part = last_hit_part;
7850 emacs_event->code = 0;
7851 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
7852 XSETWINDOW (win, window);
7853 emacs_event->frame_or_window = win;
7854 emacs_event->timestamp = EV_TIMESTAMP (e);
7855 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
7856 emacs_event->arg = Qnil;
7857 XSETINT (emacs_event->x, loc * pixel_height);
7858 XSETINT (emacs_event->y, pixel_height-20);
7862 n_emacs_events_pending++;
7863 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
7866 hold_event (emacs_event);
7867 EVENT_INIT (*emacs_event);
7868 ns_send_appdefined (-1);
7872 /* called manually thru timer to implement repeated button action w/hold-down */
7873 - repeatScroll: (NSTimer *)scrollEntry
7875 NSEvent *e = [[self window] currentEvent];
7876 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
7877 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
7879 /* clear timer if need be */
7880 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
7882 [scroll_repeat_entry invalidate];
7883 [scroll_repeat_entry release];
7884 scroll_repeat_entry = nil;
7890 = [[NSTimer scheduledTimerWithTimeInterval:
7891 SCROLL_BAR_CONTINUOUS_DELAY
7893 selector: @selector (repeatScroll:)
7899 [self sendScrollEventAtLoc: 0 fromEvent: e];
7904 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
7905 mouseDragged events without going into a modal loop. */
7906 - (void)mouseDown: (NSEvent *)e
7909 /* hitPart is only updated AFTER event is passed on */
7910 NSScrollerPart part = [self testPart: [e locationInWindow]];
7911 CGFloat inc = 0.0, loc, kloc, pos;
7914 NSTRACE ("EmacsScroller_mouseDown");
7918 case NSScrollerDecrementPage:
7919 last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
7920 case NSScrollerIncrementPage:
7921 last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
7922 case NSScrollerDecrementLine:
7923 last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
7924 case NSScrollerIncrementLine:
7925 last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
7926 case NSScrollerKnob:
7927 last_hit_part = scroll_bar_handle; break;
7928 case NSScrollerKnobSlot: /* GNUstep-only */
7929 last_hit_part = scroll_bar_move_ratio; break;
7930 default: /* NSScrollerNoPart? */
7931 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
7938 pos = 0; /* ignored */
7940 /* set a timer to repeat, as we can't let superclass do this modally */
7942 = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
7944 selector: @selector (repeatScroll:)
7951 /* handle, or on GNUstep possibly slot */
7952 NSEvent *fake_event;
7954 /* compute float loc in slot and mouse offset on knob */
7955 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
7957 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
7963 else if (loc >= NSHeight (sr))
7965 loc = NSHeight (sr);
7973 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
7975 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
7977 last_mouse_offset = kloc;
7979 /* if knob, tell emacs a location offset by knob pos
7980 (to indicate top of handle) */
7981 if (part == NSScrollerKnob)
7982 pos = (loc - last_mouse_offset) / NSHeight (sr);
7984 /* else this is a slot click on GNUstep: go straight there */
7985 pos = loc / NSHeight (sr);
7987 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
7988 fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
7989 location: [e locationInWindow]
7990 modifierFlags: [e modifierFlags]
7991 timestamp: [e timestamp]
7992 windowNumber: [e windowNumber]
7993 context: [e context]
7994 eventNumber: [e eventNumber]
7995 clickCount: [e clickCount]
7996 pressure: [e pressure]];
7997 [super mouseUp: fake_event];
8000 if (part != NSScrollerKnob)
8001 [self sendScrollEventAtLoc: pos fromEvent: e];
8005 /* Called as we manually track scroller drags, rather than superclass. */
8006 - (void)mouseDragged: (NSEvent *)e
8011 NSTRACE ("EmacsScroller_mouseDragged");
8013 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
8015 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
8021 else if (loc >= NSHeight (sr) + last_mouse_offset)
8023 loc = NSHeight (sr) + last_mouse_offset;
8026 pos = (loc - last_mouse_offset) / NSHeight (sr);
8027 [self sendScrollEventAtLoc: pos fromEvent: e];
8031 - (void)mouseUp: (NSEvent *)e
8033 if (scroll_repeat_entry)
8035 [scroll_repeat_entry invalidate];
8036 [scroll_repeat_entry release];
8037 scroll_repeat_entry = nil;
8039 last_hit_part = scroll_bar_above_handle;
8043 /* treat scrollwheel events in the bar as though they were in the main window */
8044 - (void) scrollWheel: (NSEvent *)theEvent
8046 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
8047 [view mouseDown: theEvent];
8050 @end /* EmacsScroller */
8053 #ifdef NS_IMPL_GNUSTEP
8054 /* Dummy class to get rid of startup warnings. */
8055 @implementation EmacsDocument
8061 /* ==========================================================================
8063 Font-related functions; these used to be in nsfaces.m
8065 ========================================================================== */
8069 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
8071 struct font *font = XFONT_OBJECT (font_object);
8072 EmacsView *view = FRAME_NS_VIEW (f);
8073 int font_ascent, font_descent;
8076 fontset = fontset_from_font (font_object);
8077 FRAME_FONTSET (f) = fontset;
8079 if (FRAME_FONT (f) == font)
8080 /* This font is already set in frame F. There's nothing more to
8084 FRAME_FONT (f) = font;
8086 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
8087 FRAME_COLUMN_WIDTH (f) = font->average_width;
8088 get_font_ascent_descent (font, &font_ascent, &font_descent);
8089 FRAME_LINE_HEIGHT (f) = font_ascent + font_descent;
8091 /* Compute the scroll bar width in character columns. */
8092 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
8094 int wid = FRAME_COLUMN_WIDTH (f);
8095 FRAME_CONFIG_SCROLL_BAR_COLS (f)
8096 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
8100 int wid = FRAME_COLUMN_WIDTH (f);
8101 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
8104 /* Compute the scroll bar height in character lines. */
8105 if (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) > 0)
8107 int height = FRAME_LINE_HEIGHT (f);
8108 FRAME_CONFIG_SCROLL_BAR_LINES (f)
8109 = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + height - 1) / height;
8113 int height = FRAME_LINE_HEIGHT (f);
8114 FRAME_CONFIG_SCROLL_BAR_LINES (f) = (14 + height - 1) / height;
8117 /* Now make the frame display the given font. */
8118 if (FRAME_NS_WINDOW (f) != 0 && ! [view isFullscreen])
8119 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
8120 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 3,
8127 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
8128 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
8132 ns_xlfd_to_fontname (const char *xlfd)
8133 /* --------------------------------------------------------------------------
8134 Convert an X font name (XLFD) to an NS font name.
8135 Only family is used.
8136 The string returned is temporarily allocated.
8137 -------------------------------------------------------------------------- */
8139 char *name = xmalloc (180);
8143 if (!strncmp (xlfd, "--", 2))
8144 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
8146 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
8148 /* stopgap for malformed XLFD input */
8149 if (strlen (name) == 0)
8150 strcpy (name, "Monaco");
8152 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
8153 also uppercase after '-' or ' ' */
8154 name[0] = c_toupper (name[0]);
8155 for (len =strlen (name), i =0; i<len; i++)
8161 name[i+1] = c_toupper (name[i+1]);
8163 else if (name[i] == '_')
8167 name[i+1] = c_toupper (name[i+1]);
8170 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
8171 ret = [[NSString stringWithUTF8String: name] UTF8String];
8178 syms_of_nsterm (void)
8180 NSTRACE ("syms_of_nsterm");
8182 ns_antialias_threshold = 10.0;
8184 /* from 23+ we need to tell emacs what modifiers there are.. */
8185 DEFSYM (Qmodifier_value, "modifier-value");
8186 DEFSYM (Qalt, "alt");
8187 DEFSYM (Qhyper, "hyper");
8188 DEFSYM (Qmeta, "meta");
8189 DEFSYM (Qsuper, "super");
8190 DEFSYM (Qcontrol, "control");
8191 DEFSYM (QUTF8_STRING, "UTF8_STRING");
8193 DEFSYM (Qfile, "file");
8194 DEFSYM (Qurl, "url");
8196 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
8197 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
8198 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
8199 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
8200 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
8202 DEFVAR_LISP ("ns-input-file", ns_input_file,
8203 "The file specified in the last NS event.");
8204 ns_input_file =Qnil;
8206 DEFVAR_LISP ("ns-working-text", ns_working_text,
8207 "String for visualizing working composition sequence.");
8208 ns_working_text =Qnil;
8210 DEFVAR_LISP ("ns-input-font", ns_input_font,
8211 "The font specified in the last NS event.");
8212 ns_input_font =Qnil;
8214 DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
8215 "The fontsize specified in the last NS event.");
8216 ns_input_fontsize =Qnil;
8218 DEFVAR_LISP ("ns-input-line", ns_input_line,
8219 "The line specified in the last NS event.");
8220 ns_input_line =Qnil;
8222 DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
8223 "The service name specified in the last NS event.");
8224 ns_input_spi_name =Qnil;
8226 DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
8227 "The service argument specified in the last NS event.");
8228 ns_input_spi_arg =Qnil;
8230 DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
8231 "This variable describes the behavior of the alternate or option key.\n\
8232 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8233 Set to none means that the alternate / option key is not interpreted by Emacs\n\
8234 at all, allowing it to be used at a lower level for accented character entry.");
8235 ns_alternate_modifier = Qmeta;
8237 DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
8238 "This variable describes the behavior of the right alternate or option key.\n\
8239 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8240 Set to left means be the same key as `ns-alternate-modifier'.\n\
8241 Set to none means that the alternate / option key is not interpreted by Emacs\n\
8242 at all, allowing it to be used at a lower level for accented character entry.");
8243 ns_right_alternate_modifier = Qleft;
8245 DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
8246 "This variable describes the behavior of the command key.\n\
8247 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
8248 ns_command_modifier = Qsuper;
8250 DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
8251 "This variable describes the behavior of the right command key.\n\
8252 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8253 Set to left means be the same key as `ns-command-modifier'.\n\
8254 Set to none means that the command / option key is not interpreted by Emacs\n\
8255 at all, allowing it to be used at a lower level for accented character entry.");
8256 ns_right_command_modifier = Qleft;
8258 DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
8259 "This variable describes the behavior of the control key.\n\
8260 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
8261 ns_control_modifier = Qcontrol;
8263 DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
8264 "This variable describes the behavior of the right control key.\n\
8265 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8266 Set to left means be the same key as `ns-control-modifier'.\n\
8267 Set to none means that the control / option key is not interpreted by Emacs\n\
8268 at all, allowing it to be used at a lower level for accented character entry.");
8269 ns_right_control_modifier = Qleft;
8271 DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
8272 "This variable describes the behavior of the function key (on laptops).\n\
8273 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8274 Set to none means that the function key is not interpreted by Emacs at all,\n\
8275 allowing it to be used at a lower level for accented character entry.");
8276 ns_function_modifier = Qnone;
8278 DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
8279 "Non-nil (the default) means to render text antialiased.");
8280 ns_antialias_text = Qt;
8282 DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
8283 "Whether to confirm application quit using dialog.");
8284 ns_confirm_quit = Qnil;
8286 DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
8287 doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
8288 Only works on OSX 10.6 or later. */);
8289 ns_auto_hide_menu_bar = Qnil;
8291 DEFVAR_BOOL ("ns-use-native-fullscreen", ns_use_native_fullscreen,
8292 doc: /*Non-nil means to use native fullscreen on OSX >= 10.7.
8293 Nil means use fullscreen the old (< 10.7) way. The old way works better with
8294 multiple monitors, but lacks tool bar. This variable is ignored on OSX < 10.7.
8295 Default is t for OSX >= 10.7, nil otherwise. */);
8296 #ifdef HAVE_NATIVE_FS
8297 ns_use_native_fullscreen = YES;
8299 ns_use_native_fullscreen = NO;
8301 ns_last_use_native_fullscreen = ns_use_native_fullscreen;
8303 DEFVAR_BOOL ("ns-use-fullscreen-animation", ns_use_fullscreen_animation,
8304 doc: /*Non-nil means use animation on non-native fullscreen.
8305 For native fullscreen, this does nothing.
8306 Default is nil. */);
8307 ns_use_fullscreen_animation = NO;
8309 DEFVAR_BOOL ("ns-use-srgb-colorspace", ns_use_srgb_colorspace,
8310 doc: /*Non-nil means to use sRGB colorspace on OSX >= 10.7.
8311 Note that this does not apply to images.
8312 This variable is ignored on OSX < 10.7 and GNUstep. */);
8313 ns_use_srgb_colorspace = YES;
8315 /* TODO: move to common code */
8316 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
8317 doc: /* Which toolkit scroll bars Emacs uses, if any.
8318 A value of nil means Emacs doesn't use toolkit scroll bars.
8319 With the X Window system, the value is a symbol describing the
8320 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
8321 With MS Windows or Nextstep, the value is t. */);
8322 Vx_toolkit_scroll_bars = Qt;
8324 DEFVAR_BOOL ("x-use-underline-position-properties",
8325 x_use_underline_position_properties,
8326 doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
8327 A value of nil means ignore them. If you encounter fonts with bogus
8328 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
8329 to 4.1, set this to nil. */);
8330 x_use_underline_position_properties = 0;
8332 DEFVAR_BOOL ("x-underline-at-descent-line",
8333 x_underline_at_descent_line,
8334 doc: /* Non-nil means to draw the underline at the same place as the descent line.
8335 A value of nil means to draw the underline according to the value of the
8336 variable `x-use-underline-position-properties', which is usually at the
8337 baseline level. The default value is nil. */);
8338 x_underline_at_descent_line = 0;
8340 /* Tell Emacs about this window system. */
8341 Fprovide (Qns, Qnil);
8343 DEFSYM (Qcocoa, "cocoa");
8344 DEFSYM (Qgnustep, "gnustep");
8346 #ifdef NS_IMPL_COCOA
8347 Fprovide (Qcocoa, Qnil);
8350 Fprovide (Qgnustep, Qnil);