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 ("current", 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 NSTRACE_RECT ("setFrame", wr);
1567 [window setFrame: wr display: YES];
1569 /* This is a trick to compensate for Emacs' managing the scrollbar area
1570 as a fixed number of standard character columns. Instead of leaving
1571 blank space for the extra, we chopped it off above. Now for
1572 left-hand scrollbars, we shift all rendering to the left by the
1573 difference between the real width and Emacs' imagined one. For
1574 right-hand bars, don't worry about it since the extra is never used.
1575 (Obviously doesn't work for vertically split windows tho..) */
1577 NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1578 ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1579 - NS_SCROLL_BAR_WIDTH (f), 0)
1580 : NSMakePoint (0, 0);
1581 NSTRACE_RECT ("setFrame", wr);
1582 [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1583 [view setBoundsOrigin: origin];
1586 [view updateFrameSize: NO];
1592 ns_fullscreen_hook (struct frame *f)
1594 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1596 NSTRACE ("ns_fullscreen_hook");
1598 if (!FRAME_VISIBLE_P (f))
1601 if (! [view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH)
1603 /* Old style fs don't initiate correctly if created from
1604 init/default-frame alist, so use a timer (not nice...).
1606 [NSTimer scheduledTimerWithTimeInterval: 0.5 target: view
1607 selector: @selector (handleFS)
1608 userInfo: nil repeats: NO];
1617 /* ==========================================================================
1621 ========================================================================== */
1625 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1627 struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1628 if (idx < 1 || idx >= color_table->avail)
1630 return color_table->colors[idx];
1635 ns_index_color (NSColor *color, struct frame *f)
1637 struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1641 if (!color_table->colors)
1643 color_table->size = NS_COLOR_CAPACITY;
1644 color_table->avail = 1; /* skip idx=0 as marker */
1645 color_table->colors = xmalloc (color_table->size * sizeof (NSColor *));
1646 color_table->colors[0] = nil;
1647 color_table->empty_indices = [[NSMutableSet alloc] init];
1650 /* Do we already have this color? */
1651 for (i = 1; i < color_table->avail; i++)
1652 if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1655 if ([color_table->empty_indices count] > 0)
1657 NSNumber *index = [color_table->empty_indices anyObject];
1658 [color_table->empty_indices removeObject: index];
1659 idx = [index unsignedLongValue];
1663 if (color_table->avail == color_table->size)
1664 color_table->colors =
1665 xpalloc (color_table->colors, &color_table->size, 1,
1666 min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1667 idx = color_table->avail++;
1670 color_table->colors[idx] = color;
1672 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1678 ns_free_indexed_color (unsigned long idx, struct frame *f)
1680 struct ns_color_table *color_table;
1687 color_table = FRAME_DISPLAY_INFO (f)->color_table;
1689 if (idx <= 0 || idx >= color_table->size) {
1690 message1 ("ns_free_indexed_color: Color index out of range.\n");
1694 index = [NSNumber numberWithUnsignedInt: idx];
1695 if ([color_table->empty_indices containsObject: index]) {
1696 message1 ("ns_free_indexed_color: attempt to free already freed color.\n");
1700 color = color_table->colors[idx];
1702 color_table->colors[idx] = nil;
1703 [color_table->empty_indices addObject: index];
1704 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1709 ns_get_color (const char *name, NSColor **col)
1710 /* --------------------------------------------------------------------------
1712 -------------------------------------------------------------------------- */
1713 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1714 X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1715 See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1718 static char hex[20];
1720 float r = -1.0, g, b;
1721 NSString *nsname = [NSString stringWithUTF8String: name];
1723 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1726 if ([nsname isEqualToString: @"ns_selection_bg_color"])
1728 #ifdef NS_IMPL_COCOA
1729 NSString *defname = [[NSUserDefaults standardUserDefaults]
1730 stringForKey: @"AppleHighlightColor"];
1735 if ((new = [NSColor selectedTextBackgroundColor]) != nil)
1737 *col = [new colorUsingDefaultColorSpace];
1742 nsname = NS_SELECTION_BG_COLOR_DEFAULT;
1744 name = [nsname UTF8String];
1746 else if ([nsname isEqualToString: @"ns_selection_fg_color"])
1748 /* NOTE: OSX applications normally don't set foreground selection, but
1749 text may be unreadable if we don't.
1751 if ((new = [NSColor selectedTextColor]) != nil)
1753 *col = [new colorUsingDefaultColorSpace];
1758 nsname = NS_SELECTION_FG_COLOR_DEFAULT;
1759 name = [nsname UTF8String];
1762 /* First, check for some sort of numeric specification. */
1765 if (name[0] == '0' || name[0] == '1' || name[0] == '.') /* RGB decimal */
1767 NSScanner *scanner = [NSScanner scannerWithString: nsname];
1768 [scanner scanFloat: &r];
1769 [scanner scanFloat: &g];
1770 [scanner scanFloat: &b];
1772 else if (!strncmp(name, "rgb:", 4)) /* A newer X11 format -- rgb:r/g/b */
1773 scaling = (snprintf (hex, sizeof hex, "%s", name + 4) - 2) / 3;
1774 else if (name[0] == '#') /* An old X11 format; convert to newer */
1776 int len = (strlen(name) - 1);
1777 int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1779 scaling = strlen(name+start) / 3;
1780 for (i = 0; i < 3; i++)
1781 sprintf (hex + i * (scaling + 1), "%.*s/", scaling,
1782 name + start + i * scaling);
1783 hex[3 * (scaling + 1) - 1] = '\0';
1789 float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1790 if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1800 *col = [NSColor colorForEmacsRed: r green: g blue: b alpha: 1.0];
1805 /* Otherwise, color is expected to be from a list */
1807 NSEnumerator *lenum, *cenum;
1811 #ifdef NS_IMPL_GNUSTEP
1812 /* XXX: who is wrong, the requestor or the implementation? */
1813 if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1815 nsname = @"highlightColor";
1818 lenum = [[NSColorList availableColorLists] objectEnumerator];
1819 while ( (clist = [lenum nextObject]) && new == nil)
1821 cenum = [[clist allKeys] objectEnumerator];
1822 while ( (name = [cenum nextObject]) && new == nil )
1824 if ([name compare: nsname
1825 options: NSCaseInsensitiveSearch] == NSOrderedSame )
1826 new = [clist colorWithKey: name];
1832 *col = [new colorUsingDefaultColorSpace];
1839 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1840 /* --------------------------------------------------------------------------
1841 Convert a Lisp string object to a NS color
1842 -------------------------------------------------------------------------- */
1844 NSTRACE ("ns_lisp_to_color");
1845 if (STRINGP (color))
1846 return ns_get_color (SSDATA (color), col);
1847 else if (SYMBOLP (color))
1848 return ns_get_color (SSDATA (SYMBOL_NAME (color)), col);
1854 ns_color_to_lisp (NSColor *col)
1855 /* --------------------------------------------------------------------------
1856 Convert a color to a lisp string with the RGB equivalent
1857 -------------------------------------------------------------------------- */
1859 EmacsCGFloat red, green, blue, alpha, gray;
1862 NSTRACE ("ns_color_to_lisp");
1865 if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1867 if ((str =[[col colorNameComponent] UTF8String]))
1870 return build_string ((char *)str);
1873 [[col colorUsingDefaultColorSpace]
1874 getRed: &red green: &green blue: &blue alpha: &alpha];
1875 if (red == green && red == blue)
1877 [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1878 getWhite: &gray alpha: &alpha];
1879 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1880 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1882 return build_string (buf);
1885 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1886 lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1889 return build_string (buf);
1894 ns_query_color(void *col, XColor *color_def, int setPixel)
1895 /* --------------------------------------------------------------------------
1896 Get ARGB values out of NSColor col and put them into color_def.
1897 If setPixel, set the pixel to a concatenated version.
1898 and set color_def pixel to the resulting index.
1899 -------------------------------------------------------------------------- */
1901 EmacsCGFloat r, g, b, a;
1903 [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1904 color_def->red = r * 65535;
1905 color_def->green = g * 65535;
1906 color_def->blue = b * 65535;
1908 if (setPixel == YES)
1910 = ARGB_TO_ULONG((int)(a*255),
1911 (int)(r*255), (int)(g*255), (int)(b*255));
1916 ns_defined_color (struct frame *f,
1921 /* --------------------------------------------------------------------------
1922 Return true if named color found, and set color_def rgb accordingly.
1923 If makeIndex and alloc are nonzero put the color in the color_table,
1924 and set color_def pixel to the resulting index.
1925 If makeIndex is zero, set color_def pixel to ARGB.
1926 Return false if not found
1927 -------------------------------------------------------------------------- */
1930 NSTRACE ("ns_defined_color");
1933 if (ns_get_color (name, &col) != 0) /* Color not found */
1938 if (makeIndex && alloc)
1939 color_def->pixel = ns_index_color (col, f);
1940 ns_query_color (col, color_def, !makeIndex);
1947 x_set_frame_alpha (struct frame *f)
1948 /* --------------------------------------------------------------------------
1949 change the entire-frame transparency
1950 -------------------------------------------------------------------------- */
1952 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1954 double alpha_min = 1.0;
1956 if (dpyinfo->x_highlight_frame == f)
1957 alpha = f->alpha[0];
1959 alpha = f->alpha[1];
1961 if (FLOATP (Vframe_alpha_lower_limit))
1962 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1963 else if (INTEGERP (Vframe_alpha_lower_limit))
1964 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1968 else if (1.0 < alpha)
1970 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1973 #ifdef NS_IMPL_COCOA
1975 EmacsView *view = FRAME_NS_VIEW (f);
1976 [[view window] setAlphaValue: alpha];
1982 /* ==========================================================================
1986 ========================================================================== */
1990 frame_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1991 /* --------------------------------------------------------------------------
1992 Programmatically reposition mouse pointer in pixel coordinates
1993 -------------------------------------------------------------------------- */
1995 NSTRACE ("frame_set_mouse_pixel_position");
1998 /* FIXME: this does not work, and what about GNUstep? */
1999 #ifdef NS_IMPL_COCOA
2000 [FRAME_NS_VIEW (f) lockFocus];
2001 PSsetmouse ((float)pix_x, (float)pix_y);
2002 [FRAME_NS_VIEW (f) unlockFocus];
2008 note_mouse_movement (struct frame *frame, CGFloat x, CGFloat y)
2009 /* ------------------------------------------------------------------------
2010 Called by EmacsView on mouseMovement events. Passes on
2011 to emacs mainstream code if we moved off of a rect of interest
2012 known as last_mouse_glyph.
2013 ------------------------------------------------------------------------ */
2015 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
2018 // NSTRACE ("note_mouse_movement");
2020 dpyinfo->last_mouse_motion_frame = frame;
2021 r = &dpyinfo->last_mouse_glyph;
2023 /* Note, this doesn't get called for enter/leave, since we don't have a
2024 position. Those are taken care of in the corresponding NSView methods. */
2026 /* has movement gone beyond last rect we were tracking? */
2027 if (x < r->origin.x || x >= r->origin.x + r->size.width
2028 || y < r->origin.y || y >= r->origin.y + r->size.height)
2030 ns_update_begin (frame);
2031 frame->mouse_moved = 1;
2032 note_mouse_highlight (frame, x, y);
2033 remember_mouse_glyph (frame, x, y, r);
2034 ns_update_end (frame);
2043 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
2044 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
2046 /* --------------------------------------------------------------------------
2047 External (hook): inform emacs about mouse position and hit parts.
2048 If a scrollbar is being dragged, set bar_window, part, x, y, time.
2049 x & y should be position in the scrollbar (the whole bar, not the handle)
2050 and length of scrollbar respectively
2051 -------------------------------------------------------------------------- */
2055 Lisp_Object frame, tail;
2057 struct ns_display_info *dpyinfo;
2059 NSTRACE ("ns_mouse_position");
2063 fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
2067 dpyinfo = FRAME_DISPLAY_INFO (*fp);
2071 /* Clear the mouse-moved flag for every frame on this display. */
2072 FOR_EACH_FRAME (tail, frame)
2073 if (FRAME_NS_P (XFRAME (frame))
2074 && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
2075 XFRAME (frame)->mouse_moved = 0;
2077 dpyinfo->last_mouse_scroll_bar = nil;
2078 if (dpyinfo->last_mouse_frame
2079 && FRAME_LIVE_P (dpyinfo->last_mouse_frame))
2080 f = dpyinfo->last_mouse_frame;
2082 f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame : SELECTED_FRAME ();
2084 if (f && FRAME_NS_P (f))
2086 view = FRAME_NS_VIEW (*fp);
2088 position = [[view window] mouseLocationOutsideOfEventStream];
2089 position = [view convertPoint: position fromView: nil];
2090 remember_mouse_glyph (f, position.x, position.y,
2091 &dpyinfo->last_mouse_glyph);
2092 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
2094 if (bar_window) *bar_window = Qnil;
2095 if (part) *part = scroll_bar_above_handle;
2097 if (x) XSETINT (*x, lrint (position.x));
2098 if (y) XSETINT (*y, lrint (position.y));
2100 *time = dpyinfo->last_mouse_movement_time;
2109 ns_frame_up_to_date (struct frame *f)
2110 /* --------------------------------------------------------------------------
2111 External (hook): Fix up mouse highlighting right after a full update.
2112 Can't use FRAME_MOUSE_UPDATE due to ns_frame_begin and ns_frame_end calls.
2113 -------------------------------------------------------------------------- */
2115 NSTRACE ("ns_frame_up_to_date");
2119 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
2120 if (f == hlinfo->mouse_face_mouse_frame)
2124 note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
2125 hlinfo->mouse_face_mouse_x,
2126 hlinfo->mouse_face_mouse_y);
2135 ns_define_frame_cursor (struct frame *f, Cursor cursor)
2136 /* --------------------------------------------------------------------------
2137 External (RIF): set frame mouse pointer type.
2138 -------------------------------------------------------------------------- */
2140 NSTRACE ("ns_define_frame_cursor");
2141 if (FRAME_POINTER_TYPE (f) != cursor)
2143 EmacsView *view = FRAME_NS_VIEW (f);
2144 FRAME_POINTER_TYPE (f) = cursor;
2145 [[view window] invalidateCursorRectsForView: view];
2146 /* Redisplay assumes this function also draws the changed frame
2147 cursor, but this function doesn't, so do it explicitly. */
2148 x_update_cursor (f, 1);
2154 /* ==========================================================================
2158 ========================================================================== */
2162 ns_convert_key (unsigned code)
2163 /* --------------------------------------------------------------------------
2164 Internal call used by NSView-keyDown.
2165 -------------------------------------------------------------------------- */
2167 const unsigned last_keysym = ARRAYELTS (convert_ns_to_X_keysym);
2169 /* An array would be faster, but less easy to read. */
2170 for (keysym = 0; keysym < last_keysym; keysym += 2)
2171 if (code == convert_ns_to_X_keysym[keysym])
2172 return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
2174 /* if decide to use keyCode and Carbon table, use this line:
2175 return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
2180 x_get_keysym_name (int keysym)
2181 /* --------------------------------------------------------------------------
2182 Called by keyboard.c. Not sure if the return val is important, except
2184 -------------------------------------------------------------------------- */
2186 static char value[16];
2187 NSTRACE ("x_get_keysym_name");
2188 sprintf (value, "%d", keysym);
2194 /* ==========================================================================
2196 Block drawing operations
2198 ========================================================================== */
2202 ns_redraw_scroll_bars (struct frame *f)
2206 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
2207 NSTRACE ("ns_redraw_scroll_bars");
2208 for (i =[subviews count]-1; i >= 0; i--)
2210 view = [subviews objectAtIndex: i];
2211 if (![view isKindOfClass: [EmacsScroller class]]) continue;
2218 ns_clear_frame (struct frame *f)
2219 /* --------------------------------------------------------------------------
2220 External (hook): Erase the entire frame
2221 -------------------------------------------------------------------------- */
2223 NSView *view = FRAME_NS_VIEW (f);
2226 NSTRACE ("ns_clear_frame");
2228 /* comes on initial frame because we have
2229 after-make-frame-functions = select-frame */
2230 if (!FRAME_DEFAULT_FACE (f))
2233 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2238 ns_focus (f, &r, 1);
2239 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
2243 /* as of 2006/11 or so this is now needed */
2244 ns_redraw_scroll_bars (f);
2250 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2251 /* --------------------------------------------------------------------------
2252 External (RIF): Clear section of frame
2253 -------------------------------------------------------------------------- */
2255 NSRect r = NSMakeRect (x, y, width, height);
2256 NSView *view = FRAME_NS_VIEW (f);
2257 struct face *face = FRAME_DEFAULT_FACE (f);
2262 NSTRACE ("ns_clear_frame_area");
2264 r = NSIntersectionRect (r, [view frame]);
2265 ns_focus (f, &r, 1);
2266 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2275 ns_copy_bits (struct frame *f, NSRect src, NSRect dest)
2277 if (FRAME_NS_VIEW (f))
2279 ns_focus (f, &dest, 1);
2280 [FRAME_NS_VIEW (f) scrollRect: src
2281 by: NSMakeSize (dest.origin.x - src.origin.x,
2282 dest.origin.y - src.origin.y)];
2288 ns_scroll_run (struct window *w, struct run *run)
2289 /* --------------------------------------------------------------------------
2290 External (RIF): Insert or delete n lines at line vpos
2291 -------------------------------------------------------------------------- */
2293 struct frame *f = XFRAME (w->frame);
2294 int x, y, width, height, from_y, to_y, bottom_y;
2296 NSTRACE ("ns_scroll_run");
2298 /* begin copy from other terms */
2299 /* Get frame-relative bounding box of the text display area of W,
2300 without mode lines. Include in this box the left and right
2302 window_box (w, ANY_AREA, &x, &y, &width, &height);
2304 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2305 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2306 bottom_y = y + height;
2310 /* Scrolling up. Make sure we don't copy part of the mode
2311 line at the bottom. */
2312 if (from_y + run->height > bottom_y)
2313 height = bottom_y - from_y;
2315 height = run->height;
2319 /* Scrolling down. Make sure we don't copy over the mode line.
2321 if (to_y + run->height > bottom_y)
2322 height = bottom_y - to_y;
2324 height = run->height;
2326 /* end copy from other terms */
2336 NSRect srcRect = NSMakeRect (x, from_y, width, height);
2337 NSRect dstRect = NSMakeRect (x, to_y, width, height);
2339 ns_copy_bits (f, srcRect , dstRect);
2347 ns_after_update_window_line (struct window *w, struct glyph_row *desired_row)
2348 /* --------------------------------------------------------------------------
2349 External (RIF): preparatory to fringe update after text was updated
2350 -------------------------------------------------------------------------- */
2355 NSTRACE ("ns_after_update_window_line");
2357 /* begin copy from other terms */
2360 if (!desired_row->mode_line_p && !w->pseudo_window_p)
2361 desired_row->redraw_fringe_bitmaps_p = 1;
2363 /* When a window has disappeared, make sure that no rest of
2364 full-width rows stays visible in the internal border. */
2365 if (windows_or_buffers_changed
2366 && desired_row->full_width_p
2367 && (f = XFRAME (w->frame),
2368 width = FRAME_INTERNAL_BORDER_WIDTH (f),
2370 && (height = desired_row->visible_height,
2373 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2376 ns_clear_frame_area (f, 0, y, width, height);
2377 ns_clear_frame_area (f,
2378 FRAME_PIXEL_WIDTH (f) - width,
2386 ns_shift_glyphs_for_insert (struct frame *f,
2387 int x, int y, int width, int height,
2389 /* --------------------------------------------------------------------------
2390 External (RIF): copy an area horizontally, don't worry about clearing src
2391 -------------------------------------------------------------------------- */
2393 NSRect srcRect = NSMakeRect (x, y, width, height);
2394 NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2396 NSTRACE ("ns_shift_glyphs_for_insert");
2398 ns_copy_bits (f, srcRect, dstRect);
2403 /* ==========================================================================
2405 Character encoding and metrics
2407 ========================================================================== */
2411 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2412 /* --------------------------------------------------------------------------
2413 External (RIF); compute left/right overhang of whole string and set in s
2414 -------------------------------------------------------------------------- */
2416 struct font *font = s->font;
2420 struct font_metrics metrics;
2421 unsigned int codes[2];
2422 codes[0] = *(s->char2b);
2423 codes[1] = *(s->char2b + s->nchars - 1);
2425 font->driver->text_extents (font, codes, 2, &metrics);
2426 s->left_overhang = -metrics.lbearing;
2428 = metrics.rbearing > metrics.width
2429 ? metrics.rbearing - metrics.width : 0;
2433 s->left_overhang = 0;
2434 if (EQ (font->driver->type, Qns))
2435 s->right_overhang = ((struct nsfont_info *)font)->ital ?
2436 FONT_HEIGHT (font) * 0.2 : 0;
2438 s->right_overhang = 0;
2444 /* ==========================================================================
2446 Fringe and cursor drawing
2448 ========================================================================== */
2451 extern int max_used_fringe_bitmap;
2453 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2454 struct draw_fringe_bitmap_params *p)
2455 /* --------------------------------------------------------------------------
2456 External (RIF); fringe-related
2457 -------------------------------------------------------------------------- */
2459 struct frame *f = XFRAME (WINDOW_FRAME (w));
2460 struct face *face = p->face;
2461 static EmacsImage **bimgs = NULL;
2462 static int nBimgs = 0;
2464 /* grow bimgs if needed */
2465 if (nBimgs < max_used_fringe_bitmap)
2467 bimgs = xrealloc (bimgs, max_used_fringe_bitmap * sizeof *bimgs);
2468 memset (bimgs + nBimgs, 0,
2469 (max_used_fringe_bitmap - nBimgs) * sizeof *bimgs);
2470 nBimgs = max_used_fringe_bitmap;
2473 /* Must clip because of partially visible lines. */
2474 ns_clip_to_row (w, row, ANY_AREA, YES);
2478 int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
2480 if (bx >= 0 && nx > 0)
2482 NSRect r = NSMakeRect (bx, by, nx, ny);
2484 [ns_lookup_indexed_color (face->background, f) set];
2491 NSRect r = NSMakeRect (p->x, p->y, p->wd, p->h);
2492 EmacsImage *img = bimgs[p->which - 1];
2496 unsigned short *bits = p->bits + p->dh;
2499 unsigned char *cbits = xmalloc (len);
2501 for (i = 0; i < len; i++)
2502 cbits[i] = ~(bits[i] & 0xff);
2503 img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2505 bimgs[p->which - 1] = img;
2510 /* Since we composite the bitmap instead of just blitting it, we need
2511 to erase the whole background. */
2512 [ns_lookup_indexed_color(face->background, f) set];
2518 bm_color = ns_lookup_indexed_color(face->foreground, f);
2519 else if (p->overlay_p)
2520 bm_color = ns_lookup_indexed_color(face->background, f);
2522 bm_color = f->output_data.ns->cursor_color;
2523 [img setXBMColor: bm_color];
2526 #ifdef NS_IMPL_COCOA
2528 fromRect: NSZeroRect
2529 operation: NSCompositeSourceOver
2535 NSPoint pt = r.origin;
2537 [img compositeToPoint: pt operation: NSCompositeSourceOver];
2546 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2547 int x, int y, enum text_cursor_kinds cursor_type,
2548 int cursor_width, bool on_p, bool active_p)
2549 /* --------------------------------------------------------------------------
2550 External call (RIF): draw cursor.
2551 Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2552 -------------------------------------------------------------------------- */
2555 int fx, fy, h, cursor_height;
2556 struct frame *f = WINDOW_XFRAME (w);
2557 struct glyph *phys_cursor_glyph;
2558 struct glyph *cursor_glyph;
2560 NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2562 /* If cursor is out of bounds, don't draw garbage. This can happen
2563 in mini-buffer windows when switching between echo area glyphs
2566 NSTRACE ("dumpcursor");
2571 w->phys_cursor_type = cursor_type;
2572 w->phys_cursor_on_p = on_p;
2574 if (cursor_type == NO_CURSOR)
2576 w->phys_cursor_width = 0;
2580 if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2582 if (glyph_row->exact_window_width_line_p
2583 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2585 glyph_row->cursor_in_fringe_p = 1;
2586 draw_fringe_bitmap (w, glyph_row, 0);
2591 /* We draw the cursor (with NSRectFill), then draw the glyph on top
2592 (other terminals do it the other way round). We must set
2593 w->phys_cursor_width to the cursor width. For bar cursors, that
2594 is CURSOR_WIDTH; for box cursors, it is the glyph width. */
2595 get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2597 /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2598 to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2599 if (cursor_type == BAR_CURSOR)
2601 if (cursor_width < 1)
2602 cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2603 w->phys_cursor_width = cursor_width;
2605 /* If we have an HBAR, "cursor_width" MAY specify height. */
2606 else if (cursor_type == HBAR_CURSOR)
2608 cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2609 if (cursor_height > glyph_row->height)
2610 cursor_height = glyph_row->height;
2611 if (h > cursor_height) // Cursor smaller than line height, move down
2612 fy += h - cursor_height;
2616 r.origin.x = fx, r.origin.y = fy;
2618 r.size.width = w->phys_cursor_width;
2620 /* TODO: only needed in rare cases with last-resort font in HELLO..
2621 should we do this more efficiently? */
2622 ns_clip_to_row (w, glyph_row, ANY_AREA, NO); /* do ns_focus(f, &r, 1); if remove */
2625 face = FACE_FROM_ID (f, phys_cursor_glyph->face_id);
2626 if (face && NS_FACE_BACKGROUND (face)
2627 == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2629 [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2630 hollow_color = FRAME_CURSOR_COLOR (f);
2633 [FRAME_CURSOR_COLOR (f) set];
2635 #ifdef NS_IMPL_COCOA
2636 /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2637 atomic. Cleaner ways of doing this should be investigated.
2638 One way would be to set a global variable DRAWING_CURSOR
2639 when making the call to draw_phys..(), don't focus in that
2640 case, then move the ns_unfocus() here after that call. */
2641 NSDisableScreenUpdates ();
2644 switch (cursor_type)
2646 case DEFAULT_CURSOR:
2649 case FILLED_BOX_CURSOR:
2652 case HOLLOW_BOX_CURSOR:
2655 NSRectFill (NSInsetRect (r, 1, 1));
2656 [FRAME_CURSOR_COLOR (f) set];
2663 /* If the character under cursor is R2L, draw the bar cursor
2664 on the right of its glyph, rather than on the left. */
2665 cursor_glyph = get_phys_cursor_glyph (w);
2666 if ((cursor_glyph->resolved_level & 1) != 0)
2667 s.origin.x += cursor_glyph->pixel_width - s.size.width;
2674 /* draw the character under the cursor */
2675 if (cursor_type != NO_CURSOR)
2676 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2678 #ifdef NS_IMPL_COCOA
2679 NSEnableScreenUpdates ();
2686 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2687 /* --------------------------------------------------------------------------
2688 External (RIF): Draw a vertical line.
2689 -------------------------------------------------------------------------- */
2691 struct frame *f = XFRAME (WINDOW_FRAME (w));
2693 NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2695 NSTRACE ("ns_draw_vertical_window_border");
2697 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2699 [ns_lookup_indexed_color(face->foreground, f) set];
2701 ns_focus (f, &r, 1);
2708 ns_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
2709 /* --------------------------------------------------------------------------
2710 External (RIF): Draw a window divider.
2711 -------------------------------------------------------------------------- */
2713 struct frame *f = XFRAME (WINDOW_FRAME (w));
2715 NSRect r = NSMakeRect (x0, y0, x1-x0, y1-y0);
2717 NSTRACE ("ns_draw_window_divider");
2719 face = FACE_FROM_ID (f, WINDOW_DIVIDER_FACE_ID);
2721 [ns_lookup_indexed_color(face->foreground, f) set];
2723 ns_focus (f, &r, 1);
2729 ns_show_hourglass (struct frame *f)
2731 /* TODO: add NSProgressIndicator to all frames. */
2735 ns_hide_hourglass (struct frame *f)
2737 /* TODO: remove NSProgressIndicator from all frames. */
2740 /* ==========================================================================
2742 Glyph drawing operations
2744 ========================================================================== */
2747 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2748 /* --------------------------------------------------------------------------
2749 Wrapper utility to account for internal border width on full-width lines,
2750 and allow top full-width rows to hit the frame top. nr should be pointer
2751 to two successive NSRects. Number of rects actually used is returned.
2752 -------------------------------------------------------------------------- */
2754 int n = get_glyph_string_clip_rects (s, nr, 2);
2758 /* --------------------------------------------------------------------
2759 Draw a wavy line under glyph string s. The wave fills wave_height
2766 wave_height = 3 | * * * *
2767 --------------------------------------------------------------------- */
2770 ns_draw_underwave (struct glyph_string *s, EmacsCGFloat width, EmacsCGFloat x)
2772 int wave_height = 3, wave_length = 2;
2773 int y, dx, dy, odd, xmax;
2778 dy = wave_height - 1;
2779 y = s->ybase - wave_height + 3;
2782 /* Find and set clipping rectangle */
2783 waveClip = NSMakeRect (x, y, width, wave_height);
2784 [[NSGraphicsContext currentContext] saveGraphicsState];
2785 NSRectClip (waveClip);
2787 /* Draw the waves */
2788 a.x = x - ((int)(x) % dx) + (EmacsCGFloat) 0.5;
2790 odd = (int)(a.x/dx) % 2;
2791 a.y = b.y = y + 0.5;
2800 [NSBezierPath strokeLineFromPoint:a toPoint:b];
2801 a.x = b.x, a.y = b.y;
2802 b.x += dx, b.y = y + 0.5 + odd*dy;
2806 /* Restore previous clipping rectangle(s) */
2807 [[NSGraphicsContext currentContext] restoreGraphicsState];
2813 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
2814 NSColor *defaultCol, CGFloat width, CGFloat x)
2815 /* --------------------------------------------------------------------------
2816 Draw underline, overline, and strike-through on glyph string s.
2817 -------------------------------------------------------------------------- */
2819 if (s->for_overlaps)
2823 if (face->underline_p)
2825 if (s->face->underline_type == FACE_UNDER_WAVE)
2827 if (face->underline_defaulted_p)
2830 [ns_lookup_indexed_color (face->underline_color, s->f) set];
2832 ns_draw_underwave (s, width, x);
2834 else if (s->face->underline_type == FACE_UNDER_LINE)
2838 unsigned long thickness, position;
2840 /* If the prev was underlined, match its appearance. */
2841 if (s->prev && s->prev->face->underline_p
2842 && s->prev->face->underline_type == FACE_UNDER_LINE
2843 && s->prev->underline_thickness > 0)
2845 thickness = s->prev->underline_thickness;
2846 position = s->prev->underline_position;
2851 unsigned long descent;
2854 descent = s->y + s->height - s->ybase;
2856 /* Use underline thickness of font, defaulting to 1. */
2857 thickness = (font && font->underline_thickness > 0)
2858 ? font->underline_thickness : 1;
2860 /* Determine the offset of underlining from the baseline. */
2861 if (x_underline_at_descent_line)
2862 position = descent - thickness;
2863 else if (x_use_underline_position_properties
2864 && font && font->underline_position >= 0)
2865 position = font->underline_position;
2867 position = lround (font->descent / 2);
2869 position = underline_minimum_offset;
2871 position = max (position, underline_minimum_offset);
2873 /* Ensure underlining is not cropped. */
2874 if (descent <= position)
2876 position = descent - 1;
2879 else if (descent < position + thickness)
2883 s->underline_thickness = thickness;
2884 s->underline_position = position;
2886 r = NSMakeRect (x, s->ybase + position, width, thickness);
2888 if (face->underline_defaulted_p)
2891 [ns_lookup_indexed_color (face->underline_color, s->f) set];
2895 /* Do overline. We follow other terms in using a thickness of 1
2896 and ignoring overline_margin. */
2897 if (face->overline_p)
2900 r = NSMakeRect (x, s->y, width, 1);
2902 if (face->overline_color_defaulted_p)
2905 [ns_lookup_indexed_color (face->overline_color, s->f) set];
2909 /* Do strike-through. We follow other terms for thickness and
2910 vertical position.*/
2911 if (face->strike_through_p)
2916 dy = lrint ((s->height - 1) / 2);
2917 r = NSMakeRect (x, s->y + dy, width, 1);
2919 if (face->strike_through_color_defaulted_p)
2922 [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
2928 ns_draw_box (NSRect r, CGFloat thickness, NSColor *col,
2929 char left_p, char right_p)
2930 /* --------------------------------------------------------------------------
2931 Draw an unfilled rect inside r, optionally leaving left and/or right open.
2932 Note we can't just use an NSDrawRect command, because of the possibility
2933 of some sides not being drawn, and because the rect will be filled.
2934 -------------------------------------------------------------------------- */
2940 s.size.height = thickness;
2942 s.origin.y += r.size.height - thickness;
2945 s.size.height = r.size.height;
2946 s.origin.y = r.origin.y;
2948 /* left, right (optional) */
2949 s.size.width = thickness;
2954 s.origin.x += r.size.width - thickness;
2961 ns_draw_relief (NSRect r, int thickness, char raised_p,
2962 char top_p, char bottom_p, char left_p, char right_p,
2963 struct glyph_string *s)
2964 /* --------------------------------------------------------------------------
2965 Draw a relief rect inside r, optionally leaving some sides open.
2966 Note we can't just use an NSDrawBezel command, because of the possibility
2967 of some sides not being drawn, and because the rect will be filled.
2968 -------------------------------------------------------------------------- */
2970 static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2971 NSColor *newBaseCol = nil;
2974 NSTRACE ("ns_draw_relief");
2978 if (s->face->use_box_color_for_shadows_p)
2980 newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2982 /* else if (s->first_glyph->type == IMAGE_GLYPH
2984 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2986 newBaseCol = IMAGE_BACKGROUND (s->img, s->f, 0);
2990 newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2993 if (newBaseCol == nil)
2994 newBaseCol = [NSColor grayColor];
2996 if (newBaseCol != baseCol) /* TODO: better check */
2999 baseCol = [newBaseCol retain];
3001 lightCol = [[baseCol highlightWithLevel: 0.2] retain];
3003 darkCol = [[baseCol shadowWithLevel: 0.3] retain];
3006 [(raised_p ? lightCol : darkCol) set];
3008 /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
3011 sr.size.height = thickness;
3012 if (top_p) NSRectFill (sr);
3015 sr.size.height = r.size.height;
3016 sr.size.width = thickness;
3017 if (left_p) NSRectFill (sr);
3019 [(raised_p ? darkCol : lightCol) set];
3022 sr.size.width = r.size.width;
3023 sr.size.height = thickness;
3024 sr.origin.y += r.size.height - thickness;
3025 if (bottom_p) NSRectFill (sr);
3028 sr.size.height = r.size.height;
3029 sr.origin.y = r.origin.y;
3030 sr.size.width = thickness;
3031 sr.origin.x += r.size.width - thickness;
3032 if (right_p) NSRectFill (sr);
3037 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
3038 /* --------------------------------------------------------------------------
3039 Function modeled after x_draw_glyph_string_box ().
3040 Sets up parameters for drawing.
3041 -------------------------------------------------------------------------- */
3043 int right_x, last_x;
3044 char left_p, right_p;
3045 struct glyph *last_glyph;
3050 if (s->hl == DRAW_MOUSE_FACE)
3052 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3054 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3059 thickness = face->box_line_width;
3061 NSTRACE ("ns_dumpglyphs_box_or_relief");
3063 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
3064 ? WINDOW_RIGHT_EDGE_X (s->w)
3065 : window_box_right (s->w, s->area));
3066 last_glyph = (s->cmp || s->img
3067 ? s->first_glyph : s->first_glyph + s->nchars-1);
3069 right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
3070 ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
3072 left_p = (s->first_glyph->left_box_line_p
3073 || (s->hl == DRAW_MOUSE_FACE
3074 && (s->prev == NULL || s->prev->hl != s->hl)));
3075 right_p = (last_glyph->right_box_line_p
3076 || (s->hl == DRAW_MOUSE_FACE
3077 && (s->next == NULL || s->next->hl != s->hl)));
3079 r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
3081 /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
3082 if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
3084 ns_draw_box (r, abs (thickness),
3085 ns_lookup_indexed_color (face->box_color, s->f),
3090 ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
3091 1, 1, left_p, right_p, s);
3097 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
3098 /* --------------------------------------------------------------------------
3099 Modeled after x_draw_glyph_string_background, which draws BG in
3100 certain cases. Others are left to the text rendering routine.
3101 -------------------------------------------------------------------------- */
3103 NSTRACE ("ns_maybe_dumpglyphs_background");
3105 if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
3107 int box_line_width = max (s->face->box_line_width, 0);
3108 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
3109 /* When xdisp.c ignores FONT_HEIGHT, we cannot trust font
3110 dimensions, since the actual glyphs might be much
3111 smaller. So in that case we always clear the rectangle
3112 with background color. */
3113 || FONT_TOO_HIGH (s->font)
3114 || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
3117 if (s->hl == DRAW_MOUSE_FACE)
3119 face = FACE_FROM_ID (s->f,
3120 MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3122 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3125 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3127 [(NS_FACE_BACKGROUND (face) != 0
3128 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
3129 : FRAME_BACKGROUND_COLOR (s->f)) set];
3132 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (s->f);
3133 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
3136 if (s->hl != DRAW_CURSOR)
3138 NSRect r = NSMakeRect (s->x, s->y + box_line_width,
3139 s->background_width,
3140 s->height-2*box_line_width);
3144 s->background_filled_p = 1;
3151 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
3152 /* --------------------------------------------------------------------------
3153 Renders an image and associated borders.
3154 -------------------------------------------------------------------------- */
3156 EmacsImage *img = s->img->pixmap;
3157 int box_line_vwidth = max (s->face->box_line_width, 0);
3158 int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3159 int bg_x, bg_y, bg_height;
3166 NSTRACE ("ns_dumpglyphs_image");
3168 if (s->face->box != FACE_NO_BOX
3169 && s->first_glyph->left_box_line_p && s->slice.x == 0)
3170 x += abs (s->face->box_line_width);
3173 bg_y = s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
3174 bg_height = s->height;
3175 /* other terms have this, but was causing problems w/tabbar mode */
3176 /* - 2 * box_line_vwidth; */
3178 if (s->slice.x == 0) x += s->img->hmargin;
3179 if (s->slice.y == 0) y += s->img->vmargin;
3181 /* Draw BG: if we need larger area than image itself cleared, do that,
3182 otherwise, since we composite the image under NS (instead of mucking
3183 with its background color), we must clear just the image area. */
3184 if (s->hl == DRAW_MOUSE_FACE)
3186 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3188 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3191 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3193 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
3195 if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
3196 || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
3198 br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
3199 s->background_filled_p = 1;
3203 br = NSMakeRect (x, y, s->slice.width, s->slice.height);
3208 /* Draw the image.. do we need to draw placeholder if img ==nil? */
3211 #ifdef NS_IMPL_COCOA
3212 NSRect dr = NSMakeRect (x, y, s->slice.width, s->slice.height);
3213 NSRect ir = NSMakeRect (s->slice.x, s->slice.y,
3214 s->slice.width, s->slice.height);
3217 operation: NSCompositeSourceOver
3222 [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3223 operation: NSCompositeSourceOver];
3227 if (s->hl == DRAW_CURSOR)
3229 [FRAME_CURSOR_COLOR (s->f) set];
3230 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3231 tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3233 /* Currently on NS img->mask is always 0. Since
3234 get_window_cursor_type specifies a hollow box cursor when on
3235 a non-masked image we never reach this clause. But we put it
3236 in in anticipation of better support for image masks on
3238 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3242 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3245 /* Draw underline, overline, strike-through. */
3246 ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3248 /* Draw relief, if requested */
3249 if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3251 if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3253 th = tool_bar_button_relief >= 0 ?
3254 tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3255 raised_p = (s->hl == DRAW_IMAGE_RAISED);
3259 th = abs (s->img->relief);
3260 raised_p = (s->img->relief > 0);
3263 r.origin.x = x - th;
3264 r.origin.y = y - th;
3265 r.size.width = s->slice.width + 2*th-1;
3266 r.size.height = s->slice.height + 2*th-1;
3267 ns_draw_relief (r, th, raised_p,
3269 s->slice.y + s->slice.height == s->img->height,
3271 s->slice.x + s->slice.width == s->img->width, s);
3274 /* If there is no mask, the background won't be seen,
3275 so draw a rectangle on the image for the cursor.
3276 Do this for all images, getting transparency right is not reliable. */
3277 if (s->hl == DRAW_CURSOR)
3279 int thickness = abs (s->img->relief);
3280 if (thickness == 0) thickness = 1;
3281 ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3287 ns_dumpglyphs_stretch (struct glyph_string *s)
3292 NSColor *fgCol, *bgCol;
3294 if (!s->background_filled_p)
3296 n = ns_get_glyph_string_clip_rect (s, r);
3297 *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3299 ns_focus (s->f, r, n);
3301 if (s->hl == DRAW_MOUSE_FACE)
3303 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3305 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3308 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3310 bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3311 fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3313 for (i = 0; i < n; ++i)
3315 if (!s->row->full_width_p)
3317 int overrun, leftoverrun;
3319 /* truncate to avoid overwriting fringe and/or scrollbar */
3320 overrun = max (0, (s->x + s->background_width)
3321 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3322 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3323 r[i].size.width -= overrun;
3325 /* truncate to avoid overwriting to left of the window box */
3326 leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3327 + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3329 if (leftoverrun > 0)
3331 r[i].origin.x += leftoverrun;
3332 r[i].size.width -= leftoverrun;
3335 /* XXX: Try to work between problem where a stretch glyph on
3336 a partially-visible bottom row will clear part of the
3337 modeline, and another where list-buffers headers and similar
3338 rows erroneously have visible_height set to 0. Not sure
3339 where this is coming from as other terms seem not to show. */
3340 r[i].size.height = min (s->height, s->row->visible_height);
3345 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3346 overwriting cursor (usually when cursor on a tab) */
3347 if (s->hl == DRAW_CURSOR)
3352 width = s->w->phys_cursor_width;
3353 r[i].size.width -= width;
3354 r[i].origin.x += width;
3358 /* Draw overlining, etc. on the cursor. */
3359 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3360 ns_draw_text_decoration (s, face, bgCol, width, x);
3362 ns_draw_text_decoration (s, face, fgCol, width, x);
3369 /* Draw overlining, etc. on the stretch glyph (or the part
3370 of the stretch glyph after the cursor). */
3371 ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3375 s->background_filled_p = 1;
3381 ns_draw_composite_glyph_string_foreground (struct glyph_string *s)
3384 struct font *font = s->font;
3386 /* If first glyph of S has a left box line, start drawing the text
3387 of S to the right of that box line. */
3388 if (s->face && s->face->box != FACE_NO_BOX
3389 && s->first_glyph->left_box_line_p)
3390 x = s->x + eabs (s->face->box_line_width);
3394 /* S is a glyph string for a composition. S->cmp_from is the index
3395 of the first character drawn for glyphs of this composition.
3396 S->cmp_from == 0 means we are drawing the very first character of
3397 this composition. */
3399 /* Draw a rectangle for the composition if the font for the very
3400 first character of the composition could not be loaded. */
3401 if (s->font_not_found_p)
3403 if (s->cmp_from == 0)
3405 NSRect r = NSMakeRect (s->x, s->y, s->width-1, s->height -1);
3406 ns_draw_box (r, 1, FRAME_CURSOR_COLOR (s->f), 1, 1);
3409 else if (! s->first_glyph->u.cmp.automatic)
3413 for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
3414 /* TAB in a composition means display glyphs with padding
3415 space on the left or right. */
3416 if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
3418 int xx = x + s->cmp->offsets[j * 2];
3419 int yy = y - s->cmp->offsets[j * 2 + 1];
3421 font->driver->draw (s, j, j + 1, xx, yy, false);
3422 if (s->face->overstrike)
3423 font->driver->draw (s, j, j + 1, xx + 1, yy, false);
3428 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
3433 for (i = j = s->cmp_from; i < s->cmp_to; i++)
3435 glyph = LGSTRING_GLYPH (gstring, i);
3436 if (NILP (LGLYPH_ADJUSTMENT (glyph)))
3437 width += LGLYPH_WIDTH (glyph);
3440 int xoff, yoff, wadjust;
3444 font->driver->draw (s, j, i, x, y, false);
3445 if (s->face->overstrike)
3446 font->driver->draw (s, j, i, x + 1, y, false);
3449 xoff = LGLYPH_XOFF (glyph);
3450 yoff = LGLYPH_YOFF (glyph);
3451 wadjust = LGLYPH_WADJUST (glyph);
3452 font->driver->draw (s, i, i + 1, x + xoff, y + yoff, false);
3453 if (s->face->overstrike)
3454 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff,
3463 font->driver->draw (s, j, i, x, y, false);
3464 if (s->face->overstrike)
3465 font->driver->draw (s, j, i, x + 1, y, false);
3471 ns_draw_glyph_string (struct glyph_string *s)
3472 /* --------------------------------------------------------------------------
3473 External (RIF): Main draw-text call.
3474 -------------------------------------------------------------------------- */
3476 /* TODO (optimize): focus for box and contents draw */
3479 char box_drawn_p = 0;
3480 struct font *font = s->face->font;
3481 if (! font) font = FRAME_FONT (s->f);
3483 NSTRACE ("ns_draw_glyph_string");
3485 if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3488 struct glyph_string *next;
3490 for (width = 0, next = s->next;
3491 next && width < s->right_overhang;
3492 width += next->width, next = next->next)
3493 if (next->first_glyph->type != IMAGE_GLYPH)
3495 if (next->first_glyph->type != STRETCH_GLYPH)
3497 n = ns_get_glyph_string_clip_rect (s->next, r);
3498 ns_focus (s->f, r, n);
3499 ns_maybe_dumpglyphs_background (s->next, 1);
3504 ns_dumpglyphs_stretch (s->next);
3506 next->num_clips = 0;
3510 if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3511 && (s->first_glyph->type == CHAR_GLYPH
3512 || s->first_glyph->type == COMPOSITE_GLYPH))
3514 n = ns_get_glyph_string_clip_rect (s, r);
3515 ns_focus (s->f, r, n);
3516 ns_maybe_dumpglyphs_background (s, 1);
3517 ns_dumpglyphs_box_or_relief (s);
3522 switch (s->first_glyph->type)
3526 n = ns_get_glyph_string_clip_rect (s, r);
3527 ns_focus (s->f, r, n);
3528 ns_dumpglyphs_image (s, r[0]);
3533 ns_dumpglyphs_stretch (s);
3537 case COMPOSITE_GLYPH:
3538 n = ns_get_glyph_string_clip_rect (s, r);
3539 ns_focus (s->f, r, n);
3541 if (s->for_overlaps || (s->cmp_from > 0
3542 && ! s->first_glyph->u.cmp.automatic))
3543 s->background_filled_p = 1;
3545 ns_maybe_dumpglyphs_background
3546 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3548 flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3549 (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3550 (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3551 NS_DUMPGLYPH_NORMAL));
3553 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3555 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3556 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3557 NS_FACE_FOREGROUND (s->face) = tmp;
3561 BOOL isComposite = s->first_glyph->type == COMPOSITE_GLYPH;
3564 ns_draw_composite_glyph_string_foreground (s);
3567 (s, s->cmp_from, s->nchars, s->x, s->ybase,
3568 (flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3569 || flags == NS_DUMPGLYPH_MOUSEFACE);
3573 NSColor *col = (NS_FACE_FOREGROUND (s->face) != 0
3574 ? ns_lookup_indexed_color (NS_FACE_FOREGROUND (s->face),
3576 : FRAME_FOREGROUND_COLOR (s->f));
3579 /* Draw underline, overline, strike-through. */
3580 ns_draw_text_decoration (s, s->face, col, s->width, s->x);
3583 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3585 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3586 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3587 NS_FACE_FOREGROUND (s->face) = tmp;
3593 case GLYPHLESS_GLYPH:
3594 n = ns_get_glyph_string_clip_rect (s, r);
3595 ns_focus (s->f, r, n);
3597 if (s->for_overlaps || (s->cmp_from > 0
3598 && ! s->first_glyph->u.cmp.automatic))
3599 s->background_filled_p = 1;
3601 ns_maybe_dumpglyphs_background
3602 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3604 /* Not yet implemented. */
3613 /* Draw box if not done already. */
3614 if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3616 n = ns_get_glyph_string_clip_rect (s, r);
3617 ns_focus (s->f, r, n);
3618 ns_dumpglyphs_box_or_relief (s);
3627 /* ==========================================================================
3631 ========================================================================== */
3635 ns_send_appdefined (int value)
3636 /* --------------------------------------------------------------------------
3637 Internal: post an appdefined event which EmacsApp-sendEvent will
3638 recognize and take as a command to halt the event loop.
3639 -------------------------------------------------------------------------- */
3641 NSTRACE ("ns_send_appdefined");
3643 #ifdef NS_IMPL_GNUSTEP
3644 // GNUstep needs postEvent to happen on the main thread.
3645 if (! [[NSThread currentThread] isMainThread])
3647 EmacsApp *app = (EmacsApp *)NSApp;
3648 app->nextappdefined = value;
3649 [app performSelectorOnMainThread:@selector (sendFromMainThread:)
3656 /* Only post this event if we haven't already posted one. This will end
3657 the [NXApp run] main loop after having processed all events queued at
3660 #ifdef NS_IMPL_COCOA
3661 if (! send_appdefined)
3663 /* OSX 10.10.1 swallows the AppDefined event we are sending ourselves
3664 in certain situations (rapid incoming events).
3665 So check if we have one, if not add one. */
3666 NSEvent *appev = [NSApp nextEventMatchingMask:NSApplicationDefinedMask
3667 untilDate:[NSDate distantPast]
3668 inMode:NSDefaultRunLoopMode
3670 if (! appev) send_appdefined = YES;
3674 if (send_appdefined)
3678 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
3679 send_appdefined = NO;
3681 /* Don't need wakeup timer any more */
3684 [timed_entry invalidate];
3685 [timed_entry release];
3689 nxev = [NSEvent otherEventWithType: NSApplicationDefined
3690 location: NSMakePoint (0, 0)
3693 windowNumber: [[NSApp mainWindow] windowNumber]
3694 context: [NSApp context]
3699 /* Post an application defined event on the event queue. When this is
3700 received the [NXApp run] will return, thus having processed all
3701 events which are currently queued. */
3702 [NSApp postEvent: nxev atStart: NO];
3706 #ifdef HAVE_NATIVE_FS
3710 Lisp_Object frame, tail;
3712 if (ns_last_use_native_fullscreen == ns_use_native_fullscreen)
3715 ns_last_use_native_fullscreen = ns_use_native_fullscreen;
3717 FOR_EACH_FRAME (tail, frame)
3719 struct frame *f = XFRAME (frame);
3722 EmacsView *view = FRAME_NS_VIEW (f);
3723 [view updateCollectionBehavior];
3729 /* GNUstep does not have cancelTracking. */
3730 #ifdef NS_IMPL_COCOA
3731 /* Check if menu open should be canceled or continued as normal. */
3733 ns_check_menu_open (NSMenu *menu)
3735 /* Click in menu bar? */
3736 NSArray *a = [[NSApp mainMenu] itemArray];
3740 if (menu == nil) // Menu tracking ended.
3742 if (menu_will_open_state == MENU_OPENING)
3743 menu_will_open_state = MENU_NONE;
3747 for (i = 0; ! found && i < [a count]; i++)
3748 found = menu == [[a objectAtIndex:i] submenu];
3751 if (menu_will_open_state == MENU_NONE && emacs_event)
3753 NSEvent *theEvent = [NSApp currentEvent];
3754 struct frame *emacsframe = SELECTED_FRAME ();
3756 [menu cancelTracking];
3757 menu_will_open_state = MENU_PENDING;
3758 emacs_event->kind = MENU_BAR_ACTIVATE_EVENT;
3759 EV_TRAILER (theEvent);
3761 CGEventRef ourEvent = CGEventCreate (NULL);
3762 menu_mouse_point = CGEventGetLocation (ourEvent);
3763 CFRelease (ourEvent);
3765 else if (menu_will_open_state == MENU_OPENING)
3767 menu_will_open_state = MENU_NONE;
3772 /* Redo saved menu click if state is MENU_PENDING. */
3774 ns_check_pending_open_menu ()
3776 if (menu_will_open_state == MENU_PENDING)
3778 CGEventSourceRef source
3779 = CGEventSourceCreate (kCGEventSourceStateHIDSystemState);
3781 CGEventRef event = CGEventCreateMouseEvent (source,
3782 kCGEventLeftMouseDown,
3784 kCGMouseButtonLeft);
3785 CGEventSetType (event, kCGEventLeftMouseDown);
3786 CGEventPost (kCGHIDEventTap, event);
3790 menu_will_open_state = MENU_OPENING;
3793 #endif /* NS_IMPL_COCOA */
3796 unwind_apploopnr (Lisp_Object not_used)
3799 n_emacs_events_pending = 0;
3800 ns_finish_events ();
3805 ns_read_socket (struct terminal *terminal, struct input_event *hold_quit)
3806 /* --------------------------------------------------------------------------
3807 External (hook): Post an event to ourself and keep reading events until
3808 we read it back again. In effect process all events which were waiting.
3809 From 21+ we have to manage the event buffer ourselves.
3810 -------------------------------------------------------------------------- */
3812 struct input_event ev;
3815 /* NSTRACE ("ns_read_socket"); */
3817 #ifdef HAVE_NATIVE_FS
3821 if ([NSApp modalWindow] != nil)
3824 if (hold_event_q.nr > 0)
3827 for (i = 0; i < hold_event_q.nr; ++i)
3828 kbd_buffer_store_event_hold (&hold_event_q.q[i], hold_quit);
3829 hold_event_q.nr = 0;
3834 n_emacs_events_pending = 0;
3835 ns_init_events (&ev);
3836 q_event_ptr = hold_quit;
3838 /* we manage autorelease pools by allocate/reallocate each time around
3839 the loop; strict nesting is occasionally violated but seems not to
3840 matter.. earlier methods using full nesting caused major memory leaks */
3841 [outerpool release];
3842 outerpool = [[NSAutoreleasePool alloc] init];
3844 /* If have pending open-file requests, attend to the next one of those. */
3845 if (ns_pending_files && [ns_pending_files count] != 0
3846 && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3848 [ns_pending_files removeObjectAtIndex: 0];
3850 /* Deal with pending service requests. */
3851 else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3853 NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3854 withArg: [ns_pending_service_args objectAtIndex: 0]])
3856 [ns_pending_service_names removeObjectAtIndex: 0];
3857 [ns_pending_service_args removeObjectAtIndex: 0];
3861 ptrdiff_t specpdl_count = SPECPDL_INDEX ();
3862 /* Run and wait for events. We must always send one NX_APPDEFINED event
3863 to ourself, otherwise [NXApp run] will never exit. */
3864 send_appdefined = YES;
3865 ns_send_appdefined (-1);
3867 if (++apploopnr != 1)
3871 record_unwind_protect (unwind_apploopnr, Qt);
3873 unbind_to (specpdl_count, Qnil); /* calls unwind_apploopnr */
3876 nevents = n_emacs_events_pending;
3877 n_emacs_events_pending = 0;
3878 ns_finish_events ();
3887 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3888 fd_set *exceptfds, struct timespec const *timeout,
3889 sigset_t const *sigmask)
3890 /* --------------------------------------------------------------------------
3891 Replacement for select, checking for events
3892 -------------------------------------------------------------------------- */
3896 struct input_event event;
3899 /* NSTRACE ("ns_select"); */
3901 #ifdef HAVE_NATIVE_FS
3905 if (hold_event_q.nr > 0)
3907 /* We already have events pending. */
3913 for (k = 0; k < nfds+1; k++)
3915 if (readfds && FD_ISSET(k, readfds)) ++nr;
3916 if (writefds && FD_ISSET(k, writefds)) ++nr;
3920 || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0))
3921 return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
3923 [outerpool release];
3924 outerpool = [[NSAutoreleasePool alloc] init];
3927 send_appdefined = YES;
3930 pthread_mutex_lock (&select_mutex);
3935 select_readfds = *readfds;
3936 select_valid += SELECT_HAVE_READ;
3940 select_writefds = *writefds;
3941 select_valid += SELECT_HAVE_WRITE;
3946 select_timeout = *timeout;
3947 select_valid += SELECT_HAVE_TMO;
3950 pthread_mutex_unlock (&select_mutex);
3952 /* Inform fd_handler that select should be called */
3954 emacs_write_sig (selfds[1], &c, 1);
3956 else if (nr == 0 && timeout)
3958 /* No file descriptor, just a timeout, no need to wake fd_handler */
3959 double time = timespectod (*timeout);
3960 timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3963 @selector (timeout_handler:)
3968 else /* No timeout and no file descriptors, can this happen? */
3970 /* Send appdefined so we exit from the loop */
3971 ns_send_appdefined (-1);
3975 ns_init_events (&event);
3976 if (++apploopnr != 1)
3982 ptrdiff_t specpdl_count = SPECPDL_INDEX ();
3983 record_unwind_protect (unwind_apploopnr, Qt);
3985 unbind_to (specpdl_count, Qnil); /* calls unwind_apploopnr */
3988 ns_finish_events ();
3989 if (nr > 0 && readfds)
3992 emacs_write_sig (selfds[1], &c, 1);
3996 t = last_appdefined_event_data;
3998 if (t != NO_APPDEFINED_DATA)
4000 last_appdefined_event_data = NO_APPDEFINED_DATA;
4004 /* The NX_APPDEFINED event we received was a timeout. */
4009 /* The NX_APPDEFINED event we received was the result of
4010 at least one real input event arriving. */
4016 /* Received back from select () in fd_handler; copy the results */
4017 pthread_mutex_lock (&select_mutex);
4018 if (readfds) *readfds = select_readfds;
4019 if (writefds) *writefds = select_writefds;
4020 pthread_mutex_unlock (&select_mutex);
4035 /* ==========================================================================
4039 ========================================================================== */
4043 ns_set_vertical_scroll_bar (struct window *window,
4044 int portion, int whole, int position)
4045 /* --------------------------------------------------------------------------
4046 External (hook): Update or add scrollbar
4047 -------------------------------------------------------------------------- */
4051 struct frame *f = XFRAME (WINDOW_FRAME (window));
4052 EmacsView *view = FRAME_NS_VIEW (f);
4054 int window_y, window_height;
4055 int top, left, height, width;
4056 BOOL update_p = YES;
4058 /* optimization; display engine sends WAY too many of these.. */
4059 if (!NILP (window->vertical_scroll_bar))
4061 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4062 if ([bar checkSamePosition: position portion: portion whole: whole])
4064 if (view->scrollbarsNeedingUpdate == 0)
4066 if (!windows_or_buffers_changed)
4070 view->scrollbarsNeedingUpdate--;
4075 NSTRACE ("ns_set_vertical_scroll_bar");
4077 /* Get dimensions. */
4078 window_box (window, ANY_AREA, 0, &window_y, 0, &window_height);
4080 height = window_height;
4081 width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
4082 left = WINDOW_SCROLL_BAR_AREA_X (window);
4084 r = NSMakeRect (left, top, width, height);
4085 /* the parent view is flipped, so we need to flip y value */
4087 r.origin.y = (v.size.height - r.size.height - r.origin.y);
4089 XSETWINDOW (win, window);
4092 /* we want at least 5 lines to display a scrollbar */
4093 if (WINDOW_TOTAL_LINES (window) < 5)
4095 if (!NILP (window->vertical_scroll_bar))
4097 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4098 [bar removeFromSuperview];
4099 wset_vertical_scroll_bar (window, Qnil);
4102 ns_clear_frame_area (f, left, top, width, height);
4107 if (NILP (window->vertical_scroll_bar))
4109 if (width > 0 && height > 0)
4110 ns_clear_frame_area (f, left, top, width, height);
4112 bar = [[EmacsScroller alloc] initFrame: r window: win];
4113 wset_vertical_scroll_bar (window, make_save_ptr (bar));
4119 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4120 oldRect = [bar frame];
4121 r.size.width = oldRect.size.width;
4122 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4124 if (oldRect.origin.x != r.origin.x)
4125 ns_clear_frame_area (f, left, top, width, height);
4131 [bar setPosition: position portion: portion whole: whole];
4137 ns_set_horizontal_scroll_bar (struct window *window,
4138 int portion, int whole, int position)
4139 /* --------------------------------------------------------------------------
4140 External (hook): Update or add scrollbar
4141 -------------------------------------------------------------------------- */
4145 struct frame *f = XFRAME (WINDOW_FRAME (window));
4146 EmacsView *view = FRAME_NS_VIEW (f);
4148 int top, height, left, width;
4149 int window_x, window_width;
4150 BOOL update_p = YES;
4152 /* optimization; display engine sends WAY too many of these.. */
4153 if (!NILP (window->horizontal_scroll_bar))
4155 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4156 if ([bar checkSamePosition: position portion: portion whole: whole])
4158 if (view->scrollbarsNeedingUpdate == 0)
4160 if (!windows_or_buffers_changed)
4164 view->scrollbarsNeedingUpdate--;
4169 NSTRACE ("ns_set_horizontal_scroll_bar");
4171 /* Get dimensions. */
4172 window_box (window, ANY_AREA, 0, &window_x, &window_width, 0);
4174 width = window_width;
4175 height = WINDOW_CONFIG_SCROLL_BAR_LINES (window) * FRAME_LINE_HEIGHT (f);
4176 top = WINDOW_SCROLL_BAR_AREA_Y (window);
4178 r = NSMakeRect (left, top, width, height);
4179 /* the parent view is flipped, so we need to flip y value */
4181 /* ??????? PXW/scrollbars !!!!!!!!!!!!!!!!!!!! */
4182 r.origin.y = (v.size.height - r.size.height - r.origin.y);
4184 XSETWINDOW (win, window);
4187 if (WINDOW_TOTAL_COLS (window) < 5)
4189 if (!NILP (window->horizontal_scroll_bar))
4191 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4192 [bar removeFromSuperview];
4193 wset_horizontal_scroll_bar (window, Qnil);
4195 ns_clear_frame_area (f, left, top, width, height);
4200 if (NILP (window->horizontal_scroll_bar))
4202 if (width > 0 && height > 0)
4203 ns_clear_frame_area (f, left, top, width, height);
4205 bar = [[EmacsScroller alloc] initFrame: r window: win];
4206 wset_horizontal_scroll_bar (window, make_save_ptr (bar));
4212 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4213 oldRect = [bar frame];
4214 r.size.width = oldRect.size.width;
4215 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4217 if (oldRect.origin.x != r.origin.x)
4218 ns_clear_frame_area (f, left, top, width, height);
4225 [bar setPosition: position portion: portion whole: whole];
4231 ns_condemn_scroll_bars (struct frame *f)
4232 /* --------------------------------------------------------------------------
4233 External (hook): arrange for all frame's scrollbars to be removed
4234 at next call to judge_scroll_bars, except for those redeemed.
4235 -------------------------------------------------------------------------- */
4239 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
4241 NSTRACE ("ns_condemn_scroll_bars");
4243 for (i =[subviews count]-1; i >= 0; i--)
4245 view = [subviews objectAtIndex: i];
4246 if ([view isKindOfClass: [EmacsScroller class]])
4253 ns_redeem_scroll_bar (struct window *window)
4254 /* --------------------------------------------------------------------------
4255 External (hook): arrange to spare this window's scrollbar
4256 at next call to judge_scroll_bars.
4257 -------------------------------------------------------------------------- */
4260 NSTRACE ("ns_redeem_scroll_bar");
4261 if (!NILP (window->vertical_scroll_bar))
4263 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4267 if (!NILP (window->horizontal_scroll_bar))
4269 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4276 ns_judge_scroll_bars (struct frame *f)
4277 /* --------------------------------------------------------------------------
4278 External (hook): destroy all scrollbars on frame that weren't
4279 redeemed after call to condemn_scroll_bars.
4280 -------------------------------------------------------------------------- */
4284 EmacsView *eview = FRAME_NS_VIEW (f);
4285 NSArray *subviews = [[eview superview] subviews];
4288 NSTRACE ("ns_judge_scroll_bars");
4289 for (i = [subviews count]-1; i >= 0; --i)
4291 view = [subviews objectAtIndex: i];
4292 if (![view isKindOfClass: [EmacsScroller class]]) continue;
4298 [eview updateFrameSize: NO];
4301 /* ==========================================================================
4305 ========================================================================== */
4308 x_display_pixel_height (struct ns_display_info *dpyinfo)
4310 NSArray *screens = [NSScreen screens];
4311 NSEnumerator *enumerator = [screens objectEnumerator];
4316 while ((screen = [enumerator nextObject]) != nil)
4317 frame = NSUnionRect (frame, [screen frame]);
4319 return NSHeight (frame);
4323 x_display_pixel_width (struct ns_display_info *dpyinfo)
4325 NSArray *screens = [NSScreen screens];
4326 NSEnumerator *enumerator = [screens objectEnumerator];
4331 while ((screen = [enumerator nextObject]) != nil)
4332 frame = NSUnionRect (frame, [screen frame]);
4334 return NSWidth (frame);
4338 static Lisp_Object ns_string_to_lispmod (const char *s)
4339 /* --------------------------------------------------------------------------
4340 Convert modifier name to lisp symbol
4341 -------------------------------------------------------------------------- */
4343 if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
4345 else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
4347 else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
4349 else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
4351 else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
4353 else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
4361 ns_default (const char *parameter, Lisp_Object *result,
4362 Lisp_Object yesval, Lisp_Object noval,
4363 BOOL is_float, BOOL is_modstring)
4364 /* --------------------------------------------------------------------------
4365 Check a parameter value in user's preferences
4366 -------------------------------------------------------------------------- */
4368 const char *value = ns_get_defaults_value (parameter);
4374 if (c_strcasecmp (value, "YES") == 0)
4376 else if (c_strcasecmp (value, "NO") == 0)
4378 else if (is_float && (f = strtod (value, &pos), pos != value))
4379 *result = make_float (f);
4380 else if (is_modstring && value)
4381 *result = ns_string_to_lispmod (value);
4382 else fprintf (stderr,
4383 "Bad value for default \"%s\": \"%s\"\n", parameter, value);
4389 ns_initialize_display_info (struct ns_display_info *dpyinfo)
4390 /* --------------------------------------------------------------------------
4391 Initialize global info and storage for display.
4392 -------------------------------------------------------------------------- */
4394 NSScreen *screen = [NSScreen mainScreen];
4395 NSWindowDepth depth = [screen depth];
4397 dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
4398 dpyinfo->resy = 72.27;
4399 dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
4400 NSColorSpaceFromDepth (depth)]
4401 && ![NSCalibratedWhiteColorSpace isEqualToString:
4402 NSColorSpaceFromDepth (depth)];
4403 dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
4404 dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
4405 dpyinfo->color_table->colors = NULL;
4406 dpyinfo->root_window = 42; /* a placeholder.. */
4407 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
4408 dpyinfo->n_fonts = 0;
4409 dpyinfo->smallest_font_height = 1;
4410 dpyinfo->smallest_char_width = 1;
4412 reset_mouse_highlight (&dpyinfo->mouse_highlight);
4416 /* This and next define (many of the) public functions in this file. */
4417 /* x_... are generic versions in xdisp.c that we, and other terms, get away
4418 with using despite presence in the "system dependent" redisplay
4419 interface. In addition, many of the ns_ methods have code that is
4420 shared with all terms, indicating need for further refactoring. */
4421 extern frame_parm_handler ns_frame_parm_handlers[];
4422 static struct redisplay_interface ns_redisplay_interface =
4424 ns_frame_parm_handlers,
4428 x_clear_end_of_line,
4430 ns_after_update_window_line,
4431 ns_update_window_begin,
4432 ns_update_window_end,
4433 0, /* flush_display */
4434 x_clear_window_mouse_face,
4435 x_get_glyph_overhangs,
4436 x_fix_overlapping_area,
4437 ns_draw_fringe_bitmap,
4438 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
4439 0, /* destroy_fringe_bitmap */
4440 ns_compute_glyph_string_overhangs,
4441 ns_draw_glyph_string,
4442 ns_define_frame_cursor,
4443 ns_clear_frame_area,
4444 ns_draw_window_cursor,
4445 ns_draw_vertical_window_border,
4446 ns_draw_window_divider,
4447 ns_shift_glyphs_for_insert,
4454 ns_delete_display (struct ns_display_info *dpyinfo)
4460 /* This function is called when the last frame on a display is deleted. */
4462 ns_delete_terminal (struct terminal *terminal)
4464 struct ns_display_info *dpyinfo = terminal->display_info.ns;
4466 NSTRACE ("ns_delete_terminal");
4468 /* Protect against recursive calls. delete_frame in
4469 delete_terminal calls us back when it deletes our last frame. */
4470 if (!terminal->name)
4475 x_destroy_all_bitmaps (dpyinfo);
4476 ns_delete_display (dpyinfo);
4481 static struct terminal *
4482 ns_create_terminal (struct ns_display_info *dpyinfo)
4483 /* --------------------------------------------------------------------------
4484 Set up use of NS before we make the first connection.
4485 -------------------------------------------------------------------------- */
4487 struct terminal *terminal;
4489 NSTRACE ("ns_create_terminal");
4491 terminal = create_terminal (output_ns, &ns_redisplay_interface);
4493 terminal->display_info.ns = dpyinfo;
4494 dpyinfo->terminal = terminal;
4496 terminal->clear_frame_hook = ns_clear_frame;
4497 terminal->ring_bell_hook = ns_ring_bell;
4498 terminal->update_begin_hook = ns_update_begin;
4499 terminal->update_end_hook = ns_update_end;
4500 terminal->read_socket_hook = ns_read_socket;
4501 terminal->frame_up_to_date_hook = ns_frame_up_to_date;
4502 terminal->mouse_position_hook = ns_mouse_position;
4503 terminal->frame_rehighlight_hook = ns_frame_rehighlight;
4504 terminal->frame_raise_lower_hook = ns_frame_raise_lower;
4505 terminal->fullscreen_hook = ns_fullscreen_hook;
4506 terminal->menu_show_hook = ns_menu_show;
4507 terminal->popup_dialog_hook = ns_popup_dialog;
4508 terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
4509 terminal->set_horizontal_scroll_bar_hook = ns_set_horizontal_scroll_bar;
4510 terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
4511 terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
4512 terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
4513 terminal->delete_frame_hook = x_destroy_window;
4514 terminal->delete_terminal_hook = ns_delete_terminal;
4515 /* Other hooks are NULL by default. */
4521 struct ns_display_info *
4522 ns_term_init (Lisp_Object display_name)
4523 /* --------------------------------------------------------------------------
4524 Start the Application and get things rolling.
4525 -------------------------------------------------------------------------- */
4527 struct terminal *terminal;
4528 struct ns_display_info *dpyinfo;
4529 static int ns_initialized = 0;
4532 if (ns_initialized) return x_display_list;
4537 NSTRACE ("ns_term_init");
4539 [outerpool release];
4540 outerpool = [[NSAutoreleasePool alloc] init];
4542 /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4543 /*GSDebugAllocationActive (YES); */
4547 Fset_input_interrupt_mode (Qnil);
4549 if (selfds[0] == -1)
4551 if (emacs_pipe (selfds) != 0)
4553 fprintf (stderr, "Failed to create pipe: %s\n",
4554 emacs_strerror (errno));
4558 fcntl (selfds[0], F_SETFL, O_NONBLOCK|fcntl (selfds[0], F_GETFL));
4559 FD_ZERO (&select_readfds);
4560 FD_ZERO (&select_writefds);
4561 pthread_mutex_init (&select_mutex, NULL);
4564 ns_pending_files = [[NSMutableArray alloc] init];
4565 ns_pending_service_names = [[NSMutableArray alloc] init];
4566 ns_pending_service_args = [[NSMutableArray alloc] init];
4568 /* Start app and create the main menu, window, view.
4569 Needs to be here because ns_initialize_display_info () uses AppKit classes.
4570 The view will then ask the NSApp to stop and return to Emacs. */
4571 [EmacsApp sharedApplication];
4574 [NSApp setDelegate: NSApp];
4576 /* Start the select thread. */
4577 [NSThread detachNewThreadSelector:@selector (fd_handler:)
4581 /* debugging: log all notifications */
4582 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
4583 selector: @selector (logNotification:)
4584 name: nil object: nil]; */
4586 dpyinfo = xzalloc (sizeof *dpyinfo);
4588 ns_initialize_display_info (dpyinfo);
4589 terminal = ns_create_terminal (dpyinfo);
4591 terminal->kboard = allocate_kboard (Qns);
4592 /* Don't let the initial kboard remain current longer than necessary.
4593 That would cause problems if a file loaded on startup tries to
4594 prompt in the mini-buffer. */
4595 if (current_kboard == initial_kboard)
4596 current_kboard = terminal->kboard;
4597 terminal->kboard->reference_count++;
4599 dpyinfo->next = x_display_list;
4600 x_display_list = dpyinfo;
4602 dpyinfo->name_list_element = Fcons (display_name, Qnil);
4604 terminal->name = xlispstrdup (display_name);
4608 if (!inhibit_x_resources)
4610 ns_default ("GSFontAntiAlias", &ns_antialias_text,
4613 /* this is a standard variable */
4614 ns_default ("AppleAntiAliasingThreshold", &tmp,
4615 make_float (10.0), make_float (6.0), YES, NO);
4616 ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4619 NSTRACE_MSG ("Colors");
4622 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4626 Lisp_Object color_file, color_map, color;
4630 color_file = Fexpand_file_name (build_string ("rgb.txt"),
4631 Fsymbol_value (intern ("data-directory")));
4633 color_map = Fx_load_color_file (color_file);
4634 if (NILP (color_map))
4635 fatal ("Could not read %s.\n", SDATA (color_file));
4637 cl = [[NSColorList alloc] initWithName: @"Emacs"];
4638 for ( ; CONSP (color_map); color_map = XCDR (color_map))
4640 color = XCAR (color_map);
4641 name = SSDATA (XCAR (color));
4642 c = XINT (XCDR (color));
4644 [NSColor colorForEmacsRed: RED_FROM_ULONG (c) / 255.0
4645 green: GREEN_FROM_ULONG (c) / 255.0
4646 blue: BLUE_FROM_ULONG (c) / 255.0
4648 forKey: [NSString stringWithUTF8String: name]];
4650 [cl writeToFile: nil];
4654 NSTRACE_MSG ("Versions");
4657 #ifdef NS_IMPL_GNUSTEP
4658 Vwindow_system_version = build_string (gnustep_base_version);
4660 /*PSnextrelease (128, c); */
4661 char c[DBL_BUFSIZE_BOUND];
4662 int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4663 Vwindow_system_version = make_unibyte_string (c, len);
4667 delete_keyboard_wait_descriptor (0);
4669 ns_app_name = [[NSProcessInfo processInfo] processName];
4671 /* Set up OS X app menu */
4673 NSTRACE_MSG ("Menu init");
4675 #ifdef NS_IMPL_COCOA
4679 /* set up the application menu */
4680 svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4681 [svcsMenu setAutoenablesItems: NO];
4682 appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4683 [appMenu setAutoenablesItems: NO];
4684 mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4685 dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4687 [appMenu insertItemWithTitle: @"About Emacs"
4688 action: @selector (orderFrontStandardAboutPanel:)
4691 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4692 [appMenu insertItemWithTitle: @"Preferences..."
4693 action: @selector (showPreferencesWindow:)
4696 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4697 item = [appMenu insertItemWithTitle: @"Services"
4698 action: @selector (menuDown:)
4701 [appMenu setSubmenu: svcsMenu forItem: item];
4702 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4703 [appMenu insertItemWithTitle: @"Hide Emacs"
4704 action: @selector (hide:)
4707 item = [appMenu insertItemWithTitle: @"Hide Others"
4708 action: @selector (hideOtherApplications:)
4711 [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4712 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4713 [appMenu insertItemWithTitle: @"Quit Emacs"
4714 action: @selector (terminate:)
4718 item = [mainMenu insertItemWithTitle: ns_app_name
4719 action: @selector (menuDown:)
4722 [mainMenu setSubmenu: appMenu forItem: item];
4723 [dockMenu insertItemWithTitle: @"New Frame"
4724 action: @selector (newFrame:)
4728 [NSApp setMainMenu: mainMenu];
4729 [NSApp setAppleMenu: appMenu];
4730 [NSApp setServicesMenu: svcsMenu];
4731 /* Needed at least on Cocoa, to get dock menu to show windows */
4732 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4734 [[NSNotificationCenter defaultCenter]
4735 addObserver: mainMenu
4736 selector: @selector (trackingNotification:)
4737 name: NSMenuDidBeginTrackingNotification object: mainMenu];
4738 [[NSNotificationCenter defaultCenter]
4739 addObserver: mainMenu
4740 selector: @selector (trackingNotification:)
4741 name: NSMenuDidEndTrackingNotification object: mainMenu];
4743 #endif /* MAC OS X menu setup */
4745 /* Register our external input/output types, used for determining
4746 applicable services and also drag/drop eligibility. */
4748 NSTRACE_MSG ("Input/output types");
4750 ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
4751 ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
4753 ns_drag_types = [[NSArray arrayWithObjects:
4755 NSTabularTextPboardType,
4756 NSFilenamesPboardType,
4757 NSURLPboardType, nil] retain];
4759 /* If fullscreen is in init/default-frame-alist, focus isn't set
4760 right for fullscreen windows, so set this. */
4761 [NSApp activateIgnoringOtherApps:YES];
4763 NSTRACE_MSG ("Call NSApp run");
4766 ns_do_open_file = YES;
4768 #ifdef NS_IMPL_GNUSTEP
4769 /* GNUstep steals SIGCHLD for use in NSTask, but we don't use NSTask.
4770 We must re-catch it so subprocess works. */
4771 catch_child_signal ();
4774 NSTRACE_MSG ("ns_term_init done");
4783 ns_term_shutdown (int sig)
4785 [[NSUserDefaults standardUserDefaults] synchronize];
4787 /* code not reached in emacs.c after this is called by shut_down_emacs: */
4788 if (STRINGP (Vauto_save_list_file_name))
4789 unlink (SSDATA (Vauto_save_list_file_name));
4791 if (sig == 0 || sig == SIGTERM)
4793 [NSApp terminate: NSApp];
4795 else // force a stack trace to happen
4802 /* ==========================================================================
4804 EmacsApp implementation
4806 ========================================================================== */
4809 @implementation EmacsApp
4813 NSTRACE ("[EmacsApp init]");
4815 if ((self = [super init]))
4817 #ifdef NS_IMPL_COCOA
4818 self->isFirst = YES;
4820 #ifdef NS_IMPL_GNUSTEP
4821 self->applicationDidFinishLaunchingCalled = NO;
4828 #ifdef NS_IMPL_COCOA
4831 NSTRACE ("[EmacsApp run]");
4833 #ifndef NSAppKitVersionNumber10_9
4834 #define NSAppKitVersionNumber10_9 1265
4837 if ((int)NSAppKitVersionNumber != NSAppKitVersionNumber10_9)
4843 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
4845 if (isFirst) [self finishLaunching];
4848 shouldKeepRunning = YES;
4852 pool = [[NSAutoreleasePool alloc] init];
4855 [self nextEventMatchingMask:NSAnyEventMask
4856 untilDate:[NSDate distantFuture]
4857 inMode:NSDefaultRunLoopMode
4860 [self sendEvent:event];
4861 [self updateWindows];
4862 } while (shouldKeepRunning);
4867 - (void)stop: (id)sender
4869 NSTRACE ("[EmacsApp stop]");
4871 shouldKeepRunning = NO;
4872 // Stop possible dialog also. Noop if no dialog present.
4873 // The file dialog still leaks 7k - 10k on 10.9 though.
4874 [super stop:sender];
4876 #endif /* NS_IMPL_COCOA */
4878 - (void)logNotification: (NSNotification *)notification
4880 NSTRACE ("[EmacsApp logNotification]");
4882 const char *name = [[notification name] UTF8String];
4883 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4884 && !strstr (name, "WindowNumber"))
4885 NSLog (@"notification: '%@'", [notification name]);
4889 - (void)sendEvent: (NSEvent *)theEvent
4890 /* --------------------------------------------------------------------------
4891 Called when NSApp is running for each event received. Used to stop
4892 the loop when we choose, since there's no way to just run one iteration.
4893 -------------------------------------------------------------------------- */
4895 int type = [theEvent type];
4896 NSWindow *window = [theEvent window];
4898 NSTRACE ("[EmacsApp sendEvent]");
4899 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4901 #ifdef NS_IMPL_GNUSTEP
4902 // Keyboard events aren't propagated to file dialogs for some reason.
4903 if ([NSApp modalWindow] != nil &&
4904 (type == NSKeyDown || type == NSKeyUp || type == NSFlagsChanged))
4906 [[NSApp modalWindow] sendEvent: theEvent];
4911 if (represented_filename != nil && represented_frame)
4913 NSString *fstr = represented_filename;
4914 NSView *view = FRAME_NS_VIEW (represented_frame);
4915 #ifdef NS_IMPL_COCOA
4916 /* work around a bug observed on 10.3 and later where
4917 setTitleWithRepresentedFilename does not clear out previous state
4918 if given filename does not exist */
4919 if (! [[NSFileManager defaultManager] fileExistsAtPath: fstr])
4920 [[view window] setRepresentedFilename: @""];
4922 [[view window] setRepresentedFilename: fstr];
4923 [represented_filename release];
4924 represented_filename = nil;
4925 represented_frame = NULL;
4928 if (type == NSApplicationDefined)
4930 switch ([theEvent data2])
4932 #ifdef NS_IMPL_COCOA
4933 case NSAPP_DATA2_RUNASSCRIPT:
4938 case NSAPP_DATA2_RUNFILEDIALOG:
4939 ns_run_file_dialog ();
4945 if (type == NSCursorUpdate && window == nil)
4947 fprintf (stderr, "Dropping external cursor update event.\n");
4951 if (type == NSApplicationDefined)
4953 /* Events posted by ns_send_appdefined interrupt the run loop here.
4954 But, if a modal window is up, an appdefined can still come through,
4955 (e.g., from a makeKeyWindow event) but stopping self also stops the
4956 modal loop. Just defer it until later. */
4957 if ([NSApp modalWindow] == nil)
4959 last_appdefined_event_data = [theEvent data1];
4964 send_appdefined = YES;
4969 #ifdef NS_IMPL_COCOA
4970 /* If no dialog and none of our frames have focus and it is a move, skip it.
4971 It is a mouse move in an auxiliary menu, i.e. on the top right on OSX,
4972 such as Wifi, sound, date or similar.
4973 This prevents "spooky" highlighting in the frame under the menu. */
4974 if (type == NSMouseMoved && [NSApp modalWindow] == nil)
4976 struct ns_display_info *di;
4977 BOOL has_focus = NO;
4978 for (di = x_display_list; ! has_focus && di; di = di->next)
4979 has_focus = di->x_focus_frame != 0;
4985 [super sendEvent: theEvent];
4989 - (void)showPreferencesWindow: (id)sender
4991 struct frame *emacsframe = SELECTED_FRAME ();
4992 NSEvent *theEvent = [NSApp currentEvent];
4996 emacs_event->kind = NS_NONKEY_EVENT;
4997 emacs_event->code = KEY_NS_SHOW_PREFS;
4998 emacs_event->modifiers = 0;
4999 EV_TRAILER (theEvent);
5003 - (void)newFrame: (id)sender
5005 NSTRACE ("[EmacsApp newFrame]");
5007 struct frame *emacsframe = SELECTED_FRAME ();
5008 NSEvent *theEvent = [NSApp currentEvent];
5012 emacs_event->kind = NS_NONKEY_EVENT;
5013 emacs_event->code = KEY_NS_NEW_FRAME;
5014 emacs_event->modifiers = 0;
5015 EV_TRAILER (theEvent);
5019 /* Open a file (used by below, after going into queue read by ns_read_socket) */
5020 - (BOOL) openFile: (NSString *)fileName
5022 NSTRACE ("[EmacsApp openFile]");
5024 struct frame *emacsframe = SELECTED_FRAME ();
5025 NSEvent *theEvent = [NSApp currentEvent];
5030 emacs_event->kind = NS_NONKEY_EVENT;
5031 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
5032 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
5033 ns_input_line = Qnil; /* can be start or cons start,end */
5034 emacs_event->modifiers =0;
5035 EV_TRAILER (theEvent);
5041 /* **************************************************************************
5043 EmacsApp delegate implementation
5045 ************************************************************************** */
5047 - (void)applicationDidFinishLaunching: (NSNotification *)notification
5048 /* --------------------------------------------------------------------------
5049 When application is loaded, terminate event loop in ns_term_init
5050 -------------------------------------------------------------------------- */
5052 NSTRACE ("[EmacsApp applicationDidFinishLaunching]");
5054 #ifdef NS_IMPL_GNUSTEP
5055 ((EmacsApp *)self)->applicationDidFinishLaunchingCalled = YES;
5057 [NSApp setServicesProvider: NSApp];
5059 [self antialiasThresholdDidChange:nil];
5060 #ifdef NS_IMPL_COCOA
5061 [[NSNotificationCenter defaultCenter]
5063 selector:@selector(antialiasThresholdDidChange:)
5064 name:NSAntialiasThresholdChangedNotification
5068 ns_send_appdefined (-2);
5071 - (void)antialiasThresholdDidChange:(NSNotification *)notification
5073 #ifdef NS_IMPL_COCOA
5074 macfont_update_antialias_threshold ();
5079 /* Termination sequences:
5082 MenuBar | File | Exit:
5083 Select Quit from App menubar:
5085 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5088 Select Quit from Dock menu:
5091 Cancel -> Nothing else
5095 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5100 - (void) terminate: (id)sender
5102 NSTRACE ("[EmacsApp terminate]");
5104 struct frame *emacsframe = SELECTED_FRAME ();
5109 emacs_event->kind = NS_NONKEY_EVENT;
5110 emacs_event->code = KEY_NS_POWER_OFF;
5111 emacs_event->arg = Qt; /* mark as non-key event */
5112 EV_TRAILER ((id)nil);
5116 runAlertPanel(NSString *title,
5117 NSString *msgFormat,
5118 NSString *defaultButton,
5119 NSString *alternateButton)
5121 #if !defined (NS_IMPL_COCOA) || \
5122 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
5123 return NSRunAlertPanel(title, msgFormat, defaultButton, alternateButton, nil)
5124 == NSAlertDefaultReturn;
5126 NSAlert *alert = [[NSAlert alloc] init];
5127 [alert setAlertStyle: NSCriticalAlertStyle];
5128 [alert setMessageText: msgFormat];
5129 [alert addButtonWithTitle: defaultButton];
5130 [alert addButtonWithTitle: alternateButton];
5131 NSInteger ret = [alert runModal];
5133 return ret == NSAlertFirstButtonReturn;
5138 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
5140 NSTRACE ("[EmacsApp applicationShouldTerminate]");
5144 if (NILP (ns_confirm_quit)) // || ns_shutdown_properly --> TO DO
5145 return NSTerminateNow;
5147 ret = runAlertPanel(ns_app_name,
5148 @"Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?",
5149 @"Save Buffers and Exit", @"Cancel");
5152 return NSTerminateNow;
5154 return NSTerminateCancel;
5155 return NSTerminateNow; /* just in case */
5159 not_in_argv (NSString *arg)
5162 const char *a = [arg UTF8String];
5163 for (k = 1; k < initial_argc; ++k)
5164 if (strcmp (a, initial_argv[k]) == 0) return 0;
5168 /* Notification from the Workspace to open a file */
5169 - (BOOL)application: sender openFile: (NSString *)file
5171 if (ns_do_open_file || not_in_argv (file))
5172 [ns_pending_files addObject: file];
5177 /* Open a file as a temporary file */
5178 - (BOOL)application: sender openTempFile: (NSString *)file
5180 if (ns_do_open_file || not_in_argv (file))
5181 [ns_pending_files addObject: file];
5186 /* Notification from the Workspace to open a file noninteractively (?) */
5187 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
5189 if (ns_do_open_file || not_in_argv (file))
5190 [ns_pending_files addObject: file];
5194 /* Notification from the Workspace to open multiple files */
5195 - (void)application: sender openFiles: (NSArray *)fileList
5197 NSEnumerator *files = [fileList objectEnumerator];
5199 /* Don't open files from the command line unconditionally,
5200 Cocoa parses the command line wrong, --option value tries to open value
5201 if --option is the last option. */
5202 while ((file = [files nextObject]) != nil)
5203 if (ns_do_open_file || not_in_argv (file))
5204 [ns_pending_files addObject: file];
5206 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
5211 /* Handle dock menu requests. */
5212 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
5218 /* TODO: these may help w/IO switching btwn terminal and NSApp */
5219 - (void)applicationWillBecomeActive: (NSNotification *)notification
5221 NSTRACE ("[EmacsApp applicationWillBecomeActive]");
5222 //ns_app_active=YES;
5225 - (void)applicationDidBecomeActive: (NSNotification *)notification
5227 NSTRACE ("[EmacsApp applicationDidBecomeActive]");
5229 #ifdef NS_IMPL_GNUSTEP
5230 if (! applicationDidFinishLaunchingCalled)
5231 [self applicationDidFinishLaunching:notification];
5233 //ns_app_active=YES;
5235 ns_update_auto_hide_menu_bar ();
5236 // No constraining takes place when the application is not active.
5237 ns_constrain_all_frames ();
5239 - (void)applicationDidResignActive: (NSNotification *)notification
5241 NSTRACE ("[EmacsApp applicationDidResignActive]");
5244 ns_send_appdefined (-1);
5249 /* ==========================================================================
5251 EmacsApp aux handlers for managing event loop
5253 ========================================================================== */
5256 - (void)timeout_handler: (NSTimer *)timedEntry
5257 /* --------------------------------------------------------------------------
5258 The timeout specified to ns_select has passed.
5259 -------------------------------------------------------------------------- */
5261 /*NSTRACE ("timeout_handler"); */
5262 ns_send_appdefined (-2);
5265 #ifdef NS_IMPL_GNUSTEP
5266 - (void)sendFromMainThread:(id)unused
5268 ns_send_appdefined (nextappdefined);
5272 - (void)fd_handler:(id)unused
5273 /* --------------------------------------------------------------------------
5274 Check data waiting on file descriptors and terminate if so
5275 -------------------------------------------------------------------------- */
5278 int waiting = 1, nfds;
5281 fd_set readfds, writefds, *wfds;
5282 struct timespec timeout, *tmo;
5283 NSAutoreleasePool *pool = nil;
5285 /* NSTRACE ("fd_handler"); */
5290 pool = [[NSAutoreleasePool alloc] init];
5296 FD_SET (selfds[0], &fds);
5297 result = select (selfds[0]+1, &fds, NULL, NULL, NULL);
5298 if (result > 0 && read (selfds[0], &c, 1) == 1 && c == 'g')
5303 pthread_mutex_lock (&select_mutex);
5306 if (select_valid & SELECT_HAVE_READ)
5307 readfds = select_readfds;
5311 if (select_valid & SELECT_HAVE_WRITE)
5313 writefds = select_writefds;
5318 if (select_valid & SELECT_HAVE_TMO)
5320 timeout = select_timeout;
5326 pthread_mutex_unlock (&select_mutex);
5328 FD_SET (selfds[0], &readfds);
5329 if (selfds[0] >= nfds) nfds = selfds[0]+1;
5331 result = pselect (nfds, &readfds, wfds, NULL, tmo, NULL);
5334 ns_send_appdefined (-2);
5335 else if (result > 0)
5337 if (FD_ISSET (selfds[0], &readfds))
5339 if (read (selfds[0], &c, 1) == 1 && c == 's')
5344 pthread_mutex_lock (&select_mutex);
5345 if (select_valid & SELECT_HAVE_READ)
5346 select_readfds = readfds;
5347 if (select_valid & SELECT_HAVE_WRITE)
5348 select_writefds = writefds;
5349 if (select_valid & SELECT_HAVE_TMO)
5350 select_timeout = timeout;
5351 pthread_mutex_unlock (&select_mutex);
5353 ns_send_appdefined (result);
5363 /* ==========================================================================
5367 ========================================================================== */
5369 /* called from system: queue for next pass through event loop */
5370 - (void)requestService: (NSPasteboard *)pboard
5371 userData: (NSString *)userData
5372 error: (NSString **)error
5374 [ns_pending_service_names addObject: userData];
5375 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
5376 SSDATA (ns_string_from_pasteboard (pboard))]];
5380 /* called from ns_read_socket to clear queue */
5381 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
5383 struct frame *emacsframe = SELECTED_FRAME ();
5384 NSEvent *theEvent = [NSApp currentEvent];
5389 emacs_event->kind = NS_NONKEY_EVENT;
5390 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
5391 ns_input_spi_name = build_string ([name UTF8String]);
5392 ns_input_spi_arg = build_string ([arg UTF8String]);
5393 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5394 EV_TRAILER (theEvent);
5404 /* ==========================================================================
5406 EmacsView implementation
5408 ========================================================================== */
5411 @implementation EmacsView
5413 /* needed to inform when window closed from LISP */
5414 - (void) setWindowClosing: (BOOL)closing
5416 windowClosing = closing;
5422 NSTRACE ("EmacsView_dealloc");
5424 if (fs_state == FULLSCREEN_BOTH)
5425 [nonfs_window release];
5430 /* called on font panel selection */
5431 - (void)changeFont: (id)sender
5433 NSEvent *e = [[self window] currentEvent];
5434 struct face *face = FRAME_DEFAULT_FACE (emacsframe);
5435 struct font *font = face->font;
5440 NSTRACE ("changeFont");
5445 #ifdef NS_IMPL_GNUSTEP
5446 nsfont = ((struct nsfont_info *)font)->nsfont;
5448 #ifdef NS_IMPL_COCOA
5449 nsfont = (NSFont *) macfont_get_nsctfont (font);
5452 if ((newFont = [sender convertFont: nsfont]))
5454 SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
5456 emacs_event->kind = NS_NONKEY_EVENT;
5457 emacs_event->modifiers = 0;
5458 emacs_event->code = KEY_NS_CHANGE_FONT;
5460 size = [newFont pointSize];
5461 ns_input_fontsize = make_number (lrint (size));
5462 ns_input_font = build_string ([[newFont familyName] UTF8String]);
5468 - (BOOL)acceptsFirstResponder
5470 NSTRACE ("acceptsFirstResponder");
5475 - (void)resetCursorRects
5477 NSRect visible = [self visibleRect];
5478 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
5479 NSTRACE ("resetCursorRects");
5481 if (currentCursor == nil)
5482 currentCursor = [NSCursor arrowCursor];
5484 if (!NSIsEmptyRect (visible))
5485 [self addCursorRect: visible cursor: currentCursor];
5486 [currentCursor setOnMouseEntered: YES];
5491 /*****************************************************************************/
5492 /* Keyboard handling. */
5495 - (void)keyDown: (NSEvent *)theEvent
5497 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5499 unsigned fnKeysym = 0;
5500 static NSMutableArray *nsEvArray;
5502 unsigned int flags = [theEvent modifierFlags];
5504 NSTRACE ("keyDown");
5506 /* Rhapsody and OS X give up and down events for the arrow keys */
5507 if (ns_fake_keydown == YES)
5508 ns_fake_keydown = NO;
5509 else if ([theEvent type] != NSKeyDown)
5515 if (![[self window] isKeyWindow]
5516 && [[theEvent window] isKindOfClass: [EmacsWindow class]]
5517 /* we must avoid an infinite loop here. */
5518 && (EmacsView *)[[theEvent window] delegate] != self)
5520 /* XXX: There is an occasional condition in which, when Emacs display
5521 updates a different frame from the current one, and temporarily
5522 selects it, then processes some interrupt-driven input
5523 (dispnew.c:3878), OS will send the event to the correct NSWindow, but
5524 for some reason that window has its first responder set to the NSView
5525 most recently updated (I guess), which is not the correct one. */
5526 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
5530 if (nsEvArray == nil)
5531 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
5533 [NSCursor setHiddenUntilMouseMoves: YES];
5535 if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
5537 clear_mouse_face (hlinfo);
5538 hlinfo->mouse_face_hidden = 1;
5541 if (!processingCompose)
5543 /* When using screen sharing, no left or right information is sent,
5544 so use Left key in those cases. */
5545 int is_left_key, is_right_key;
5547 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
5548 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
5550 /* (Carbon way: [theEvent keyCode]) */
5552 /* is it a "function key"? */
5553 /* Note: Sometimes a plain key will have the NSNumericPadKeyMask
5554 flag set (this is probably a bug in the OS).
5556 if (code < 0x00ff && (flags&NSNumericPadKeyMask))
5558 fnKeysym = ns_convert_key ([theEvent keyCode] | NSNumericPadKeyMask);
5562 fnKeysym = ns_convert_key (code);
5567 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
5568 because Emacs treats Delete and KP-Delete same (in simple.el). */
5569 if ((fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
5570 #ifdef NS_IMPL_GNUSTEP
5571 /* GNUstep uses incompatible keycodes, even for those that are
5572 supposed to be hardware independent. Just check for delete.
5573 Keypad delete does not have keysym 0xFFFF.
5574 See http://savannah.gnu.org/bugs/?25395
5576 || (fnKeysym == 0xFFFF && code == 127)
5579 code = 0xFF08; /* backspace */
5584 /* are there modifiers? */
5585 emacs_event->modifiers = 0;
5587 if (flags & NSHelpKeyMask)
5588 emacs_event->modifiers |= hyper_modifier;
5590 if (flags & NSShiftKeyMask)
5591 emacs_event->modifiers |= shift_modifier;
5593 is_right_key = (flags & NSRightCommandKeyMask) == NSRightCommandKeyMask;
5594 is_left_key = (flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask
5595 || (! is_right_key && (flags & NSCommandKeyMask) == NSCommandKeyMask);
5598 emacs_event->modifiers |= parse_solitary_modifier
5599 (EQ (ns_right_command_modifier, Qleft)
5600 ? ns_command_modifier
5601 : ns_right_command_modifier);
5605 emacs_event->modifiers |= parse_solitary_modifier
5606 (ns_command_modifier);
5608 /* if super (default), take input manager's word so things like
5609 dvorak / qwerty layout work */
5610 if (EQ (ns_command_modifier, Qsuper)
5612 && [[theEvent characters] length] != 0)
5614 /* XXX: the code we get will be unshifted, so if we have
5615 a shift modifier, must convert ourselves */
5616 if (!(flags & NSShiftKeyMask))
5617 code = [[theEvent characters] characterAtIndex: 0];
5619 /* this is ugly and also requires linking w/Carbon framework
5620 (for LMGetKbdType) so for now leave this rare (?) case
5621 undealt with.. in future look into CGEvent methods */
5624 long smv = GetScriptManagerVariable (smKeyScript);
5625 Handle uchrHandle = GetResource
5626 ('uchr', GetScriptVariable (smv, smScriptKeys));
5628 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
5629 [[theEvent characters] characterAtIndex: 0],
5630 kUCKeyActionDisplay,
5631 (flags & ~NSCommandKeyMask) >> 8,
5632 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
5633 &dummy, 1, &dummy, &code);
5640 is_right_key = (flags & NSRightControlKeyMask) == NSRightControlKeyMask;
5641 is_left_key = (flags & NSLeftControlKeyMask) == NSLeftControlKeyMask
5642 || (! is_right_key && (flags & NSControlKeyMask) == NSControlKeyMask);
5645 emacs_event->modifiers |= parse_solitary_modifier
5646 (EQ (ns_right_control_modifier, Qleft)
5647 ? ns_control_modifier
5648 : ns_right_control_modifier);
5651 emacs_event->modifiers |= parse_solitary_modifier
5652 (ns_control_modifier);
5654 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
5655 emacs_event->modifiers |=
5656 parse_solitary_modifier (ns_function_modifier);
5658 left_is_none = NILP (ns_alternate_modifier)
5659 || EQ (ns_alternate_modifier, Qnone);
5661 is_right_key = (flags & NSRightAlternateKeyMask)
5662 == NSRightAlternateKeyMask;
5663 is_left_key = (flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask
5665 && (flags & NSAlternateKeyMask) == NSAlternateKeyMask);
5669 if ((NILP (ns_right_alternate_modifier)
5670 || EQ (ns_right_alternate_modifier, Qnone)
5671 || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
5673 { /* accept pre-interp alt comb */
5674 if ([[theEvent characters] length] > 0)
5675 code = [[theEvent characters] characterAtIndex: 0];
5676 /*HACK: clear lone shift modifier to stop next if from firing */
5677 if (emacs_event->modifiers == shift_modifier)
5678 emacs_event->modifiers = 0;
5681 emacs_event->modifiers |= parse_solitary_modifier
5682 (EQ (ns_right_alternate_modifier, Qleft)
5683 ? ns_alternate_modifier
5684 : ns_right_alternate_modifier);
5687 if (is_left_key) /* default = meta */
5689 if (left_is_none && !fnKeysym)
5690 { /* accept pre-interp alt comb */
5691 if ([[theEvent characters] length] > 0)
5692 code = [[theEvent characters] characterAtIndex: 0];
5693 /*HACK: clear lone shift modifier to stop next if from firing */
5694 if (emacs_event->modifiers == shift_modifier)
5695 emacs_event->modifiers = 0;
5698 emacs_event->modifiers |=
5699 parse_solitary_modifier (ns_alternate_modifier);
5703 fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
5704 code, fnKeysym, flags, emacs_event->modifiers);
5706 /* if it was a function key or had modifiers, pass it directly to emacs */
5707 if (fnKeysym || (emacs_event->modifiers
5708 && (emacs_event->modifiers != shift_modifier)
5709 && [[theEvent charactersIgnoringModifiers] length] > 0))
5710 /*[[theEvent characters] length] */
5712 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5714 code |= (1<<28)|(3<<16);
5715 else if (code == 0x7f)
5716 code |= (1<<28)|(3<<16);
5718 emacs_event->kind = code > 0xFF
5719 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5721 emacs_event->code = code;
5722 EV_TRAILER (theEvent);
5723 processingCompose = NO;
5729 if (NS_KEYLOG && !processingCompose)
5730 fprintf (stderr, "keyDown: Begin compose sequence.\n");
5732 processingCompose = YES;
5733 [nsEvArray addObject: theEvent];
5734 [self interpretKeyEvents: nsEvArray];
5735 [nsEvArray removeObject: theEvent];
5739 #ifdef NS_IMPL_COCOA
5740 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
5741 decided not to send key-down for.
5742 See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
5743 This only applies on Tiger and earlier.
5744 If it matches one of these, send it on to keyDown. */
5745 -(void)keyUp: (NSEvent *)theEvent
5747 int flags = [theEvent modifierFlags];
5748 int code = [theEvent keyCode];
5749 if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
5750 code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
5753 fprintf (stderr, "keyUp: passed test");
5754 ns_fake_keydown = YES;
5755 [self keyDown: theEvent];
5761 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
5764 /* <NSTextInput>: called when done composing;
5765 NOTE: also called when we delete over working text, followed immed.
5766 by doCommandBySelector: deleteBackward: */
5767 - (void)insertText: (id)aString
5770 int len = [(NSString *)aString length];
5774 NSLog (@"insertText '%@'\tlen = %d", aString, len);
5775 processingCompose = NO;
5780 /* first, clear any working text */
5781 if (workingText != nil)
5782 [self deleteWorkingText];
5784 /* now insert the string as keystrokes */
5785 for (i =0; i<len; i++)
5787 code = [aString characterAtIndex: i];
5788 /* TODO: still need this? */
5790 code = '~'; /* 0x7E */
5791 if (code != 32) /* Space */
5792 emacs_event->modifiers = 0;
5794 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5795 emacs_event->code = code;
5796 EV_TRAILER ((id)nil);
5801 /* <NSTextInput>: inserts display of composing characters */
5802 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
5804 NSString *str = [aString respondsToSelector: @selector (string)] ?
5805 [aString string] : aString;
5807 NSLog (@"setMarkedText '%@' len =%lu range %lu from %lu",
5808 str, (unsigned long)[str length],
5809 (unsigned long)selRange.length,
5810 (unsigned long)selRange.location);
5812 if (workingText != nil)
5813 [self deleteWorkingText];
5814 if ([str length] == 0)
5820 processingCompose = YES;
5821 workingText = [str copy];
5822 ns_working_text = build_string ([workingText UTF8String]);
5824 emacs_event->kind = NS_TEXT_EVENT;
5825 emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
5826 EV_TRAILER ((id)nil);
5830 /* delete display of composing characters [not in <NSTextInput>] */
5831 - (void)deleteWorkingText
5833 if (workingText == nil)
5836 NSLog(@"deleteWorkingText len =%lu\n", (unsigned long)[workingText length]);
5837 [workingText release];
5839 processingCompose = NO;
5844 emacs_event->kind = NS_TEXT_EVENT;
5845 emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
5846 EV_TRAILER ((id)nil);
5850 - (BOOL)hasMarkedText
5852 return workingText != nil;
5856 - (NSRange)markedRange
5858 NSRange rng = workingText != nil
5859 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
5861 NSLog (@"markedRange request");
5869 NSLog (@"unmark (accept) text");
5870 [self deleteWorkingText];
5871 processingCompose = NO;
5875 /* used to position char selection windows, etc. */
5876 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
5880 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
5882 NSLog (@"firstRectForCharRange request");
5884 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
5885 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
5886 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
5887 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
5888 +FRAME_LINE_HEIGHT (emacsframe));
5890 pt = [self convertPoint: pt toView: nil];
5891 pt = [[self window] convertBaseToScreen: pt];
5897 - (NSInteger)conversationIdentifier
5899 return (NSInteger)self;
5903 - (void)doCommandBySelector: (SEL)aSelector
5906 NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
5908 processingCompose = NO;
5909 if (aSelector == @selector (deleteBackward:))
5911 /* happens when user backspaces over an ongoing composition:
5912 throw a 'delete' into the event queue */
5915 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5916 emacs_event->code = 0xFF08;
5917 EV_TRAILER ((id)nil);
5921 - (NSArray *)validAttributesForMarkedText
5923 static NSArray *arr = nil;
5924 if (arr == nil) arr = [NSArray new];
5925 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
5929 - (NSRange)selectedRange
5932 NSLog (@"selectedRange request");
5933 return NSMakeRange (NSNotFound, 0);
5936 #if defined (NS_IMPL_COCOA) || GNUSTEP_GUI_MAJOR_VERSION > 0 || \
5937 GNUSTEP_GUI_MINOR_VERSION > 22
5938 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
5940 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
5944 NSLog (@"characterIndexForPoint request");
5948 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
5950 static NSAttributedString *str = nil;
5951 if (str == nil) str = [NSAttributedString new];
5953 NSLog (@"attributedSubstringFromRange request");
5957 /* End <NSTextInput> impl. */
5958 /*****************************************************************************/
5961 /* This is what happens when the user presses a mouse button. */
5962 - (void)mouseDown: (NSEvent *)theEvent
5964 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
5965 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5967 NSTRACE ("mouseDown");
5969 [self deleteWorkingText];
5974 dpyinfo->last_mouse_frame = emacsframe;
5975 /* appears to be needed to prevent spurious movement events generated on
5977 emacsframe->mouse_moved = 0;
5979 if ([theEvent type] == NSScrollWheel)
5981 CGFloat delta = [theEvent deltaY];
5982 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
5985 delta = [theEvent deltaX];
5988 NSTRACE ("deltaIsZero");
5991 emacs_event->kind = HORIZ_WHEEL_EVENT;
5994 emacs_event->kind = WHEEL_EVENT;
5996 emacs_event->code = 0;
5997 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
5998 ((delta > 0) ? up_modifier : down_modifier);
6002 emacs_event->kind = MOUSE_CLICK_EVENT;
6003 emacs_event->code = EV_BUTTON (theEvent);
6004 emacs_event->modifiers = EV_MODIFIERS (theEvent)
6005 | EV_UDMODIFIERS (theEvent);
6007 XSETINT (emacs_event->x, lrint (p.x));
6008 XSETINT (emacs_event->y, lrint (p.y));
6009 EV_TRAILER (theEvent);
6013 - (void)rightMouseDown: (NSEvent *)theEvent
6015 NSTRACE ("rightMouseDown");
6016 [self mouseDown: theEvent];
6020 - (void)otherMouseDown: (NSEvent *)theEvent
6022 NSTRACE ("otherMouseDown");
6023 [self mouseDown: theEvent];
6027 - (void)mouseUp: (NSEvent *)theEvent
6029 NSTRACE ("mouseUp");
6030 [self mouseDown: theEvent];
6034 - (void)rightMouseUp: (NSEvent *)theEvent
6036 NSTRACE ("rightMouseUp");
6037 [self mouseDown: theEvent];
6041 - (void)otherMouseUp: (NSEvent *)theEvent
6043 NSTRACE ("otherMouseUp");
6044 [self mouseDown: theEvent];
6048 - (void) scrollWheel: (NSEvent *)theEvent
6050 NSTRACE ("scrollWheel");
6051 [self mouseDown: theEvent];
6055 /* Tell emacs the mouse has moved. */
6056 - (void)mouseMoved: (NSEvent *)e
6058 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
6059 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6063 // NSTRACE ("mouseMoved");
6065 dpyinfo->last_mouse_movement_time = EV_TIMESTAMP (e);
6066 pt = [self convertPoint: [e locationInWindow] fromView: nil];
6067 dpyinfo->last_mouse_motion_x = pt.x;
6068 dpyinfo->last_mouse_motion_y = pt.y;
6070 /* update any mouse face */
6071 if (hlinfo->mouse_face_hidden)
6073 hlinfo->mouse_face_hidden = 0;
6074 clear_mouse_face (hlinfo);
6077 /* tooltip handling */
6078 previous_help_echo_string = help_echo_string;
6079 help_echo_string = Qnil;
6081 if (!NILP (Vmouse_autoselect_window))
6083 NSTRACE ("mouse_autoselect_window");
6084 static Lisp_Object last_mouse_window;
6086 = window_from_coordinates (emacsframe, pt.x, pt.y, 0, 0);
6088 if (WINDOWP (window)
6089 && !EQ (window, last_mouse_window)
6090 && !EQ (window, selected_window)
6091 && (focus_follows_mouse
6092 || (EQ (XWINDOW (window)->frame,
6093 XWINDOW (selected_window)->frame))))
6095 NSTRACE ("in_window");
6096 emacs_event->kind = SELECT_WINDOW_EVENT;
6097 emacs_event->frame_or_window = window;
6100 /* Remember the last window where we saw the mouse. */
6101 last_mouse_window = window;
6104 if (!note_mouse_movement (emacsframe, pt.x, pt.y))
6105 help_echo_string = previous_help_echo_string;
6107 XSETFRAME (frame, emacsframe);
6108 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
6110 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
6111 (note_mouse_highlight), which is called through the
6112 note_mouse_movement () call above */
6113 any_help_event_p = YES;
6114 gen_help_event (help_echo_string, frame, help_echo_window,
6115 help_echo_object, help_echo_pos);
6118 if (emacsframe->mouse_moved && send_appdefined)
6119 ns_send_appdefined (-1);
6123 - (void)mouseDragged: (NSEvent *)e
6125 NSTRACE ("mouseDragged");
6126 [self mouseMoved: e];
6130 - (void)rightMouseDragged: (NSEvent *)e
6132 NSTRACE ("rightMouseDragged");
6133 [self mouseMoved: e];
6137 - (void)otherMouseDragged: (NSEvent *)e
6139 NSTRACE ("otherMouseDragged");
6140 [self mouseMoved: e];
6144 - (BOOL)windowShouldClose: (id)sender
6146 NSEvent *e =[[self window] currentEvent];
6148 NSTRACE ("windowShouldClose");
6149 windowClosing = YES;
6152 emacs_event->kind = DELETE_WINDOW_EVENT;
6153 emacs_event->modifiers = 0;
6154 emacs_event->code = 0;
6156 /* Don't close this window, let this be done from lisp code. */
6160 - (void) updateFrameSize: (BOOL) delay;
6162 NSWindow *window = [self window];
6163 NSRect wr = [window frame];
6165 int oldc = cols, oldr = rows;
6166 int oldw = FRAME_PIXEL_WIDTH (emacsframe);
6167 int oldh = FRAME_PIXEL_HEIGHT (emacsframe);
6170 NSTRACE ("updateFrameSize");
6171 NSTRACE_SIZE ("Original size", NSMakeSize (oldw, oldh));
6172 NSTRACE_RECT ("Original frame", wr);
6173 NSTRACE_MSG ("Original columns: %d", cols);
6174 NSTRACE_MSG ("Original rows: %d", rows);
6176 if (! [self isFullscreen])
6178 #ifdef NS_IMPL_GNUSTEP
6179 // GNUstep does not always update the tool bar height. Force it.
6180 if (toolbar && [toolbar isVisible])
6181 update_frame_tool_bar (emacsframe);
6184 extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6185 + FRAME_TOOLBAR_HEIGHT (emacsframe);
6188 if (wait_for_tool_bar)
6190 if (FRAME_TOOLBAR_HEIGHT (emacsframe) == 0)
6192 NSTRACE_MSG ("Waiting for toolbar");
6195 wait_for_tool_bar = NO;
6198 neww = (int)wr.size.width - emacsframe->border_width;
6199 newh = (int)wr.size.height - extra;
6201 NSTRACE_SIZE ("New size", NSMakeSize (neww, newh));
6202 NSTRACE_MSG ("tool_bar_height: %d", emacsframe->tool_bar_height);
6204 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, neww);
6205 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, newh);
6207 if (cols < MINWIDTH)
6210 if (rows < MINHEIGHT)
6213 NSTRACE_MSG ("New columns: %d", cols);
6214 NSTRACE_MSG ("New rows: %d", rows);
6216 if (oldr != rows || oldc != cols || neww != oldw || newh != oldh)
6218 NSView *view = FRAME_NS_VIEW (emacsframe);
6219 NSWindow *win = [view window];
6221 change_frame_size (emacsframe,
6222 FRAME_PIXEL_TO_TEXT_WIDTH (emacsframe, neww),
6223 FRAME_PIXEL_TO_TEXT_HEIGHT (emacsframe, newh),
6225 SET_FRAME_GARBAGED (emacsframe);
6226 cancel_mouse_face (emacsframe);
6228 wr = NSMakeRect (0, 0, neww, newh);
6229 NSTRACE_RECT ("setFrame", wr);
6230 [view setFrame: wr];
6231 [self windowDidMove:nil]; // Update top/left.
6235 NSTRACE_MSG ("No change");
6239 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
6240 /* normalize frame to gridded text size */
6244 NSTRACE ("windowWillResize: toSize: " NSTRACE_FMT_SIZE,
6245 NSTRACE_ARG_SIZE (frameSize));
6246 NSTRACE_RECT ("[sender frame]", [sender frame]);
6247 NSTRACE_FSTYPE ("fs_state", fs_state);
6249 if (fs_state == FULLSCREEN_MAXIMIZED
6250 && (maximized_width != (int)frameSize.width
6251 || maximized_height != (int)frameSize.height))
6252 [self setFSValue: FULLSCREEN_NONE];
6253 else if (fs_state == FULLSCREEN_WIDTH
6254 && maximized_width != (int)frameSize.width)
6255 [self setFSValue: FULLSCREEN_NONE];
6256 else if (fs_state == FULLSCREEN_HEIGHT
6257 && maximized_height != (int)frameSize.height)
6258 [self setFSValue: FULLSCREEN_NONE];
6260 if (fs_state == FULLSCREEN_NONE)
6261 maximized_width = maximized_height = -1;
6263 if (! [self isFullscreen])
6265 extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6266 + FRAME_TOOLBAR_HEIGHT (emacsframe);
6269 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, frameSize.width);
6270 if (cols < MINWIDTH)
6273 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe,
6274 frameSize.height - extra);
6275 if (rows < MINHEIGHT)
6277 #ifdef NS_IMPL_COCOA
6279 /* this sets window title to have size in it; the wm does this under GS */
6280 NSRect r = [[self window] frame];
6281 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
6289 else if (fs_state == FULLSCREEN_NONE && ! maximizing_resize)
6292 NSWindow *window = [self window];
6295 char *t = strdup ([[[self window] title] UTF8String]);
6296 char *pos = strstr (t, " — ");
6301 size_title = xmalloc (strlen (old_title) + 40);
6302 esprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
6303 [window setTitle: [NSString stringWithUTF8String: size_title]];
6308 #endif /* NS_IMPL_COCOA */
6310 NSTRACE_MSG ("cols: %d rows: %d", cols, rows);
6312 /* Restrict the new size to the text gird.
6314 Don't restict the width if the user only adjusted the height, and
6315 vice versa. (Without this, the frame would shrink, and move
6316 slightly, if the window was resized by dragging one of its
6318 if (!frame_resize_pixelwise)
6320 NSRect r = [[self window] frame];
6322 if (r.size.width != frameSize.width)
6325 FRAME_TEXT_COLS_TO_PIXEL_WIDTH (emacsframe, cols);
6328 if (r.size.height != frameSize.height)
6331 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows) + extra;
6335 NSTRACE_RETURN_SIZE (frameSize);
6341 - (void)windowDidResize: (NSNotification *)notification
6343 NSTRACE ("windowDidResize");
6345 if (emacsframe->output_data.ns->in_animation)
6347 NSTRACE_MSG ("Ignored (in animation)");
6351 if (! [self fsIsNative])
6353 NSWindow *theWindow = [notification object];
6354 /* We can get notification on the non-FS window when in
6356 if ([self window] != theWindow) return;
6359 NSTRACE_RECT ("frame", [[notification object] frame]);
6361 #ifdef NS_IMPL_GNUSTEP
6362 NSWindow *theWindow = [notification object];
6364 /* In GNUstep, at least currently, it's possible to get a didResize
6365 without getting a willResize.. therefore we need to act as if we got
6366 the willResize now */
6367 NSSize sz = [theWindow frame].size;
6368 sz = [self windowWillResize: theWindow toSize: sz];
6369 #endif /* NS_IMPL_GNUSTEP */
6371 if (cols > 0 && rows > 0)
6373 [self updateFrameSize: YES];
6376 ns_send_appdefined (-1);
6379 #ifdef NS_IMPL_COCOA
6380 - (void)viewDidEndLiveResize
6382 [super viewDidEndLiveResize];
6385 [[self window] setTitle: [NSString stringWithUTF8String: old_title]];
6389 maximizing_resize = NO;
6391 #endif /* NS_IMPL_COCOA */
6394 - (void)windowDidBecomeKey: (NSNotification *)notification
6395 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6397 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6398 struct frame *old_focus = dpyinfo->x_focus_frame;
6400 NSTRACE ("windowDidBecomeKey");
6402 if (emacsframe != old_focus)
6403 dpyinfo->x_focus_frame = emacsframe;
6405 ns_frame_rehighlight (emacsframe);
6409 emacs_event->kind = FOCUS_IN_EVENT;
6410 EV_TRAILER ((id)nil);
6415 - (void)windowDidResignKey: (NSNotification *)notification
6416 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6418 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6419 BOOL is_focus_frame = dpyinfo->x_focus_frame == emacsframe;
6420 NSTRACE ("windowDidResignKey");
6423 dpyinfo->x_focus_frame = 0;
6425 emacsframe->mouse_moved = 0;
6426 ns_frame_rehighlight (emacsframe);
6428 /* FIXME: for some reason needed on second and subsequent clicks away
6429 from sole-frame Emacs to get hollow box to show */
6430 if (!windowClosing && [[self window] isVisible] == YES)
6432 x_update_cursor (emacsframe, 1);
6433 x_set_frame_alpha (emacsframe);
6436 if (any_help_event_p)
6439 XSETFRAME (frame, emacsframe);
6440 help_echo_string = Qnil;
6441 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
6444 if (emacs_event && is_focus_frame)
6446 [self deleteWorkingText];
6447 emacs_event->kind = FOCUS_OUT_EVENT;
6448 EV_TRAILER ((id)nil);
6453 - (void)windowWillMiniaturize: sender
6455 NSTRACE ("windowWillMiniaturize");
6471 - initFrameFromEmacs: (struct frame *)f
6479 NSTRACE ("initFrameFromEmacs");
6482 processingCompose = NO;
6483 scrollbarsNeedingUpdate = 0;
6484 fs_state = FULLSCREEN_NONE;
6485 fs_before_fs = next_maximized = -1;
6486 #ifdef HAVE_NATIVE_FS
6487 fs_is_native = ns_use_native_fullscreen;
6491 maximized_width = maximized_height = -1;
6494 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
6496 ns_userRect = NSMakeRect (0, 0, 0, 0);
6497 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
6498 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
6499 [self initWithFrame: r];
6500 [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
6502 FRAME_NS_VIEW (f) = self;
6504 #ifdef NS_IMPL_COCOA
6506 maximizing_resize = NO;
6509 win = [[EmacsWindow alloc]
6510 initWithContentRect: r
6511 styleMask: (NSResizableWindowMask |
6512 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6513 NSTitledWindowMask |
6515 NSMiniaturizableWindowMask |
6516 NSClosableWindowMask)
6517 backing: NSBackingStoreBuffered
6520 #ifdef HAVE_NATIVE_FS
6521 [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
6525 bwidth = f->border_width = wr.size.width - r.size.width;
6526 tibar_height = FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
6528 [win setAcceptsMouseMovedEvents: YES];
6529 [win setDelegate: self];
6530 #if !defined (NS_IMPL_COCOA) || \
6531 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6532 [win useOptimizedDrawing: YES];
6535 [[win contentView] addSubview: self];
6538 [self registerForDraggedTypes: ns_drag_types];
6541 name = [NSString stringWithUTF8String:
6542 NILP (tem) ? "Emacs" : SSDATA (tem)];
6543 [win setTitle: name];
6545 /* toolbar support */
6546 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
6547 [NSString stringWithFormat: @"Emacs Frame %d",
6549 [win setToolbar: toolbar];
6550 [toolbar setVisible: NO];
6552 /* Don't set frame garbaged until tool bar is up to date?
6553 This avoids an extra clear and redraw (flicker) at frame creation. */
6554 if (FRAME_EXTERNAL_TOOL_BAR (f)) wait_for_tool_bar = YES;
6555 else wait_for_tool_bar = NO;
6558 #ifdef NS_IMPL_COCOA
6560 NSButton *toggleButton;
6561 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
6562 [toggleButton setTarget: self];
6563 [toggleButton setAction: @selector (toggleToolbar: )];
6566 FRAME_TOOLBAR_HEIGHT (f) = 0;
6570 [win setMiniwindowTitle:
6571 [NSString stringWithUTF8String: SSDATA (tem)]];
6574 NSScreen *screen = [win screen];
6578 NSPoint pt = NSMakePoint
6579 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
6580 IN_BOUND (-SCREENMAX,
6581 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX));
6583 NSTRACE_POINT ("setFrameTopLeftPoint", pt);
6585 [win setFrameTopLeftPoint: pt];
6587 NSTRACE_RECT ("new frame", [win frame]);
6591 [win makeFirstResponder: self];
6593 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6594 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
6595 [win setBackgroundColor: col];
6596 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6597 [win setOpaque: NO];
6599 #if !defined (NS_IMPL_COCOA) || \
6600 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6601 [self allocateGState];
6603 [NSApp registerServicesMenuSendTypes: ns_send_types
6611 - (void)windowDidMove: sender
6613 NSWindow *win = [self window];
6614 NSRect r = [win frame];
6615 NSArray *screens = [NSScreen screens];
6616 NSScreen *screen = [screens objectAtIndex: 0];
6618 NSTRACE ("windowDidMove");
6620 if (!emacsframe->output_data.ns)
6624 emacsframe->left_pos = r.origin.x;
6625 emacsframe->top_pos =
6626 [screen frame].size.height - (r.origin.y + r.size.height);
6631 /* Called AFTER method below, but before our windowWillResize call there leads
6632 to windowDidResize -> x_set_window_size. Update emacs' notion of frame
6633 location so set_window_size moves the frame. */
6634 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
6636 NSTRACE (("[windowShouldZoom:win toFrame:" NSTRACE_FMT_RECT "]"
6637 NSTRACE_FMT_RETURN "YES"),
6638 NSTRACE_ARG_RECT (newFrame));
6640 emacsframe->output_data.ns->zooming = 1;
6645 /* Override to do something slightly nonstandard, but nice. First click on
6646 zoom button will zoom vertically. Second will zoom completely. Third
6647 returns to original. */
6648 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
6649 defaultFrame:(NSRect)defaultFrame
6651 // TODO: Rename to "currentFrame" and assign "result" properly in
6653 NSRect result = [sender frame];
6655 NSTRACE (("[windowWillUseStandardFrame: defaultFrame:"
6656 NSTRACE_FMT_RECT "]"),
6657 NSTRACE_ARG_RECT (defaultFrame));
6658 NSTRACE_FSTYPE ("fs_state", fs_state);
6659 NSTRACE_FSTYPE ("fs_before_fs", fs_before_fs);
6660 NSTRACE_FSTYPE ("next_maximized", next_maximized);
6661 NSTRACE_RECT ("ns_userRect", ns_userRect);
6662 NSTRACE_RECT ("[sender frame]", [sender frame]);
6664 if (fs_before_fs != -1) /* Entering fullscreen */
6666 NSTRACE_MSG ("Entering fullscreen");
6667 result = defaultFrame;
6671 // Save the window size and position (frame) before the resize.
6672 if (fs_state != FULLSCREEN_MAXIMIZED
6673 && fs_state != FULLSCREEN_WIDTH)
6675 ns_userRect.size.width = result.size.width;
6676 ns_userRect.origin.x = result.origin.x;
6679 if (fs_state != FULLSCREEN_MAXIMIZED
6680 && fs_state != FULLSCREEN_HEIGHT)
6682 ns_userRect.size.height = result.size.height;
6683 ns_userRect.origin.y = result.origin.y;
6686 NSTRACE_RECT ("ns_userRect (2)", ns_userRect);
6688 if (next_maximized == FULLSCREEN_HEIGHT
6689 || (next_maximized == -1
6690 && abs ((int)(defaultFrame.size.height - result.size.height))
6691 > FRAME_LINE_HEIGHT (emacsframe)))
6694 NSTRACE_MSG ("FULLSCREEN_HEIGHT");
6695 maximized_height = result.size.height = defaultFrame.size.height;
6696 maximized_width = -1;
6697 result.origin.y = defaultFrame.origin.y;
6698 if (ns_userRect.size.height != 0)
6700 result.origin.x = ns_userRect.origin.x;
6701 result.size.width = ns_userRect.size.width;
6703 [self setFSValue: FULLSCREEN_HEIGHT];
6704 #ifdef NS_IMPL_COCOA
6705 maximizing_resize = YES;
6708 else if (next_maximized == FULLSCREEN_WIDTH)
6710 NSTRACE_MSG ("FULLSCREEN_WIDTH");
6711 maximized_width = result.size.width = defaultFrame.size.width;
6712 maximized_height = -1;
6713 result.origin.x = defaultFrame.origin.x;
6714 if (ns_userRect.size.width != 0)
6716 result.origin.y = ns_userRect.origin.y;
6717 result.size.height = ns_userRect.size.height;
6719 [self setFSValue: FULLSCREEN_WIDTH];
6721 else if (next_maximized == FULLSCREEN_MAXIMIZED
6722 || (next_maximized == -1
6723 && abs ((int)(defaultFrame.size.width - result.size.width))
6724 > FRAME_COLUMN_WIDTH (emacsframe)))
6726 NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
6728 result = defaultFrame; /* second click */
6729 maximized_width = result.size.width;
6730 maximized_height = result.size.height;
6731 [self setFSValue: FULLSCREEN_MAXIMIZED];
6732 #ifdef NS_IMPL_COCOA
6733 maximizing_resize = YES;
6739 NSTRACE_MSG ("Restore");
6740 result = ns_userRect.size.height ? ns_userRect : result;
6741 NSTRACE_RECT ("restore (2)", result);
6742 ns_userRect = NSMakeRect (0, 0, 0, 0);
6743 #ifdef NS_IMPL_COCOA
6744 maximizing_resize = fs_state != FULLSCREEN_NONE;
6746 [self setFSValue: FULLSCREEN_NONE];
6747 maximized_width = maximized_height = -1;
6751 if (fs_before_fs == -1) next_maximized = -1;
6753 NSTRACE_RECT ("Final ns_userRect", ns_userRect);
6754 NSTRACE_MSG ("Final maximized_width: %d", maximized_width);
6755 NSTRACE_MSG ("Final maximized_height: %d", maximized_height);
6756 NSTRACE_FSTYPE ("Final next_maximized", next_maximized);
6758 [self windowWillResize: sender toSize: result.size];
6760 NSTRACE_RETURN_RECT (result);
6766 - (void)windowDidDeminiaturize: sender
6768 NSTRACE ("windowDidDeminiaturize");
6769 if (!emacsframe->output_data.ns)
6772 SET_FRAME_ICONIFIED (emacsframe, 0);
6773 SET_FRAME_VISIBLE (emacsframe, 1);
6774 windows_or_buffers_changed = 63;
6778 emacs_event->kind = DEICONIFY_EVENT;
6779 EV_TRAILER ((id)nil);
6784 - (void)windowDidExpose: sender
6786 NSTRACE ("windowDidExpose");
6787 if (!emacsframe->output_data.ns)
6790 SET_FRAME_VISIBLE (emacsframe, 1);
6791 SET_FRAME_GARBAGED (emacsframe);
6793 if (send_appdefined)
6794 ns_send_appdefined (-1);
6798 - (void)windowDidMiniaturize: sender
6800 NSTRACE ("windowDidMiniaturize");
6801 if (!emacsframe->output_data.ns)
6804 SET_FRAME_ICONIFIED (emacsframe, 1);
6805 SET_FRAME_VISIBLE (emacsframe, 0);
6809 emacs_event->kind = ICONIFY_EVENT;
6810 EV_TRAILER ((id)nil);
6814 #ifdef HAVE_NATIVE_FS
6815 - (NSApplicationPresentationOptions)window:(NSWindow *)window
6816 willUseFullScreenPresentationOptions:
6817 (NSApplicationPresentationOptions)proposedOptions
6819 return proposedOptions|NSApplicationPresentationAutoHideToolbar;
6823 - (void)windowWillEnterFullScreen:(NSNotification *)notification
6825 NSTRACE ("windowWillEnterFullScreen");
6826 fs_before_fs = fs_state;
6829 - (void)windowDidEnterFullScreen:(NSNotification *)notification
6831 NSTRACE ("windowDidEnterFullScreen");
6832 [self setFSValue: FULLSCREEN_BOTH];
6833 if (! [self fsIsNative])
6835 [self windowDidBecomeKey:notification];
6836 [nonfs_window orderOut:self];
6840 BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (emacsframe) ? YES : NO;
6841 #ifdef NS_IMPL_COCOA
6842 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6843 unsigned val = (unsigned)[NSApp presentationOptions];
6845 // OSX 10.7 bug fix, the menu won't appear without this.
6846 // val is non-zero on other OSX versions.
6849 NSApplicationPresentationOptions options
6850 = NSApplicationPresentationAutoHideDock
6851 | NSApplicationPresentationAutoHideMenuBar
6852 | NSApplicationPresentationFullScreen
6853 | NSApplicationPresentationAutoHideToolbar;
6855 [NSApp setPresentationOptions: options];
6859 [toolbar setVisible:tbar_visible];
6863 - (void)windowWillExitFullScreen:(NSNotification *)notification
6865 NSTRACE ("windowWillExitFullScreen");
6867 if (next_maximized != -1)
6868 fs_before_fs = next_maximized;
6871 - (void)windowDidExitFullScreen:(NSNotification *)notification
6873 NSTRACE ("windowDidExitFullScreen");
6875 [self setFSValue: fs_before_fs];
6877 #ifdef HAVE_NATIVE_FS
6878 [self updateCollectionBehavior];
6880 if (FRAME_EXTERNAL_TOOL_BAR (emacsframe))
6882 [toolbar setVisible:YES];
6883 update_frame_tool_bar (emacsframe);
6884 [self updateFrameSize:YES];
6885 [[self window] display];
6888 [toolbar setVisible:NO];
6890 if (next_maximized != -1)
6891 [[self window] performZoom:self];
6896 return fs_is_native;
6899 - (BOOL)isFullscreen
6901 if (! fs_is_native) return nonfs_window != nil;
6902 #ifdef HAVE_NATIVE_FS
6903 return ([[self window] styleMask] & NSFullScreenWindowMask) != 0;
6909 #ifdef HAVE_NATIVE_FS
6910 - (void)updateCollectionBehavior
6912 if (! [self isFullscreen])
6914 NSWindow *win = [self window];
6915 NSWindowCollectionBehavior b = [win collectionBehavior];
6916 if (ns_use_native_fullscreen)
6917 b |= NSWindowCollectionBehaviorFullScreenPrimary;
6919 b &= ~NSWindowCollectionBehaviorFullScreenPrimary;
6921 [win setCollectionBehavior: b];
6922 fs_is_native = ns_use_native_fullscreen;
6927 - (void)toggleFullScreen: (id)sender
6935 NSTRACE ("toggleFullScreen");
6939 #ifdef HAVE_NATIVE_FS
6940 [[self window] toggleFullScreen:sender];
6946 onFirstScreen = [[w screen] isEqual:[[NSScreen screens] objectAtIndex:0]];
6949 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6950 (FRAME_DEFAULT_FACE (f)),
6953 if (fs_state != FULLSCREEN_BOTH)
6955 NSScreen *screen = [w screen];
6957 #if defined (NS_IMPL_COCOA) && \
6958 MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
6959 /* Hide ghost menu bar on secondary monitor? */
6960 if (! onFirstScreen)
6961 onFirstScreen = [NSScreen screensHaveSeparateSpaces];
6963 /* Hide dock and menubar if we are on the primary screen. */
6966 #ifdef NS_IMPL_COCOA
6967 NSApplicationPresentationOptions options
6968 = NSApplicationPresentationAutoHideDock
6969 | NSApplicationPresentationAutoHideMenuBar;
6971 [NSApp setPresentationOptions: options];
6973 [NSMenu setMenuBarVisible:NO];
6977 fw = [[EmacsFSWindow alloc]
6978 initWithContentRect:[w contentRectForFrameRect:wr]
6979 styleMask:NSBorderlessWindowMask
6980 backing:NSBackingStoreBuffered
6984 [fw setContentView:[w contentView]];
6985 [fw setTitle:[w title]];
6986 [fw setDelegate:self];
6987 [fw setAcceptsMouseMovedEvents: YES];
6988 #if !defined (NS_IMPL_COCOA) || \
6989 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6990 [fw useOptimizedDrawing: YES];
6992 [fw setBackgroundColor: col];
6993 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6996 f->border_width = 0;
6997 FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
6998 tobar_height = FRAME_TOOLBAR_HEIGHT (f);
6999 FRAME_TOOLBAR_HEIGHT (f) = 0;
7003 [self windowWillEnterFullScreen:nil];
7004 [fw makeKeyAndOrderFront:NSApp];
7005 [fw makeFirstResponder:self];
7007 r = [fw frameRectForContentRect:[screen frame]];
7008 [fw setFrame: r display:YES animate:ns_use_fullscreen_animation];
7009 [self windowDidEnterFullScreen:nil];
7020 #ifdef NS_IMPL_COCOA
7021 [NSApp setPresentationOptions: NSApplicationPresentationDefault];
7023 [NSMenu setMenuBarVisible:YES];
7027 [w setContentView:[fw contentView]];
7028 [w setBackgroundColor: col];
7029 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
7032 f->border_width = bwidth;
7033 FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
7034 if (FRAME_EXTERNAL_TOOL_BAR (f))
7035 FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
7037 [self windowWillExitFullScreen:nil];
7038 [fw setFrame: [w frame] display:YES animate:ns_use_fullscreen_animation];
7040 [w makeKeyAndOrderFront:NSApp];
7041 [self windowDidExitFullScreen:nil];
7042 [self updateFrameSize:YES];
7048 NSTRACE ("handleFS");
7050 if (fs_state != emacsframe->want_fullscreen)
7052 if (fs_state == FULLSCREEN_BOTH)
7054 NSTRACE_MSG ("fs_state == FULLSCREEN_BOTH");
7055 [self toggleFullScreen:self];
7058 switch (emacsframe->want_fullscreen)
7060 case FULLSCREEN_BOTH:
7061 NSTRACE_MSG ("FULLSCREEN_BOTH");
7062 [self toggleFullScreen:self];
7064 case FULLSCREEN_WIDTH:
7065 NSTRACE_MSG ("FULLSCREEN_WIDTH");
7066 next_maximized = FULLSCREEN_WIDTH;
7067 if (fs_state != FULLSCREEN_BOTH)
7068 [[self window] performZoom:self];
7070 case FULLSCREEN_HEIGHT:
7071 NSTRACE_MSG ("FULLSCREEN_HEIGHT");
7072 next_maximized = FULLSCREEN_HEIGHT;
7073 if (fs_state != FULLSCREEN_BOTH)
7074 [[self window] performZoom:self];
7076 case FULLSCREEN_MAXIMIZED:
7077 NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
7078 next_maximized = FULLSCREEN_MAXIMIZED;
7079 if (fs_state != FULLSCREEN_BOTH)
7080 [[self window] performZoom:self];
7082 case FULLSCREEN_NONE:
7083 NSTRACE_MSG ("FULLSCREEN_NONE");
7084 if (fs_state != FULLSCREEN_BOTH)
7086 next_maximized = FULLSCREEN_NONE;
7087 [[self window] performZoom:self];
7092 emacsframe->want_fullscreen = FULLSCREEN_NONE;
7097 - (void) setFSValue: (int)value
7099 NSTRACE ("setFSValue");
7100 NSTRACE_FSTYPE ("value", value);
7102 Lisp_Object lval = Qnil;
7105 case FULLSCREEN_BOTH:
7108 case FULLSCREEN_WIDTH:
7111 case FULLSCREEN_HEIGHT:
7114 case FULLSCREEN_MAXIMIZED:
7118 store_frame_param (emacsframe, Qfullscreen, lval);
7122 - (void)mouseEntered: (NSEvent *)theEvent
7124 NSTRACE ("mouseEntered");
7126 FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7127 = EV_TIMESTAMP (theEvent);
7131 - (void)mouseExited: (NSEvent *)theEvent
7133 Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
7135 NSTRACE ("mouseExited");
7140 FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7141 = EV_TIMESTAMP (theEvent);
7143 if (emacsframe == hlinfo->mouse_face_mouse_frame)
7145 clear_mouse_face (hlinfo);
7146 hlinfo->mouse_face_mouse_frame = 0;
7153 NSTRACE ("menuDown");
7154 if (context_menu_value == -1)
7155 context_menu_value = [sender tag];
7158 NSInteger tag = [sender tag];
7159 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
7160 emacsframe->menu_bar_vector,
7164 ns_send_appdefined (-1);
7169 - (EmacsToolbar *)toolbar
7175 /* this gets called on toolbar button click */
7176 - toolbarClicked: (id)item
7179 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
7181 NSTRACE ("toolbarClicked");
7186 /* send first event (for some reason two needed) */
7187 theEvent = [[self window] currentEvent];
7188 emacs_event->kind = TOOL_BAR_EVENT;
7189 XSETFRAME (emacs_event->arg, emacsframe);
7190 EV_TRAILER (theEvent);
7192 emacs_event->kind = TOOL_BAR_EVENT;
7193 /* XSETINT (emacs_event->code, 0); */
7194 emacs_event->arg = AREF (emacsframe->tool_bar_items,
7195 idx + TOOL_BAR_ITEM_KEY);
7196 emacs_event->modifiers = EV_MODIFIERS (theEvent);
7197 EV_TRAILER (theEvent);
7202 - toggleToolbar: (id)sender
7207 emacs_event->kind = NS_NONKEY_EVENT;
7208 emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
7209 EV_TRAILER ((id)nil);
7214 - (void)drawRect: (NSRect)rect
7216 int x = NSMinX (rect), y = NSMinY (rect);
7217 int width = NSWidth (rect), height = NSHeight (rect);
7219 NSTRACE ("drawRect");
7220 NSTRACE_RECT ("input", rect);
7222 if (!emacsframe || !emacsframe->output_data.ns)
7225 ns_clear_frame_area (emacsframe, x, y, width, height);
7227 expose_frame (emacsframe, x, y, width, height);
7231 drawRect: may be called (at least in OS X 10.5) for invisible
7232 views as well for some reason. Thus, do not infer visibility
7235 emacsframe->async_visible = 1;
7236 emacsframe->async_iconified = 0;
7241 /* NSDraggingDestination protocol methods. Actually this is not really a
7242 protocol, but a category of Object. O well... */
7244 -(NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
7246 NSTRACE ("draggingEntered");
7247 return NSDragOperationGeneric;
7251 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
7257 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
7262 NSEvent *theEvent = [[self window] currentEvent];
7264 NSDragOperation op = [sender draggingSourceOperationMask];
7267 NSTRACE ("performDragOperation");
7272 position = [self convertPoint: [sender draggingLocation] fromView: nil];
7273 x = lrint (position.x); y = lrint (position.y);
7275 pb = [sender draggingPasteboard];
7276 type = [pb availableTypeFromArray: ns_drag_types];
7278 if (! (op & (NSDragOperationMove|NSDragOperationDelete)) &&
7279 // URL drags contain all operations (0xf), don't allow all to be set.
7282 if (op & NSDragOperationLink)
7283 modifiers |= NSControlKeyMask;
7284 if (op & NSDragOperationCopy)
7285 modifiers |= NSAlternateKeyMask;
7286 if (op & NSDragOperationGeneric)
7287 modifiers |= NSCommandKeyMask;
7290 modifiers = EV_MODIFIERS2 (modifiers);
7295 else if ([type isEqualToString: NSFilenamesPboardType])
7298 NSEnumerator *fenum;
7301 if (!(files = [pb propertyListForType: type]))
7304 fenum = [files objectEnumerator];
7305 while ( (file = [fenum nextObject]) )
7307 emacs_event->kind = DRAG_N_DROP_EVENT;
7308 XSETINT (emacs_event->x, x);
7309 XSETINT (emacs_event->y, y);
7310 ns_input_file = append2 (ns_input_file,
7311 build_string ([file UTF8String]));
7312 emacs_event->modifiers = modifiers;
7313 emacs_event->arg = list2 (Qfile, build_string ([file UTF8String]));
7314 EV_TRAILER (theEvent);
7318 else if ([type isEqualToString: NSURLPboardType])
7320 NSURL *url = [NSURL URLFromPasteboard: pb];
7321 if (url == nil) return NO;
7323 emacs_event->kind = DRAG_N_DROP_EVENT;
7324 XSETINT (emacs_event->x, x);
7325 XSETINT (emacs_event->y, y);
7326 emacs_event->modifiers = modifiers;
7327 emacs_event->arg = list2 (Qurl,
7328 build_string ([[url absoluteString]
7330 EV_TRAILER (theEvent);
7332 if ([url isFileURL] != NO)
7334 NSString *file = [url path];
7335 ns_input_file = append2 (ns_input_file,
7336 build_string ([file UTF8String]));
7340 else if ([type isEqualToString: NSStringPboardType]
7341 || [type isEqualToString: NSTabularTextPboardType])
7345 if (! (data = [pb stringForType: type]))
7348 emacs_event->kind = DRAG_N_DROP_EVENT;
7349 XSETINT (emacs_event->x, x);
7350 XSETINT (emacs_event->y, y);
7351 emacs_event->modifiers = modifiers;
7352 emacs_event->arg = list2 (Qnil, build_string ([data UTF8String]));
7353 EV_TRAILER (theEvent);
7358 fprintf (stderr, "Invalid data type in dragging pasteboard");
7364 - (id) validRequestorForSendType: (NSString *)typeSent
7365 returnType: (NSString *)typeReturned
7367 NSTRACE ("validRequestorForSendType");
7368 if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
7369 && typeReturned == nil)
7371 if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
7375 return [super validRequestorForSendType: typeSent
7376 returnType: typeReturned];
7380 /* The next two methods are part of NSServicesRequests informal protocol,
7381 supposedly called when a services menu item is chosen from this app.
7382 But this should not happen because we override the services menu with our
7383 own entries which call ns-perform-service.
7384 Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
7385 So let's at least stub them out until further investigation can be done. */
7387 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
7389 /* we could call ns_string_from_pasteboard(pboard) here but then it should
7390 be written into the buffer in place of the existing selection..
7391 ordinary service calls go through functions defined in ns-win.el */
7395 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
7397 NSArray *typesDeclared;
7400 /* We only support NSStringPboardType */
7401 if ([types containsObject:NSStringPboardType] == NO) {
7405 val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7406 if (CONSP (val) && SYMBOLP (XCAR (val)))
7409 if (CONSP (val) && NILP (XCDR (val)))
7412 if (! STRINGP (val))
7415 typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
7416 [pb declareTypes:typesDeclared owner:nil];
7417 ns_string_to_pasteboard (pb, val);
7422 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
7423 (gives a miniaturized version of the window); currently we use the latter for
7424 frames whose active buffer doesn't correspond to any file
7425 (e.g., '*scratch*') */
7426 - setMiniwindowImage: (BOOL) setMini
7428 id image = [[self window] miniwindowImage];
7429 NSTRACE ("setMiniwindowImage");
7431 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
7432 about "AppleDockIconEnabled" notwithstanding, however the set message
7433 below has its effect nonetheless. */
7434 if (image != emacsframe->output_data.ns->miniimage)
7436 if (image && [image isKindOfClass: [EmacsImage class]])
7438 [[self window] setMiniwindowImage:
7439 setMini ? emacsframe->output_data.ns->miniimage : nil];
7446 - (void) setRows: (int) r andColumns: (int) c
7448 NSTRACE ("[EmacsView setRows:%d andColumns:%d]", r, c);
7453 - (int) fullscreenState
7458 @end /* EmacsView */
7462 /* ==========================================================================
7464 EmacsWindow implementation
7466 ========================================================================== */
7468 @implementation EmacsWindow
7470 #ifdef NS_IMPL_COCOA
7471 - (id)accessibilityAttributeValue:(NSString *)attribute
7473 Lisp_Object str = Qnil;
7474 struct frame *f = SELECTED_FRAME ();
7475 struct buffer *curbuf = XBUFFER (XWINDOW (f->selected_window)->contents);
7477 if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
7478 return NSAccessibilityTextFieldRole;
7480 if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]
7481 && curbuf && ! NILP (BVAR (curbuf, mark_active)))
7483 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7485 else if (curbuf && [attribute isEqualToString:NSAccessibilityValueAttribute])
7487 if (! NILP (BVAR (curbuf, mark_active)))
7488 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7492 ptrdiff_t start_byte = BUF_BEGV_BYTE (curbuf);
7493 ptrdiff_t byte_range = BUF_ZV_BYTE (curbuf) - start_byte;
7494 ptrdiff_t range = BUF_ZV (curbuf) - BUF_BEGV (curbuf);
7496 if (! NILP (BVAR (curbuf, enable_multibyte_characters)))
7497 str = make_uninit_multibyte_string (range, byte_range);
7499 str = make_uninit_string (range);
7500 /* To check: This returns emacs-utf-8, which is a superset of utf-8.
7501 Is this a problem? */
7502 memcpy (SDATA (str), BYTE_POS_ADDR (start_byte), byte_range);
7509 if (CONSP (str) && SYMBOLP (XCAR (str)))
7512 if (CONSP (str) && NILP (XCDR (str)))
7517 const char *utfStr = SSDATA (str);
7518 NSString *nsStr = [NSString stringWithUTF8String: utfStr];
7523 return [super accessibilityAttributeValue:attribute];
7525 #endif /* NS_IMPL_COCOA */
7527 /* Constrain size and placement of a frame.
7529 By returning the original "frameRect", the frame is not
7530 contrained. This can lead to unwanted situations where, for
7531 example, the menu bar covers the frame.
7533 The default implementation (accessed using "super") constrains the
7534 frame to the visible area of SCREEN, minus the menu bar (if
7535 present) and the Dock. Note that default implementation also calls
7536 windowWillResize, with the frame it thinks should have. (This can
7537 make the frame exit maximized mode.)
7539 Note that this should work in situations where multiple monitors
7540 are present. Common configurations are side-by-side monitors and a
7541 monitor on top of another (e.g. when a laptop is placed under a
7543 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
7545 NSTRACE ("constrainFrameRect:" NSTRACE_FMT_RECT " toScreen:",
7546 NSTRACE_ARG_RECT (frameRect));
7548 #ifdef NS_IMPL_COCOA
7549 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7550 // If separate spaces is on, it is like each screen is independent. There is
7551 // no spanning of frames across screens.
7552 if ([NSScreen screensHaveSeparateSpaces])
7554 NSTRACE_MSG ("Screens have separate spaces");
7555 frameRect = [super constrainFrameRect:frameRect toScreen:screen];
7556 NSTRACE_RETURN_RECT (frameRect);
7562 return constrain_frame_rect(frameRect);
7566 - (void)performZoom:(id)sender
7568 NSTRACE ("performZoom");
7570 return [super performZoom:sender];
7573 - (void)zoom:(id)sender
7575 struct frame * f = SELECTED_FRAME ();
7579 ns_update_auto_hide_menu_bar();
7581 // Below are three zoom implementations. In the final commit, the
7582 // idea is that the last should be included.
7585 // Native zoom done using the standard zoom animation. Size of the
7586 // resulting frame reduced to accomodate the Dock and, if present,
7588 [super zoom:sender];
7591 // Native zoom done using the standard zoom animation, plus an
7592 // explicit resize to cover the full screen.
7593 [super zoom:sender];
7595 // After the native zoom, resize the resulting frame to fill the
7596 // entire screen, except the menu-bar.
7598 // This works for all practical purposes. (The only minor oddity is
7599 // when transiting from full-height frame to a maximized, the
7600 // animation reduces the height of the frame slighty (to the 4
7601 // pixels needed to accomodate the Doc) before it snaps back into
7602 // full height. The user would need a very trained eye to spot
7604 NSScreen * screen = [self screen];
7607 int fs_state = [(EmacsView *)[self delegate] fullscreenState];
7609 NSTRACE_FSTYPE ("fullscreenState", fs_state);
7611 NSRect sr = [screen frame];
7612 NSRect wr = [self frame];
7613 NSTRACE_RECT ("Rect after zoom", wr);
7617 if (fs_state == FULLSCREEN_MAXIMIZED
7618 || fs_state == FULLSCREEN_HEIGHT)
7621 newWr.size.height = sr.size.height - ns_menu_bar_height(screen);
7624 if (fs_state == FULLSCREEN_MAXIMIZED
7625 || fs_state == FULLSCREEN_WIDTH)
7628 newWr.size.width = sr.size.width;
7631 if (newWr.size.width != wr.size.width
7632 || newWr.size.height != wr.size.height
7633 || newWr.origin.x != wr.origin.x
7634 || newWr.origin.y != wr.origin.y)
7636 NSTRACE_RECT ("Corrected rect", newWr);
7637 [self setFrame: newWr display: NO];
7641 // Non-native zoom which is done instantaneous. The resulting frame
7642 // covert the entire scrren, except the menu-bar, if present.
7643 NSScreen * screen = [self screen];
7646 NSRect sr = [screen frame];
7647 sr.size.height -= ns_menu_bar_height (screen);
7649 sr = [[self delegate] windowWillUseStandardFrame:self
7651 [self setFrame: sr display: NO];
7656 @end /* EmacsWindow */
7659 @implementation EmacsFSWindow
7661 - (BOOL)canBecomeKeyWindow
7666 - (BOOL)canBecomeMainWindow
7673 /* ==========================================================================
7675 EmacsScroller implementation
7677 ========================================================================== */
7680 @implementation EmacsScroller
7682 /* for repeat button push */
7683 #define SCROLL_BAR_FIRST_DELAY 0.5
7684 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
7686 + (CGFloat) scrollerWidth
7688 /* TODO: if we want to allow variable widths, this is the place to do it,
7689 however neither GNUstep nor Cocoa support it very well */
7691 #if !defined (NS_IMPL_COCOA) || \
7692 MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
7693 r = [NSScroller scrollerWidth];
7695 r = [NSScroller scrollerWidthForControlSize: NSRegularControlSize
7696 scrollerStyle: NSScrollerStyleLegacy];
7702 - initFrame: (NSRect )r window: (Lisp_Object)nwin
7704 NSTRACE ("EmacsScroller_initFrame");
7706 r.size.width = [EmacsScroller scrollerWidth];
7707 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
7708 [self setContinuous: YES];
7709 [self setEnabled: YES];
7711 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
7712 locked against the top and bottom edges, and right edge on OS X, where
7713 scrollers are on right. */
7714 #ifdef NS_IMPL_GNUSTEP
7715 [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
7717 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
7720 window = XWINDOW (nwin);
7722 pixel_height = NSHeight (r);
7723 if (pixel_height == 0) pixel_height = 1;
7724 min_portion = 20 / pixel_height;
7726 frame = XFRAME (window->frame);
7727 if (FRAME_LIVE_P (frame))
7730 EmacsView *view = FRAME_NS_VIEW (frame);
7731 NSView *sview = [[view window] contentView];
7732 NSArray *subs = [sview subviews];
7734 /* disable optimization stopping redraw of other scrollbars */
7735 view->scrollbarsNeedingUpdate = 0;
7736 for (i =[subs count]-1; i >= 0; i--)
7737 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
7738 view->scrollbarsNeedingUpdate++;
7739 [sview addSubview: self];
7742 /* [self setFrame: r]; */
7748 - (void)setFrame: (NSRect)newRect
7750 NSTRACE ("EmacsScroller_setFrame");
7751 /* block_input (); */
7752 pixel_height = NSHeight (newRect);
7753 if (pixel_height == 0) pixel_height = 1;
7754 min_portion = 20 / pixel_height;
7755 [super setFrame: newRect];
7756 /* unblock_input (); */
7762 NSTRACE ("EmacsScroller_dealloc");
7764 wset_vertical_scroll_bar (window, Qnil);
7772 NSTRACE ("condemn");
7780 NSTRACE ("reprieve");
7789 bool ret = condemned;
7794 /* ensure other scrollbar updates after deletion */
7795 view = (EmacsView *)FRAME_NS_VIEW (frame);
7797 view->scrollbarsNeedingUpdate++;
7799 wset_vertical_scroll_bar (window, Qnil);
7801 [self removeFromSuperview];
7809 - (void)resetCursorRects
7811 NSRect visible = [self visibleRect];
7812 NSTRACE ("resetCursorRects");
7814 if (!NSIsEmptyRect (visible))
7815 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
7816 [[NSCursor arrowCursor] setOnMouseEntered: YES];
7820 - (int) checkSamePosition: (int) position portion: (int) portion
7823 return em_position ==position && em_portion ==portion && em_whole ==whole
7824 && portion != whole; /* needed for resize empty buf */
7828 - setPosition: (int)position portion: (int)portion whole: (int)whole
7830 NSTRACE ("setPosition");
7832 em_position = position;
7833 em_portion = portion;
7836 if (portion >= whole)
7838 #ifdef NS_IMPL_COCOA
7839 [self setKnobProportion: 1.0];
7840 [self setDoubleValue: 1.0];
7842 [self setFloatValue: 0.0 knobProportion: 1.0];
7849 portion = max ((float)whole*min_portion/pixel_height, portion);
7850 pos = (float)position / (whole - portion);
7851 por = (CGFloat)portion/whole;
7852 #ifdef NS_IMPL_COCOA
7853 [self setKnobProportion: por];
7854 [self setDoubleValue: pos];
7856 [self setFloatValue: pos knobProportion: por];
7863 /* set up emacs_event */
7864 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
7870 emacs_event->part = last_hit_part;
7871 emacs_event->code = 0;
7872 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
7873 XSETWINDOW (win, window);
7874 emacs_event->frame_or_window = win;
7875 emacs_event->timestamp = EV_TIMESTAMP (e);
7876 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
7877 emacs_event->arg = Qnil;
7878 XSETINT (emacs_event->x, loc * pixel_height);
7879 XSETINT (emacs_event->y, pixel_height-20);
7883 n_emacs_events_pending++;
7884 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
7887 hold_event (emacs_event);
7888 EVENT_INIT (*emacs_event);
7889 ns_send_appdefined (-1);
7893 /* called manually thru timer to implement repeated button action w/hold-down */
7894 - repeatScroll: (NSTimer *)scrollEntry
7896 NSEvent *e = [[self window] currentEvent];
7897 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
7898 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
7900 /* clear timer if need be */
7901 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
7903 [scroll_repeat_entry invalidate];
7904 [scroll_repeat_entry release];
7905 scroll_repeat_entry = nil;
7911 = [[NSTimer scheduledTimerWithTimeInterval:
7912 SCROLL_BAR_CONTINUOUS_DELAY
7914 selector: @selector (repeatScroll:)
7920 [self sendScrollEventAtLoc: 0 fromEvent: e];
7925 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
7926 mouseDragged events without going into a modal loop. */
7927 - (void)mouseDown: (NSEvent *)e
7930 /* hitPart is only updated AFTER event is passed on */
7931 NSScrollerPart part = [self testPart: [e locationInWindow]];
7932 CGFloat inc = 0.0, loc, kloc, pos;
7935 NSTRACE ("EmacsScroller_mouseDown");
7939 case NSScrollerDecrementPage:
7940 last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
7941 case NSScrollerIncrementPage:
7942 last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
7943 case NSScrollerDecrementLine:
7944 last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
7945 case NSScrollerIncrementLine:
7946 last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
7947 case NSScrollerKnob:
7948 last_hit_part = scroll_bar_handle; break;
7949 case NSScrollerKnobSlot: /* GNUstep-only */
7950 last_hit_part = scroll_bar_move_ratio; break;
7951 default: /* NSScrollerNoPart? */
7952 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
7959 pos = 0; /* ignored */
7961 /* set a timer to repeat, as we can't let superclass do this modally */
7963 = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
7965 selector: @selector (repeatScroll:)
7972 /* handle, or on GNUstep possibly slot */
7973 NSEvent *fake_event;
7975 /* compute float loc in slot and mouse offset on knob */
7976 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
7978 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
7984 else if (loc >= NSHeight (sr))
7986 loc = NSHeight (sr);
7994 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
7996 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
7998 last_mouse_offset = kloc;
8000 /* if knob, tell emacs a location offset by knob pos
8001 (to indicate top of handle) */
8002 if (part == NSScrollerKnob)
8003 pos = (loc - last_mouse_offset) / NSHeight (sr);
8005 /* else this is a slot click on GNUstep: go straight there */
8006 pos = loc / NSHeight (sr);
8008 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
8009 fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
8010 location: [e locationInWindow]
8011 modifierFlags: [e modifierFlags]
8012 timestamp: [e timestamp]
8013 windowNumber: [e windowNumber]
8014 context: [e context]
8015 eventNumber: [e eventNumber]
8016 clickCount: [e clickCount]
8017 pressure: [e pressure]];
8018 [super mouseUp: fake_event];
8021 if (part != NSScrollerKnob)
8022 [self sendScrollEventAtLoc: pos fromEvent: e];
8026 /* Called as we manually track scroller drags, rather than superclass. */
8027 - (void)mouseDragged: (NSEvent *)e
8032 NSTRACE ("EmacsScroller_mouseDragged");
8034 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
8036 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
8042 else if (loc >= NSHeight (sr) + last_mouse_offset)
8044 loc = NSHeight (sr) + last_mouse_offset;
8047 pos = (loc - last_mouse_offset) / NSHeight (sr);
8048 [self sendScrollEventAtLoc: pos fromEvent: e];
8052 - (void)mouseUp: (NSEvent *)e
8054 if (scroll_repeat_entry)
8056 [scroll_repeat_entry invalidate];
8057 [scroll_repeat_entry release];
8058 scroll_repeat_entry = nil;
8060 last_hit_part = scroll_bar_above_handle;
8064 /* treat scrollwheel events in the bar as though they were in the main window */
8065 - (void) scrollWheel: (NSEvent *)theEvent
8067 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
8068 [view mouseDown: theEvent];
8071 @end /* EmacsScroller */
8074 #ifdef NS_IMPL_GNUSTEP
8075 /* Dummy class to get rid of startup warnings. */
8076 @implementation EmacsDocument
8082 /* ==========================================================================
8084 Font-related functions; these used to be in nsfaces.m
8086 ========================================================================== */
8090 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
8092 struct font *font = XFONT_OBJECT (font_object);
8093 EmacsView *view = FRAME_NS_VIEW (f);
8094 int font_ascent, font_descent;
8097 fontset = fontset_from_font (font_object);
8098 FRAME_FONTSET (f) = fontset;
8100 if (FRAME_FONT (f) == font)
8101 /* This font is already set in frame F. There's nothing more to
8105 FRAME_FONT (f) = font;
8107 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
8108 FRAME_COLUMN_WIDTH (f) = font->average_width;
8109 get_font_ascent_descent (font, &font_ascent, &font_descent);
8110 FRAME_LINE_HEIGHT (f) = font_ascent + font_descent;
8112 /* Compute the scroll bar width in character columns. */
8113 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
8115 int wid = FRAME_COLUMN_WIDTH (f);
8116 FRAME_CONFIG_SCROLL_BAR_COLS (f)
8117 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
8121 int wid = FRAME_COLUMN_WIDTH (f);
8122 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
8125 /* Compute the scroll bar height in character lines. */
8126 if (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) > 0)
8128 int height = FRAME_LINE_HEIGHT (f);
8129 FRAME_CONFIG_SCROLL_BAR_LINES (f)
8130 = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + height - 1) / height;
8134 int height = FRAME_LINE_HEIGHT (f);
8135 FRAME_CONFIG_SCROLL_BAR_LINES (f) = (14 + height - 1) / height;
8138 /* Now make the frame display the given font. */
8139 if (FRAME_NS_WINDOW (f) != 0 && ! [view isFullscreen])
8140 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
8141 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 3,
8148 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
8149 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
8153 ns_xlfd_to_fontname (const char *xlfd)
8154 /* --------------------------------------------------------------------------
8155 Convert an X font name (XLFD) to an NS font name.
8156 Only family is used.
8157 The string returned is temporarily allocated.
8158 -------------------------------------------------------------------------- */
8160 char *name = xmalloc (180);
8164 if (!strncmp (xlfd, "--", 2))
8165 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
8167 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
8169 /* stopgap for malformed XLFD input */
8170 if (strlen (name) == 0)
8171 strcpy (name, "Monaco");
8173 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
8174 also uppercase after '-' or ' ' */
8175 name[0] = c_toupper (name[0]);
8176 for (len =strlen (name), i =0; i<len; i++)
8182 name[i+1] = c_toupper (name[i+1]);
8184 else if (name[i] == '_')
8188 name[i+1] = c_toupper (name[i+1]);
8191 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
8192 ret = [[NSString stringWithUTF8String: name] UTF8String];
8199 syms_of_nsterm (void)
8201 NSTRACE ("syms_of_nsterm");
8203 ns_antialias_threshold = 10.0;
8205 /* from 23+ we need to tell emacs what modifiers there are.. */
8206 DEFSYM (Qmodifier_value, "modifier-value");
8207 DEFSYM (Qalt, "alt");
8208 DEFSYM (Qhyper, "hyper");
8209 DEFSYM (Qmeta, "meta");
8210 DEFSYM (Qsuper, "super");
8211 DEFSYM (Qcontrol, "control");
8212 DEFSYM (QUTF8_STRING, "UTF8_STRING");
8214 DEFSYM (Qfile, "file");
8215 DEFSYM (Qurl, "url");
8217 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
8218 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
8219 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
8220 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
8221 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
8223 DEFVAR_LISP ("ns-input-file", ns_input_file,
8224 "The file specified in the last NS event.");
8225 ns_input_file =Qnil;
8227 DEFVAR_LISP ("ns-working-text", ns_working_text,
8228 "String for visualizing working composition sequence.");
8229 ns_working_text =Qnil;
8231 DEFVAR_LISP ("ns-input-font", ns_input_font,
8232 "The font specified in the last NS event.");
8233 ns_input_font =Qnil;
8235 DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
8236 "The fontsize specified in the last NS event.");
8237 ns_input_fontsize =Qnil;
8239 DEFVAR_LISP ("ns-input-line", ns_input_line,
8240 "The line specified in the last NS event.");
8241 ns_input_line =Qnil;
8243 DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
8244 "The service name specified in the last NS event.");
8245 ns_input_spi_name =Qnil;
8247 DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
8248 "The service argument specified in the last NS event.");
8249 ns_input_spi_arg =Qnil;
8251 DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
8252 "This variable describes the behavior of the alternate or option key.\n\
8253 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8254 Set to none means that the alternate / 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_alternate_modifier = Qmeta;
8258 DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
8259 "This variable describes the behavior of the right alternate or option key.\n\
8260 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8261 Set to left means be the same key as `ns-alternate-modifier'.\n\
8262 Set to none means that the alternate / option key is not interpreted by Emacs\n\
8263 at all, allowing it to be used at a lower level for accented character entry.");
8264 ns_right_alternate_modifier = Qleft;
8266 DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
8267 "This variable describes the behavior of the command key.\n\
8268 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
8269 ns_command_modifier = Qsuper;
8271 DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
8272 "This variable describes the behavior of the right command key.\n\
8273 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8274 Set to left means be the same key as `ns-command-modifier'.\n\
8275 Set to none means that the command / option key is not interpreted by Emacs\n\
8276 at all, allowing it to be used at a lower level for accented character entry.");
8277 ns_right_command_modifier = Qleft;
8279 DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
8280 "This variable describes the behavior of the control key.\n\
8281 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
8282 ns_control_modifier = Qcontrol;
8284 DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
8285 "This variable describes the behavior of the right control key.\n\
8286 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8287 Set to left means be the same key as `ns-control-modifier'.\n\
8288 Set to none means that the control / option key is not interpreted by Emacs\n\
8289 at all, allowing it to be used at a lower level for accented character entry.");
8290 ns_right_control_modifier = Qleft;
8292 DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
8293 "This variable describes the behavior of the function key (on laptops).\n\
8294 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8295 Set to none means that the function key is not interpreted by Emacs at all,\n\
8296 allowing it to be used at a lower level for accented character entry.");
8297 ns_function_modifier = Qnone;
8299 DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
8300 "Non-nil (the default) means to render text antialiased.");
8301 ns_antialias_text = Qt;
8303 DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
8304 "Whether to confirm application quit using dialog.");
8305 ns_confirm_quit = Qnil;
8307 DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
8308 doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
8309 Only works on OSX 10.6 or later. */);
8310 ns_auto_hide_menu_bar = Qnil;
8312 DEFVAR_BOOL ("ns-use-native-fullscreen", ns_use_native_fullscreen,
8313 doc: /*Non-nil means to use native fullscreen on OSX >= 10.7.
8314 Nil means use fullscreen the old (< 10.7) way. The old way works better with
8315 multiple monitors, but lacks tool bar. This variable is ignored on OSX < 10.7.
8316 Default is t for OSX >= 10.7, nil otherwise. */);
8317 #ifdef HAVE_NATIVE_FS
8318 ns_use_native_fullscreen = YES;
8320 ns_use_native_fullscreen = NO;
8322 ns_last_use_native_fullscreen = ns_use_native_fullscreen;
8324 DEFVAR_BOOL ("ns-use-fullscreen-animation", ns_use_fullscreen_animation,
8325 doc: /*Non-nil means use animation on non-native fullscreen.
8326 For native fullscreen, this does nothing.
8327 Default is nil. */);
8328 ns_use_fullscreen_animation = NO;
8330 DEFVAR_BOOL ("ns-use-srgb-colorspace", ns_use_srgb_colorspace,
8331 doc: /*Non-nil means to use sRGB colorspace on OSX >= 10.7.
8332 Note that this does not apply to images.
8333 This variable is ignored on OSX < 10.7 and GNUstep. */);
8334 ns_use_srgb_colorspace = YES;
8336 /* TODO: move to common code */
8337 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
8338 doc: /* Which toolkit scroll bars Emacs uses, if any.
8339 A value of nil means Emacs doesn't use toolkit scroll bars.
8340 With the X Window system, the value is a symbol describing the
8341 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
8342 With MS Windows or Nextstep, the value is t. */);
8343 Vx_toolkit_scroll_bars = Qt;
8345 DEFVAR_BOOL ("x-use-underline-position-properties",
8346 x_use_underline_position_properties,
8347 doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
8348 A value of nil means ignore them. If you encounter fonts with bogus
8349 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
8350 to 4.1, set this to nil. */);
8351 x_use_underline_position_properties = 0;
8353 DEFVAR_BOOL ("x-underline-at-descent-line",
8354 x_underline_at_descent_line,
8355 doc: /* Non-nil means to draw the underline at the same place as the descent line.
8356 A value of nil means to draw the underline according to the value of the
8357 variable `x-use-underline-position-properties', which is usually at the
8358 baseline level. The default value is nil. */);
8359 x_underline_at_descent_line = 0;
8361 /* Tell Emacs about this window system. */
8362 Fprovide (Qns, Qnil);
8364 DEFSYM (Qcocoa, "cocoa");
8365 DEFSYM (Qgnustep, "gnustep");
8367 #ifdef NS_IMPL_COCOA
8368 Fprovide (Qcocoa, Qnil);
8371 Fprovide (Qgnustep, Qnil);