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 /* Fringe bitmaps comes in two variants, normal and periodic. A
2460 periodic bitmap is used to create a continuous pattern. Since a
2461 bitmap is rendered one text line at a time, the start offset (dh)
2462 of the bitmap varies. Concretely, this is used for the empty
2465 For a bitmap, "h + dh" is the full height and is always
2466 invariant. For a normal bitmap "dh" is zero.
2468 For example, when the period is three and the full height is 72
2469 the following combinations exists:
2475 struct frame *f = XFRAME (WINDOW_FRAME (w));
2476 struct face *face = p->face;
2477 static EmacsImage **bimgs = NULL;
2478 static int nBimgs = 0;
2480 NSTRACE ("ns_draw_fringe_bitmap");
2481 NSTRACE_MSG ("which:%d cursor:%d overlay:%d width:%d height:%d period:%d",
2482 p->which, p->cursor_p, p->overlay_p, p->wd, p->h, p->dh);
2484 /* grow bimgs if needed */
2485 if (nBimgs < max_used_fringe_bitmap)
2487 bimgs = xrealloc (bimgs, max_used_fringe_bitmap * sizeof *bimgs);
2488 memset (bimgs + nBimgs, 0,
2489 (max_used_fringe_bitmap - nBimgs) * sizeof *bimgs);
2490 nBimgs = max_used_fringe_bitmap;
2493 /* Must clip because of partially visible lines. */
2494 ns_clip_to_row (w, row, ANY_AREA, YES);
2498 int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
2500 if (bx >= 0 && nx > 0)
2502 NSRect r = NSMakeRect (bx, by, nx, ny);
2504 [ns_lookup_indexed_color (face->background, f) set];
2511 NSRect r = NSMakeRect (p->x, p->y, p->wd, p->h);
2512 EmacsImage *img = bimgs[p->which - 1];
2516 // Note: For "periodic" images, allocate one EmacsImage for
2517 // the base image, and use it for all dh:s.
2518 unsigned short *bits = p->bits;
2519 int full_height = p->h + p->dh;
2521 unsigned char *cbits = xmalloc (full_height);
2523 for (i = 0; i < full_height; i++)
2525 img = [[EmacsImage alloc] initFromXBM: cbits width: 8
2528 bimgs[p->which - 1] = img;
2532 NSTRACE_RECT ("r", r);
2535 /* Since we composite the bitmap instead of just blitting it, we need
2536 to erase the whole background. */
2537 [ns_lookup_indexed_color(face->background, f) set];
2543 bm_color = ns_lookup_indexed_color(face->foreground, f);
2544 else if (p->overlay_p)
2545 bm_color = ns_lookup_indexed_color(face->background, f);
2547 bm_color = f->output_data.ns->cursor_color;
2548 [img setXBMColor: bm_color];
2551 // Note: For periodic images, the full image height is "h + hd".
2552 // By using the height h, a suitable part of the image is used.
2553 NSRect fromRect = NSMakeRect(0, 0, p->wd, p->h);
2555 NSTRACE_RECT ("fromRect", fromRect);
2557 #ifdef NS_IMPL_COCOA
2560 operation: NSCompositeSourceOver
2566 NSPoint pt = r.origin;
2568 [img compositeToPoint: pt operation: NSCompositeSourceOver];
2577 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2578 int x, int y, enum text_cursor_kinds cursor_type,
2579 int cursor_width, bool on_p, bool active_p)
2580 /* --------------------------------------------------------------------------
2581 External call (RIF): draw cursor.
2582 Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2583 -------------------------------------------------------------------------- */
2586 int fx, fy, h, cursor_height;
2587 struct frame *f = WINDOW_XFRAME (w);
2588 struct glyph *phys_cursor_glyph;
2589 struct glyph *cursor_glyph;
2591 NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2593 /* If cursor is out of bounds, don't draw garbage. This can happen
2594 in mini-buffer windows when switching between echo area glyphs
2597 NSTRACE ("dumpcursor");
2602 w->phys_cursor_type = cursor_type;
2603 w->phys_cursor_on_p = on_p;
2605 if (cursor_type == NO_CURSOR)
2607 w->phys_cursor_width = 0;
2611 if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2613 if (glyph_row->exact_window_width_line_p
2614 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2616 glyph_row->cursor_in_fringe_p = 1;
2617 draw_fringe_bitmap (w, glyph_row, 0);
2622 /* We draw the cursor (with NSRectFill), then draw the glyph on top
2623 (other terminals do it the other way round). We must set
2624 w->phys_cursor_width to the cursor width. For bar cursors, that
2625 is CURSOR_WIDTH; for box cursors, it is the glyph width. */
2626 get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2628 /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2629 to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2630 if (cursor_type == BAR_CURSOR)
2632 if (cursor_width < 1)
2633 cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2634 w->phys_cursor_width = cursor_width;
2636 /* If we have an HBAR, "cursor_width" MAY specify height. */
2637 else if (cursor_type == HBAR_CURSOR)
2639 cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2640 if (cursor_height > glyph_row->height)
2641 cursor_height = glyph_row->height;
2642 if (h > cursor_height) // Cursor smaller than line height, move down
2643 fy += h - cursor_height;
2647 r.origin.x = fx, r.origin.y = fy;
2649 r.size.width = w->phys_cursor_width;
2651 /* TODO: only needed in rare cases with last-resort font in HELLO..
2652 should we do this more efficiently? */
2653 ns_clip_to_row (w, glyph_row, ANY_AREA, NO); /* do ns_focus(f, &r, 1); if remove */
2656 face = FACE_FROM_ID (f, phys_cursor_glyph->face_id);
2657 if (face && NS_FACE_BACKGROUND (face)
2658 == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2660 [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2661 hollow_color = FRAME_CURSOR_COLOR (f);
2664 [FRAME_CURSOR_COLOR (f) set];
2666 #ifdef NS_IMPL_COCOA
2667 /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2668 atomic. Cleaner ways of doing this should be investigated.
2669 One way would be to set a global variable DRAWING_CURSOR
2670 when making the call to draw_phys..(), don't focus in that
2671 case, then move the ns_unfocus() here after that call. */
2672 NSDisableScreenUpdates ();
2675 switch (cursor_type)
2677 case DEFAULT_CURSOR:
2680 case FILLED_BOX_CURSOR:
2683 case HOLLOW_BOX_CURSOR:
2686 NSRectFill (NSInsetRect (r, 1, 1));
2687 [FRAME_CURSOR_COLOR (f) set];
2694 /* If the character under cursor is R2L, draw the bar cursor
2695 on the right of its glyph, rather than on the left. */
2696 cursor_glyph = get_phys_cursor_glyph (w);
2697 if ((cursor_glyph->resolved_level & 1) != 0)
2698 s.origin.x += cursor_glyph->pixel_width - s.size.width;
2705 /* draw the character under the cursor */
2706 if (cursor_type != NO_CURSOR)
2707 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2709 #ifdef NS_IMPL_COCOA
2710 NSEnableScreenUpdates ();
2717 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2718 /* --------------------------------------------------------------------------
2719 External (RIF): Draw a vertical line.
2720 -------------------------------------------------------------------------- */
2722 struct frame *f = XFRAME (WINDOW_FRAME (w));
2724 NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2726 NSTRACE ("ns_draw_vertical_window_border");
2728 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2730 [ns_lookup_indexed_color(face->foreground, f) set];
2732 ns_focus (f, &r, 1);
2739 ns_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
2740 /* --------------------------------------------------------------------------
2741 External (RIF): Draw a window divider.
2742 -------------------------------------------------------------------------- */
2744 struct frame *f = XFRAME (WINDOW_FRAME (w));
2746 NSRect r = NSMakeRect (x0, y0, x1-x0, y1-y0);
2748 NSTRACE ("ns_draw_window_divider");
2750 face = FACE_FROM_ID (f, WINDOW_DIVIDER_FACE_ID);
2752 [ns_lookup_indexed_color(face->foreground, f) set];
2754 ns_focus (f, &r, 1);
2760 ns_show_hourglass (struct frame *f)
2762 /* TODO: add NSProgressIndicator to all frames. */
2766 ns_hide_hourglass (struct frame *f)
2768 /* TODO: remove NSProgressIndicator from all frames. */
2771 /* ==========================================================================
2773 Glyph drawing operations
2775 ========================================================================== */
2778 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2779 /* --------------------------------------------------------------------------
2780 Wrapper utility to account for internal border width on full-width lines,
2781 and allow top full-width rows to hit the frame top. nr should be pointer
2782 to two successive NSRects. Number of rects actually used is returned.
2783 -------------------------------------------------------------------------- */
2785 int n = get_glyph_string_clip_rects (s, nr, 2);
2789 /* --------------------------------------------------------------------
2790 Draw a wavy line under glyph string s. The wave fills wave_height
2797 wave_height = 3 | * * * *
2798 --------------------------------------------------------------------- */
2801 ns_draw_underwave (struct glyph_string *s, EmacsCGFloat width, EmacsCGFloat x)
2803 int wave_height = 3, wave_length = 2;
2804 int y, dx, dy, odd, xmax;
2809 dy = wave_height - 1;
2810 y = s->ybase - wave_height + 3;
2813 /* Find and set clipping rectangle */
2814 waveClip = NSMakeRect (x, y, width, wave_height);
2815 [[NSGraphicsContext currentContext] saveGraphicsState];
2816 NSRectClip (waveClip);
2818 /* Draw the waves */
2819 a.x = x - ((int)(x) % dx) + (EmacsCGFloat) 0.5;
2821 odd = (int)(a.x/dx) % 2;
2822 a.y = b.y = y + 0.5;
2831 [NSBezierPath strokeLineFromPoint:a toPoint:b];
2832 a.x = b.x, a.y = b.y;
2833 b.x += dx, b.y = y + 0.5 + odd*dy;
2837 /* Restore previous clipping rectangle(s) */
2838 [[NSGraphicsContext currentContext] restoreGraphicsState];
2844 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
2845 NSColor *defaultCol, CGFloat width, CGFloat x)
2846 /* --------------------------------------------------------------------------
2847 Draw underline, overline, and strike-through on glyph string s.
2848 -------------------------------------------------------------------------- */
2850 if (s->for_overlaps)
2854 if (face->underline_p)
2856 if (s->face->underline_type == FACE_UNDER_WAVE)
2858 if (face->underline_defaulted_p)
2861 [ns_lookup_indexed_color (face->underline_color, s->f) set];
2863 ns_draw_underwave (s, width, x);
2865 else if (s->face->underline_type == FACE_UNDER_LINE)
2869 unsigned long thickness, position;
2871 /* If the prev was underlined, match its appearance. */
2872 if (s->prev && s->prev->face->underline_p
2873 && s->prev->face->underline_type == FACE_UNDER_LINE
2874 && s->prev->underline_thickness > 0)
2876 thickness = s->prev->underline_thickness;
2877 position = s->prev->underline_position;
2882 unsigned long descent;
2885 descent = s->y + s->height - s->ybase;
2887 /* Use underline thickness of font, defaulting to 1. */
2888 thickness = (font && font->underline_thickness > 0)
2889 ? font->underline_thickness : 1;
2891 /* Determine the offset of underlining from the baseline. */
2892 if (x_underline_at_descent_line)
2893 position = descent - thickness;
2894 else if (x_use_underline_position_properties
2895 && font && font->underline_position >= 0)
2896 position = font->underline_position;
2898 position = lround (font->descent / 2);
2900 position = underline_minimum_offset;
2902 position = max (position, underline_minimum_offset);
2904 /* Ensure underlining is not cropped. */
2905 if (descent <= position)
2907 position = descent - 1;
2910 else if (descent < position + thickness)
2914 s->underline_thickness = thickness;
2915 s->underline_position = position;
2917 r = NSMakeRect (x, s->ybase + position, width, thickness);
2919 if (face->underline_defaulted_p)
2922 [ns_lookup_indexed_color (face->underline_color, s->f) set];
2926 /* Do overline. We follow other terms in using a thickness of 1
2927 and ignoring overline_margin. */
2928 if (face->overline_p)
2931 r = NSMakeRect (x, s->y, width, 1);
2933 if (face->overline_color_defaulted_p)
2936 [ns_lookup_indexed_color (face->overline_color, s->f) set];
2940 /* Do strike-through. We follow other terms for thickness and
2941 vertical position.*/
2942 if (face->strike_through_p)
2947 dy = lrint ((s->height - 1) / 2);
2948 r = NSMakeRect (x, s->y + dy, width, 1);
2950 if (face->strike_through_color_defaulted_p)
2953 [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
2959 ns_draw_box (NSRect r, CGFloat thickness, NSColor *col,
2960 char left_p, char right_p)
2961 /* --------------------------------------------------------------------------
2962 Draw an unfilled rect inside r, optionally leaving left and/or right open.
2963 Note we can't just use an NSDrawRect command, because of the possibility
2964 of some sides not being drawn, and because the rect will be filled.
2965 -------------------------------------------------------------------------- */
2971 s.size.height = thickness;
2973 s.origin.y += r.size.height - thickness;
2976 s.size.height = r.size.height;
2977 s.origin.y = r.origin.y;
2979 /* left, right (optional) */
2980 s.size.width = thickness;
2985 s.origin.x += r.size.width - thickness;
2992 ns_draw_relief (NSRect r, int thickness, char raised_p,
2993 char top_p, char bottom_p, char left_p, char right_p,
2994 struct glyph_string *s)
2995 /* --------------------------------------------------------------------------
2996 Draw a relief rect inside r, optionally leaving some sides open.
2997 Note we can't just use an NSDrawBezel command, because of the possibility
2998 of some sides not being drawn, and because the rect will be filled.
2999 -------------------------------------------------------------------------- */
3001 static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
3002 NSColor *newBaseCol = nil;
3005 NSTRACE ("ns_draw_relief");
3009 if (s->face->use_box_color_for_shadows_p)
3011 newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
3013 /* else if (s->first_glyph->type == IMAGE_GLYPH
3015 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
3017 newBaseCol = IMAGE_BACKGROUND (s->img, s->f, 0);
3021 newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
3024 if (newBaseCol == nil)
3025 newBaseCol = [NSColor grayColor];
3027 if (newBaseCol != baseCol) /* TODO: better check */
3030 baseCol = [newBaseCol retain];
3032 lightCol = [[baseCol highlightWithLevel: 0.2] retain];
3034 darkCol = [[baseCol shadowWithLevel: 0.3] retain];
3037 [(raised_p ? lightCol : darkCol) set];
3039 /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
3042 sr.size.height = thickness;
3043 if (top_p) NSRectFill (sr);
3046 sr.size.height = r.size.height;
3047 sr.size.width = thickness;
3048 if (left_p) NSRectFill (sr);
3050 [(raised_p ? darkCol : lightCol) set];
3053 sr.size.width = r.size.width;
3054 sr.size.height = thickness;
3055 sr.origin.y += r.size.height - thickness;
3056 if (bottom_p) NSRectFill (sr);
3059 sr.size.height = r.size.height;
3060 sr.origin.y = r.origin.y;
3061 sr.size.width = thickness;
3062 sr.origin.x += r.size.width - thickness;
3063 if (right_p) NSRectFill (sr);
3068 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
3069 /* --------------------------------------------------------------------------
3070 Function modeled after x_draw_glyph_string_box ().
3071 Sets up parameters for drawing.
3072 -------------------------------------------------------------------------- */
3074 int right_x, last_x;
3075 char left_p, right_p;
3076 struct glyph *last_glyph;
3081 if (s->hl == DRAW_MOUSE_FACE)
3083 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3085 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3090 thickness = face->box_line_width;
3092 NSTRACE ("ns_dumpglyphs_box_or_relief");
3094 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
3095 ? WINDOW_RIGHT_EDGE_X (s->w)
3096 : window_box_right (s->w, s->area));
3097 last_glyph = (s->cmp || s->img
3098 ? s->first_glyph : s->first_glyph + s->nchars-1);
3100 right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
3101 ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
3103 left_p = (s->first_glyph->left_box_line_p
3104 || (s->hl == DRAW_MOUSE_FACE
3105 && (s->prev == NULL || s->prev->hl != s->hl)));
3106 right_p = (last_glyph->right_box_line_p
3107 || (s->hl == DRAW_MOUSE_FACE
3108 && (s->next == NULL || s->next->hl != s->hl)));
3110 r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
3112 /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
3113 if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
3115 ns_draw_box (r, abs (thickness),
3116 ns_lookup_indexed_color (face->box_color, s->f),
3121 ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
3122 1, 1, left_p, right_p, s);
3128 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
3129 /* --------------------------------------------------------------------------
3130 Modeled after x_draw_glyph_string_background, which draws BG in
3131 certain cases. Others are left to the text rendering routine.
3132 -------------------------------------------------------------------------- */
3134 NSTRACE ("ns_maybe_dumpglyphs_background");
3136 if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
3138 int box_line_width = max (s->face->box_line_width, 0);
3139 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
3140 /* When xdisp.c ignores FONT_HEIGHT, we cannot trust font
3141 dimensions, since the actual glyphs might be much
3142 smaller. So in that case we always clear the rectangle
3143 with background color. */
3144 || FONT_TOO_HIGH (s->font)
3145 || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
3148 if (s->hl == DRAW_MOUSE_FACE)
3150 face = FACE_FROM_ID (s->f,
3151 MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3153 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3156 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3158 [(NS_FACE_BACKGROUND (face) != 0
3159 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
3160 : FRAME_BACKGROUND_COLOR (s->f)) set];
3163 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (s->f);
3164 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
3167 if (s->hl != DRAW_CURSOR)
3169 NSRect r = NSMakeRect (s->x, s->y + box_line_width,
3170 s->background_width,
3171 s->height-2*box_line_width);
3175 s->background_filled_p = 1;
3182 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
3183 /* --------------------------------------------------------------------------
3184 Renders an image and associated borders.
3185 -------------------------------------------------------------------------- */
3187 EmacsImage *img = s->img->pixmap;
3188 int box_line_vwidth = max (s->face->box_line_width, 0);
3189 int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3190 int bg_x, bg_y, bg_height;
3197 NSTRACE ("ns_dumpglyphs_image");
3199 if (s->face->box != FACE_NO_BOX
3200 && s->first_glyph->left_box_line_p && s->slice.x == 0)
3201 x += abs (s->face->box_line_width);
3204 bg_y = s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
3205 bg_height = s->height;
3206 /* other terms have this, but was causing problems w/tabbar mode */
3207 /* - 2 * box_line_vwidth; */
3209 if (s->slice.x == 0) x += s->img->hmargin;
3210 if (s->slice.y == 0) y += s->img->vmargin;
3212 /* Draw BG: if we need larger area than image itself cleared, do that,
3213 otherwise, since we composite the image under NS (instead of mucking
3214 with its background color), we must clear just the image area. */
3215 if (s->hl == DRAW_MOUSE_FACE)
3217 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3219 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3222 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3224 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
3226 if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
3227 || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
3229 br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
3230 s->background_filled_p = 1;
3234 br = NSMakeRect (x, y, s->slice.width, s->slice.height);
3239 /* Draw the image.. do we need to draw placeholder if img ==nil? */
3242 #ifdef NS_IMPL_COCOA
3243 NSRect dr = NSMakeRect (x, y, s->slice.width, s->slice.height);
3244 NSRect ir = NSMakeRect (s->slice.x, s->slice.y,
3245 s->slice.width, s->slice.height);
3248 operation: NSCompositeSourceOver
3253 [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3254 operation: NSCompositeSourceOver];
3258 if (s->hl == DRAW_CURSOR)
3260 [FRAME_CURSOR_COLOR (s->f) set];
3261 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3262 tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3264 /* Currently on NS img->mask is always 0. Since
3265 get_window_cursor_type specifies a hollow box cursor when on
3266 a non-masked image we never reach this clause. But we put it
3267 in in anticipation of better support for image masks on
3269 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3273 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3276 /* Draw underline, overline, strike-through. */
3277 ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3279 /* Draw relief, if requested */
3280 if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3282 if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3284 th = tool_bar_button_relief >= 0 ?
3285 tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3286 raised_p = (s->hl == DRAW_IMAGE_RAISED);
3290 th = abs (s->img->relief);
3291 raised_p = (s->img->relief > 0);
3294 r.origin.x = x - th;
3295 r.origin.y = y - th;
3296 r.size.width = s->slice.width + 2*th-1;
3297 r.size.height = s->slice.height + 2*th-1;
3298 ns_draw_relief (r, th, raised_p,
3300 s->slice.y + s->slice.height == s->img->height,
3302 s->slice.x + s->slice.width == s->img->width, s);
3305 /* If there is no mask, the background won't be seen,
3306 so draw a rectangle on the image for the cursor.
3307 Do this for all images, getting transparency right is not reliable. */
3308 if (s->hl == DRAW_CURSOR)
3310 int thickness = abs (s->img->relief);
3311 if (thickness == 0) thickness = 1;
3312 ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3318 ns_dumpglyphs_stretch (struct glyph_string *s)
3323 NSColor *fgCol, *bgCol;
3325 if (!s->background_filled_p)
3327 n = ns_get_glyph_string_clip_rect (s, r);
3328 *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3330 ns_focus (s->f, r, n);
3332 if (s->hl == DRAW_MOUSE_FACE)
3334 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3336 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3339 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3341 bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3342 fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3344 for (i = 0; i < n; ++i)
3346 if (!s->row->full_width_p)
3348 int overrun, leftoverrun;
3350 /* truncate to avoid overwriting fringe and/or scrollbar */
3351 overrun = max (0, (s->x + s->background_width)
3352 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3353 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3354 r[i].size.width -= overrun;
3356 /* truncate to avoid overwriting to left of the window box */
3357 leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3358 + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3360 if (leftoverrun > 0)
3362 r[i].origin.x += leftoverrun;
3363 r[i].size.width -= leftoverrun;
3366 /* XXX: Try to work between problem where a stretch glyph on
3367 a partially-visible bottom row will clear part of the
3368 modeline, and another where list-buffers headers and similar
3369 rows erroneously have visible_height set to 0. Not sure
3370 where this is coming from as other terms seem not to show. */
3371 r[i].size.height = min (s->height, s->row->visible_height);
3376 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3377 overwriting cursor (usually when cursor on a tab) */
3378 if (s->hl == DRAW_CURSOR)
3383 width = s->w->phys_cursor_width;
3384 r[i].size.width -= width;
3385 r[i].origin.x += width;
3389 /* Draw overlining, etc. on the cursor. */
3390 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3391 ns_draw_text_decoration (s, face, bgCol, width, x);
3393 ns_draw_text_decoration (s, face, fgCol, width, x);
3400 /* Draw overlining, etc. on the stretch glyph (or the part
3401 of the stretch glyph after the cursor). */
3402 ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3406 s->background_filled_p = 1;
3412 ns_draw_composite_glyph_string_foreground (struct glyph_string *s)
3415 struct font *font = s->font;
3417 /* If first glyph of S has a left box line, start drawing the text
3418 of S to the right of that box line. */
3419 if (s->face && s->face->box != FACE_NO_BOX
3420 && s->first_glyph->left_box_line_p)
3421 x = s->x + eabs (s->face->box_line_width);
3425 /* S is a glyph string for a composition. S->cmp_from is the index
3426 of the first character drawn for glyphs of this composition.
3427 S->cmp_from == 0 means we are drawing the very first character of
3428 this composition. */
3430 /* Draw a rectangle for the composition if the font for the very
3431 first character of the composition could not be loaded. */
3432 if (s->font_not_found_p)
3434 if (s->cmp_from == 0)
3436 NSRect r = NSMakeRect (s->x, s->y, s->width-1, s->height -1);
3437 ns_draw_box (r, 1, FRAME_CURSOR_COLOR (s->f), 1, 1);
3440 else if (! s->first_glyph->u.cmp.automatic)
3444 for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
3445 /* TAB in a composition means display glyphs with padding
3446 space on the left or right. */
3447 if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
3449 int xx = x + s->cmp->offsets[j * 2];
3450 int yy = y - s->cmp->offsets[j * 2 + 1];
3452 font->driver->draw (s, j, j + 1, xx, yy, false);
3453 if (s->face->overstrike)
3454 font->driver->draw (s, j, j + 1, xx + 1, yy, false);
3459 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
3464 for (i = j = s->cmp_from; i < s->cmp_to; i++)
3466 glyph = LGSTRING_GLYPH (gstring, i);
3467 if (NILP (LGLYPH_ADJUSTMENT (glyph)))
3468 width += LGLYPH_WIDTH (glyph);
3471 int xoff, yoff, wadjust;
3475 font->driver->draw (s, j, i, x, y, false);
3476 if (s->face->overstrike)
3477 font->driver->draw (s, j, i, x + 1, y, false);
3480 xoff = LGLYPH_XOFF (glyph);
3481 yoff = LGLYPH_YOFF (glyph);
3482 wadjust = LGLYPH_WADJUST (glyph);
3483 font->driver->draw (s, i, i + 1, x + xoff, y + yoff, false);
3484 if (s->face->overstrike)
3485 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff,
3494 font->driver->draw (s, j, i, x, y, false);
3495 if (s->face->overstrike)
3496 font->driver->draw (s, j, i, x + 1, y, false);
3502 ns_draw_glyph_string (struct glyph_string *s)
3503 /* --------------------------------------------------------------------------
3504 External (RIF): Main draw-text call.
3505 -------------------------------------------------------------------------- */
3507 /* TODO (optimize): focus for box and contents draw */
3510 char box_drawn_p = 0;
3511 struct font *font = s->face->font;
3512 if (! font) font = FRAME_FONT (s->f);
3514 NSTRACE ("ns_draw_glyph_string");
3516 if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3519 struct glyph_string *next;
3521 for (width = 0, next = s->next;
3522 next && width < s->right_overhang;
3523 width += next->width, next = next->next)
3524 if (next->first_glyph->type != IMAGE_GLYPH)
3526 if (next->first_glyph->type != STRETCH_GLYPH)
3528 n = ns_get_glyph_string_clip_rect (s->next, r);
3529 ns_focus (s->f, r, n);
3530 ns_maybe_dumpglyphs_background (s->next, 1);
3535 ns_dumpglyphs_stretch (s->next);
3537 next->num_clips = 0;
3541 if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3542 && (s->first_glyph->type == CHAR_GLYPH
3543 || s->first_glyph->type == COMPOSITE_GLYPH))
3545 n = ns_get_glyph_string_clip_rect (s, r);
3546 ns_focus (s->f, r, n);
3547 ns_maybe_dumpglyphs_background (s, 1);
3548 ns_dumpglyphs_box_or_relief (s);
3553 switch (s->first_glyph->type)
3557 n = ns_get_glyph_string_clip_rect (s, r);
3558 ns_focus (s->f, r, n);
3559 ns_dumpglyphs_image (s, r[0]);
3564 ns_dumpglyphs_stretch (s);
3568 case COMPOSITE_GLYPH:
3569 n = ns_get_glyph_string_clip_rect (s, r);
3570 ns_focus (s->f, r, n);
3572 if (s->for_overlaps || (s->cmp_from > 0
3573 && ! s->first_glyph->u.cmp.automatic))
3574 s->background_filled_p = 1;
3576 ns_maybe_dumpglyphs_background
3577 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3579 flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3580 (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3581 (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3582 NS_DUMPGLYPH_NORMAL));
3584 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3586 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3587 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3588 NS_FACE_FOREGROUND (s->face) = tmp;
3592 BOOL isComposite = s->first_glyph->type == COMPOSITE_GLYPH;
3595 ns_draw_composite_glyph_string_foreground (s);
3598 (s, s->cmp_from, s->nchars, s->x, s->ybase,
3599 (flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3600 || flags == NS_DUMPGLYPH_MOUSEFACE);
3604 NSColor *col = (NS_FACE_FOREGROUND (s->face) != 0
3605 ? ns_lookup_indexed_color (NS_FACE_FOREGROUND (s->face),
3607 : FRAME_FOREGROUND_COLOR (s->f));
3610 /* Draw underline, overline, strike-through. */
3611 ns_draw_text_decoration (s, s->face, col, s->width, s->x);
3614 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3616 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3617 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3618 NS_FACE_FOREGROUND (s->face) = tmp;
3624 case GLYPHLESS_GLYPH:
3625 n = ns_get_glyph_string_clip_rect (s, r);
3626 ns_focus (s->f, r, n);
3628 if (s->for_overlaps || (s->cmp_from > 0
3629 && ! s->first_glyph->u.cmp.automatic))
3630 s->background_filled_p = 1;
3632 ns_maybe_dumpglyphs_background
3633 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3635 /* Not yet implemented. */
3644 /* Draw box if not done already. */
3645 if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3647 n = ns_get_glyph_string_clip_rect (s, r);
3648 ns_focus (s->f, r, n);
3649 ns_dumpglyphs_box_or_relief (s);
3658 /* ==========================================================================
3662 ========================================================================== */
3666 ns_send_appdefined (int value)
3667 /* --------------------------------------------------------------------------
3668 Internal: post an appdefined event which EmacsApp-sendEvent will
3669 recognize and take as a command to halt the event loop.
3670 -------------------------------------------------------------------------- */
3672 NSTRACE ("ns_send_appdefined");
3674 #ifdef NS_IMPL_GNUSTEP
3675 // GNUstep needs postEvent to happen on the main thread.
3676 if (! [[NSThread currentThread] isMainThread])
3678 EmacsApp *app = (EmacsApp *)NSApp;
3679 app->nextappdefined = value;
3680 [app performSelectorOnMainThread:@selector (sendFromMainThread:)
3687 /* Only post this event if we haven't already posted one. This will end
3688 the [NXApp run] main loop after having processed all events queued at
3691 #ifdef NS_IMPL_COCOA
3692 if (! send_appdefined)
3694 /* OSX 10.10.1 swallows the AppDefined event we are sending ourselves
3695 in certain situations (rapid incoming events).
3696 So check if we have one, if not add one. */
3697 NSEvent *appev = [NSApp nextEventMatchingMask:NSApplicationDefinedMask
3698 untilDate:[NSDate distantPast]
3699 inMode:NSDefaultRunLoopMode
3701 if (! appev) send_appdefined = YES;
3705 if (send_appdefined)
3709 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
3710 send_appdefined = NO;
3712 /* Don't need wakeup timer any more */
3715 [timed_entry invalidate];
3716 [timed_entry release];
3720 nxev = [NSEvent otherEventWithType: NSApplicationDefined
3721 location: NSMakePoint (0, 0)
3724 windowNumber: [[NSApp mainWindow] windowNumber]
3725 context: [NSApp context]
3730 /* Post an application defined event on the event queue. When this is
3731 received the [NXApp run] will return, thus having processed all
3732 events which are currently queued. */
3733 [NSApp postEvent: nxev atStart: NO];
3737 #ifdef HAVE_NATIVE_FS
3741 Lisp_Object frame, tail;
3743 if (ns_last_use_native_fullscreen == ns_use_native_fullscreen)
3746 ns_last_use_native_fullscreen = ns_use_native_fullscreen;
3748 FOR_EACH_FRAME (tail, frame)
3750 struct frame *f = XFRAME (frame);
3753 EmacsView *view = FRAME_NS_VIEW (f);
3754 [view updateCollectionBehavior];
3760 /* GNUstep does not have cancelTracking. */
3761 #ifdef NS_IMPL_COCOA
3762 /* Check if menu open should be canceled or continued as normal. */
3764 ns_check_menu_open (NSMenu *menu)
3766 /* Click in menu bar? */
3767 NSArray *a = [[NSApp mainMenu] itemArray];
3771 if (menu == nil) // Menu tracking ended.
3773 if (menu_will_open_state == MENU_OPENING)
3774 menu_will_open_state = MENU_NONE;
3778 for (i = 0; ! found && i < [a count]; i++)
3779 found = menu == [[a objectAtIndex:i] submenu];
3782 if (menu_will_open_state == MENU_NONE && emacs_event)
3784 NSEvent *theEvent = [NSApp currentEvent];
3785 struct frame *emacsframe = SELECTED_FRAME ();
3787 [menu cancelTracking];
3788 menu_will_open_state = MENU_PENDING;
3789 emacs_event->kind = MENU_BAR_ACTIVATE_EVENT;
3790 EV_TRAILER (theEvent);
3792 CGEventRef ourEvent = CGEventCreate (NULL);
3793 menu_mouse_point = CGEventGetLocation (ourEvent);
3794 CFRelease (ourEvent);
3796 else if (menu_will_open_state == MENU_OPENING)
3798 menu_will_open_state = MENU_NONE;
3803 /* Redo saved menu click if state is MENU_PENDING. */
3805 ns_check_pending_open_menu ()
3807 if (menu_will_open_state == MENU_PENDING)
3809 CGEventSourceRef source
3810 = CGEventSourceCreate (kCGEventSourceStateHIDSystemState);
3812 CGEventRef event = CGEventCreateMouseEvent (source,
3813 kCGEventLeftMouseDown,
3815 kCGMouseButtonLeft);
3816 CGEventSetType (event, kCGEventLeftMouseDown);
3817 CGEventPost (kCGHIDEventTap, event);
3821 menu_will_open_state = MENU_OPENING;
3824 #endif /* NS_IMPL_COCOA */
3827 unwind_apploopnr (Lisp_Object not_used)
3830 n_emacs_events_pending = 0;
3831 ns_finish_events ();
3836 ns_read_socket (struct terminal *terminal, struct input_event *hold_quit)
3837 /* --------------------------------------------------------------------------
3838 External (hook): Post an event to ourself and keep reading events until
3839 we read it back again. In effect process all events which were waiting.
3840 From 21+ we have to manage the event buffer ourselves.
3841 -------------------------------------------------------------------------- */
3843 struct input_event ev;
3846 /* NSTRACE ("ns_read_socket"); */
3848 #ifdef HAVE_NATIVE_FS
3852 if ([NSApp modalWindow] != nil)
3855 if (hold_event_q.nr > 0)
3858 for (i = 0; i < hold_event_q.nr; ++i)
3859 kbd_buffer_store_event_hold (&hold_event_q.q[i], hold_quit);
3860 hold_event_q.nr = 0;
3865 n_emacs_events_pending = 0;
3866 ns_init_events (&ev);
3867 q_event_ptr = hold_quit;
3869 /* we manage autorelease pools by allocate/reallocate each time around
3870 the loop; strict nesting is occasionally violated but seems not to
3871 matter.. earlier methods using full nesting caused major memory leaks */
3872 [outerpool release];
3873 outerpool = [[NSAutoreleasePool alloc] init];
3875 /* If have pending open-file requests, attend to the next one of those. */
3876 if (ns_pending_files && [ns_pending_files count] != 0
3877 && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3879 [ns_pending_files removeObjectAtIndex: 0];
3881 /* Deal with pending service requests. */
3882 else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3884 NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3885 withArg: [ns_pending_service_args objectAtIndex: 0]])
3887 [ns_pending_service_names removeObjectAtIndex: 0];
3888 [ns_pending_service_args removeObjectAtIndex: 0];
3892 ptrdiff_t specpdl_count = SPECPDL_INDEX ();
3893 /* Run and wait for events. We must always send one NX_APPDEFINED event
3894 to ourself, otherwise [NXApp run] will never exit. */
3895 send_appdefined = YES;
3896 ns_send_appdefined (-1);
3898 if (++apploopnr != 1)
3902 record_unwind_protect (unwind_apploopnr, Qt);
3904 unbind_to (specpdl_count, Qnil); /* calls unwind_apploopnr */
3907 nevents = n_emacs_events_pending;
3908 n_emacs_events_pending = 0;
3909 ns_finish_events ();
3918 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3919 fd_set *exceptfds, struct timespec const *timeout,
3920 sigset_t const *sigmask)
3921 /* --------------------------------------------------------------------------
3922 Replacement for select, checking for events
3923 -------------------------------------------------------------------------- */
3927 struct input_event event;
3930 /* NSTRACE ("ns_select"); */
3932 #ifdef HAVE_NATIVE_FS
3936 if (hold_event_q.nr > 0)
3938 /* We already have events pending. */
3944 for (k = 0; k < nfds+1; k++)
3946 if (readfds && FD_ISSET(k, readfds)) ++nr;
3947 if (writefds && FD_ISSET(k, writefds)) ++nr;
3951 || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0))
3952 return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
3954 [outerpool release];
3955 outerpool = [[NSAutoreleasePool alloc] init];
3958 send_appdefined = YES;
3961 pthread_mutex_lock (&select_mutex);
3966 select_readfds = *readfds;
3967 select_valid += SELECT_HAVE_READ;
3971 select_writefds = *writefds;
3972 select_valid += SELECT_HAVE_WRITE;
3977 select_timeout = *timeout;
3978 select_valid += SELECT_HAVE_TMO;
3981 pthread_mutex_unlock (&select_mutex);
3983 /* Inform fd_handler that select should be called */
3985 emacs_write_sig (selfds[1], &c, 1);
3987 else if (nr == 0 && timeout)
3989 /* No file descriptor, just a timeout, no need to wake fd_handler */
3990 double time = timespectod (*timeout);
3991 timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3994 @selector (timeout_handler:)
3999 else /* No timeout and no file descriptors, can this happen? */
4001 /* Send appdefined so we exit from the loop */
4002 ns_send_appdefined (-1);
4006 ns_init_events (&event);
4007 if (++apploopnr != 1)
4013 ptrdiff_t specpdl_count = SPECPDL_INDEX ();
4014 record_unwind_protect (unwind_apploopnr, Qt);
4016 unbind_to (specpdl_count, Qnil); /* calls unwind_apploopnr */
4019 ns_finish_events ();
4020 if (nr > 0 && readfds)
4023 emacs_write_sig (selfds[1], &c, 1);
4027 t = last_appdefined_event_data;
4029 if (t != NO_APPDEFINED_DATA)
4031 last_appdefined_event_data = NO_APPDEFINED_DATA;
4035 /* The NX_APPDEFINED event we received was a timeout. */
4040 /* The NX_APPDEFINED event we received was the result of
4041 at least one real input event arriving. */
4047 /* Received back from select () in fd_handler; copy the results */
4048 pthread_mutex_lock (&select_mutex);
4049 if (readfds) *readfds = select_readfds;
4050 if (writefds) *writefds = select_writefds;
4051 pthread_mutex_unlock (&select_mutex);
4066 /* ==========================================================================
4070 ========================================================================== */
4074 ns_set_vertical_scroll_bar (struct window *window,
4075 int portion, int whole, int position)
4076 /* --------------------------------------------------------------------------
4077 External (hook): Update or add scrollbar
4078 -------------------------------------------------------------------------- */
4082 struct frame *f = XFRAME (WINDOW_FRAME (window));
4083 EmacsView *view = FRAME_NS_VIEW (f);
4085 int window_y, window_height;
4086 int top, left, height, width;
4087 BOOL update_p = YES;
4089 /* optimization; display engine sends WAY too many of these.. */
4090 if (!NILP (window->vertical_scroll_bar))
4092 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4093 if ([bar checkSamePosition: position portion: portion whole: whole])
4095 if (view->scrollbarsNeedingUpdate == 0)
4097 if (!windows_or_buffers_changed)
4101 view->scrollbarsNeedingUpdate--;
4106 NSTRACE ("ns_set_vertical_scroll_bar");
4108 /* Get dimensions. */
4109 window_box (window, ANY_AREA, 0, &window_y, 0, &window_height);
4111 height = window_height;
4112 width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
4113 left = WINDOW_SCROLL_BAR_AREA_X (window);
4115 r = NSMakeRect (left, top, width, height);
4116 /* the parent view is flipped, so we need to flip y value */
4118 r.origin.y = (v.size.height - r.size.height - r.origin.y);
4120 XSETWINDOW (win, window);
4123 /* we want at least 5 lines to display a scrollbar */
4124 if (WINDOW_TOTAL_LINES (window) < 5)
4126 if (!NILP (window->vertical_scroll_bar))
4128 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4129 [bar removeFromSuperview];
4130 wset_vertical_scroll_bar (window, Qnil);
4133 ns_clear_frame_area (f, left, top, width, height);
4138 if (NILP (window->vertical_scroll_bar))
4140 if (width > 0 && height > 0)
4141 ns_clear_frame_area (f, left, top, width, height);
4143 bar = [[EmacsScroller alloc] initFrame: r window: win];
4144 wset_vertical_scroll_bar (window, make_save_ptr (bar));
4150 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4151 oldRect = [bar frame];
4152 r.size.width = oldRect.size.width;
4153 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4155 if (oldRect.origin.x != r.origin.x)
4156 ns_clear_frame_area (f, left, top, width, height);
4162 [bar setPosition: position portion: portion whole: whole];
4168 ns_set_horizontal_scroll_bar (struct window *window,
4169 int portion, int whole, int position)
4170 /* --------------------------------------------------------------------------
4171 External (hook): Update or add scrollbar
4172 -------------------------------------------------------------------------- */
4176 struct frame *f = XFRAME (WINDOW_FRAME (window));
4177 EmacsView *view = FRAME_NS_VIEW (f);
4179 int top, height, left, width;
4180 int window_x, window_width;
4181 BOOL update_p = YES;
4183 /* optimization; display engine sends WAY too many of these.. */
4184 if (!NILP (window->horizontal_scroll_bar))
4186 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4187 if ([bar checkSamePosition: position portion: portion whole: whole])
4189 if (view->scrollbarsNeedingUpdate == 0)
4191 if (!windows_or_buffers_changed)
4195 view->scrollbarsNeedingUpdate--;
4200 NSTRACE ("ns_set_horizontal_scroll_bar");
4202 /* Get dimensions. */
4203 window_box (window, ANY_AREA, 0, &window_x, &window_width, 0);
4205 width = window_width;
4206 height = WINDOW_CONFIG_SCROLL_BAR_LINES (window) * FRAME_LINE_HEIGHT (f);
4207 top = WINDOW_SCROLL_BAR_AREA_Y (window);
4209 r = NSMakeRect (left, top, width, height);
4210 /* the parent view is flipped, so we need to flip y value */
4212 /* ??????? PXW/scrollbars !!!!!!!!!!!!!!!!!!!! */
4213 r.origin.y = (v.size.height - r.size.height - r.origin.y);
4215 XSETWINDOW (win, window);
4218 if (WINDOW_TOTAL_COLS (window) < 5)
4220 if (!NILP (window->horizontal_scroll_bar))
4222 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4223 [bar removeFromSuperview];
4224 wset_horizontal_scroll_bar (window, Qnil);
4226 ns_clear_frame_area (f, left, top, width, height);
4231 if (NILP (window->horizontal_scroll_bar))
4233 if (width > 0 && height > 0)
4234 ns_clear_frame_area (f, left, top, width, height);
4236 bar = [[EmacsScroller alloc] initFrame: r window: win];
4237 wset_horizontal_scroll_bar (window, make_save_ptr (bar));
4243 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4244 oldRect = [bar frame];
4245 r.size.width = oldRect.size.width;
4246 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4248 if (oldRect.origin.x != r.origin.x)
4249 ns_clear_frame_area (f, left, top, width, height);
4256 [bar setPosition: position portion: portion whole: whole];
4262 ns_condemn_scroll_bars (struct frame *f)
4263 /* --------------------------------------------------------------------------
4264 External (hook): arrange for all frame's scrollbars to be removed
4265 at next call to judge_scroll_bars, except for those redeemed.
4266 -------------------------------------------------------------------------- */
4270 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
4272 NSTRACE ("ns_condemn_scroll_bars");
4274 for (i =[subviews count]-1; i >= 0; i--)
4276 view = [subviews objectAtIndex: i];
4277 if ([view isKindOfClass: [EmacsScroller class]])
4284 ns_redeem_scroll_bar (struct window *window)
4285 /* --------------------------------------------------------------------------
4286 External (hook): arrange to spare this window's scrollbar
4287 at next call to judge_scroll_bars.
4288 -------------------------------------------------------------------------- */
4291 NSTRACE ("ns_redeem_scroll_bar");
4292 if (!NILP (window->vertical_scroll_bar))
4294 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4298 if (!NILP (window->horizontal_scroll_bar))
4300 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4307 ns_judge_scroll_bars (struct frame *f)
4308 /* --------------------------------------------------------------------------
4309 External (hook): destroy all scrollbars on frame that weren't
4310 redeemed after call to condemn_scroll_bars.
4311 -------------------------------------------------------------------------- */
4315 EmacsView *eview = FRAME_NS_VIEW (f);
4316 NSArray *subviews = [[eview superview] subviews];
4319 NSTRACE ("ns_judge_scroll_bars");
4320 for (i = [subviews count]-1; i >= 0; --i)
4322 view = [subviews objectAtIndex: i];
4323 if (![view isKindOfClass: [EmacsScroller class]]) continue;
4329 [eview updateFrameSize: NO];
4332 /* ==========================================================================
4336 ========================================================================== */
4339 x_display_pixel_height (struct ns_display_info *dpyinfo)
4341 NSArray *screens = [NSScreen screens];
4342 NSEnumerator *enumerator = [screens objectEnumerator];
4347 while ((screen = [enumerator nextObject]) != nil)
4348 frame = NSUnionRect (frame, [screen frame]);
4350 return NSHeight (frame);
4354 x_display_pixel_width (struct ns_display_info *dpyinfo)
4356 NSArray *screens = [NSScreen screens];
4357 NSEnumerator *enumerator = [screens objectEnumerator];
4362 while ((screen = [enumerator nextObject]) != nil)
4363 frame = NSUnionRect (frame, [screen frame]);
4365 return NSWidth (frame);
4369 static Lisp_Object ns_string_to_lispmod (const char *s)
4370 /* --------------------------------------------------------------------------
4371 Convert modifier name to lisp symbol
4372 -------------------------------------------------------------------------- */
4374 if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
4376 else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
4378 else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
4380 else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
4382 else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
4384 else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
4392 ns_default (const char *parameter, Lisp_Object *result,
4393 Lisp_Object yesval, Lisp_Object noval,
4394 BOOL is_float, BOOL is_modstring)
4395 /* --------------------------------------------------------------------------
4396 Check a parameter value in user's preferences
4397 -------------------------------------------------------------------------- */
4399 const char *value = ns_get_defaults_value (parameter);
4405 if (c_strcasecmp (value, "YES") == 0)
4407 else if (c_strcasecmp (value, "NO") == 0)
4409 else if (is_float && (f = strtod (value, &pos), pos != value))
4410 *result = make_float (f);
4411 else if (is_modstring && value)
4412 *result = ns_string_to_lispmod (value);
4413 else fprintf (stderr,
4414 "Bad value for default \"%s\": \"%s\"\n", parameter, value);
4420 ns_initialize_display_info (struct ns_display_info *dpyinfo)
4421 /* --------------------------------------------------------------------------
4422 Initialize global info and storage for display.
4423 -------------------------------------------------------------------------- */
4425 NSScreen *screen = [NSScreen mainScreen];
4426 NSWindowDepth depth = [screen depth];
4428 dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
4429 dpyinfo->resy = 72.27;
4430 dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
4431 NSColorSpaceFromDepth (depth)]
4432 && ![NSCalibratedWhiteColorSpace isEqualToString:
4433 NSColorSpaceFromDepth (depth)];
4434 dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
4435 dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
4436 dpyinfo->color_table->colors = NULL;
4437 dpyinfo->root_window = 42; /* a placeholder.. */
4438 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
4439 dpyinfo->n_fonts = 0;
4440 dpyinfo->smallest_font_height = 1;
4441 dpyinfo->smallest_char_width = 1;
4443 reset_mouse_highlight (&dpyinfo->mouse_highlight);
4447 /* This and next define (many of the) public functions in this file. */
4448 /* x_... are generic versions in xdisp.c that we, and other terms, get away
4449 with using despite presence in the "system dependent" redisplay
4450 interface. In addition, many of the ns_ methods have code that is
4451 shared with all terms, indicating need for further refactoring. */
4452 extern frame_parm_handler ns_frame_parm_handlers[];
4453 static struct redisplay_interface ns_redisplay_interface =
4455 ns_frame_parm_handlers,
4459 x_clear_end_of_line,
4461 ns_after_update_window_line,
4462 ns_update_window_begin,
4463 ns_update_window_end,
4464 0, /* flush_display */
4465 x_clear_window_mouse_face,
4466 x_get_glyph_overhangs,
4467 x_fix_overlapping_area,
4468 ns_draw_fringe_bitmap,
4469 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
4470 0, /* destroy_fringe_bitmap */
4471 ns_compute_glyph_string_overhangs,
4472 ns_draw_glyph_string,
4473 ns_define_frame_cursor,
4474 ns_clear_frame_area,
4475 ns_draw_window_cursor,
4476 ns_draw_vertical_window_border,
4477 ns_draw_window_divider,
4478 ns_shift_glyphs_for_insert,
4485 ns_delete_display (struct ns_display_info *dpyinfo)
4491 /* This function is called when the last frame on a display is deleted. */
4493 ns_delete_terminal (struct terminal *terminal)
4495 struct ns_display_info *dpyinfo = terminal->display_info.ns;
4497 NSTRACE ("ns_delete_terminal");
4499 /* Protect against recursive calls. delete_frame in
4500 delete_terminal calls us back when it deletes our last frame. */
4501 if (!terminal->name)
4506 x_destroy_all_bitmaps (dpyinfo);
4507 ns_delete_display (dpyinfo);
4512 static struct terminal *
4513 ns_create_terminal (struct ns_display_info *dpyinfo)
4514 /* --------------------------------------------------------------------------
4515 Set up use of NS before we make the first connection.
4516 -------------------------------------------------------------------------- */
4518 struct terminal *terminal;
4520 NSTRACE ("ns_create_terminal");
4522 terminal = create_terminal (output_ns, &ns_redisplay_interface);
4524 terminal->display_info.ns = dpyinfo;
4525 dpyinfo->terminal = terminal;
4527 terminal->clear_frame_hook = ns_clear_frame;
4528 terminal->ring_bell_hook = ns_ring_bell;
4529 terminal->update_begin_hook = ns_update_begin;
4530 terminal->update_end_hook = ns_update_end;
4531 terminal->read_socket_hook = ns_read_socket;
4532 terminal->frame_up_to_date_hook = ns_frame_up_to_date;
4533 terminal->mouse_position_hook = ns_mouse_position;
4534 terminal->frame_rehighlight_hook = ns_frame_rehighlight;
4535 terminal->frame_raise_lower_hook = ns_frame_raise_lower;
4536 terminal->fullscreen_hook = ns_fullscreen_hook;
4537 terminal->menu_show_hook = ns_menu_show;
4538 terminal->popup_dialog_hook = ns_popup_dialog;
4539 terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
4540 terminal->set_horizontal_scroll_bar_hook = ns_set_horizontal_scroll_bar;
4541 terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
4542 terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
4543 terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
4544 terminal->delete_frame_hook = x_destroy_window;
4545 terminal->delete_terminal_hook = ns_delete_terminal;
4546 /* Other hooks are NULL by default. */
4552 struct ns_display_info *
4553 ns_term_init (Lisp_Object display_name)
4554 /* --------------------------------------------------------------------------
4555 Start the Application and get things rolling.
4556 -------------------------------------------------------------------------- */
4558 struct terminal *terminal;
4559 struct ns_display_info *dpyinfo;
4560 static int ns_initialized = 0;
4563 if (ns_initialized) return x_display_list;
4568 NSTRACE ("ns_term_init");
4570 [outerpool release];
4571 outerpool = [[NSAutoreleasePool alloc] init];
4573 /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4574 /*GSDebugAllocationActive (YES); */
4578 Fset_input_interrupt_mode (Qnil);
4580 if (selfds[0] == -1)
4582 if (emacs_pipe (selfds) != 0)
4584 fprintf (stderr, "Failed to create pipe: %s\n",
4585 emacs_strerror (errno));
4589 fcntl (selfds[0], F_SETFL, O_NONBLOCK|fcntl (selfds[0], F_GETFL));
4590 FD_ZERO (&select_readfds);
4591 FD_ZERO (&select_writefds);
4592 pthread_mutex_init (&select_mutex, NULL);
4595 ns_pending_files = [[NSMutableArray alloc] init];
4596 ns_pending_service_names = [[NSMutableArray alloc] init];
4597 ns_pending_service_args = [[NSMutableArray alloc] init];
4599 /* Start app and create the main menu, window, view.
4600 Needs to be here because ns_initialize_display_info () uses AppKit classes.
4601 The view will then ask the NSApp to stop and return to Emacs. */
4602 [EmacsApp sharedApplication];
4605 [NSApp setDelegate: NSApp];
4607 /* Start the select thread. */
4608 [NSThread detachNewThreadSelector:@selector (fd_handler:)
4612 /* debugging: log all notifications */
4613 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
4614 selector: @selector (logNotification:)
4615 name: nil object: nil]; */
4617 dpyinfo = xzalloc (sizeof *dpyinfo);
4619 ns_initialize_display_info (dpyinfo);
4620 terminal = ns_create_terminal (dpyinfo);
4622 terminal->kboard = allocate_kboard (Qns);
4623 /* Don't let the initial kboard remain current longer than necessary.
4624 That would cause problems if a file loaded on startup tries to
4625 prompt in the mini-buffer. */
4626 if (current_kboard == initial_kboard)
4627 current_kboard = terminal->kboard;
4628 terminal->kboard->reference_count++;
4630 dpyinfo->next = x_display_list;
4631 x_display_list = dpyinfo;
4633 dpyinfo->name_list_element = Fcons (display_name, Qnil);
4635 terminal->name = xlispstrdup (display_name);
4639 if (!inhibit_x_resources)
4641 ns_default ("GSFontAntiAlias", &ns_antialias_text,
4644 /* this is a standard variable */
4645 ns_default ("AppleAntiAliasingThreshold", &tmp,
4646 make_float (10.0), make_float (6.0), YES, NO);
4647 ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4650 NSTRACE_MSG ("Colors");
4653 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4657 Lisp_Object color_file, color_map, color;
4661 color_file = Fexpand_file_name (build_string ("rgb.txt"),
4662 Fsymbol_value (intern ("data-directory")));
4664 color_map = Fx_load_color_file (color_file);
4665 if (NILP (color_map))
4666 fatal ("Could not read %s.\n", SDATA (color_file));
4668 cl = [[NSColorList alloc] initWithName: @"Emacs"];
4669 for ( ; CONSP (color_map); color_map = XCDR (color_map))
4671 color = XCAR (color_map);
4672 name = SSDATA (XCAR (color));
4673 c = XINT (XCDR (color));
4675 [NSColor colorForEmacsRed: RED_FROM_ULONG (c) / 255.0
4676 green: GREEN_FROM_ULONG (c) / 255.0
4677 blue: BLUE_FROM_ULONG (c) / 255.0
4679 forKey: [NSString stringWithUTF8String: name]];
4681 [cl writeToFile: nil];
4685 NSTRACE_MSG ("Versions");
4688 #ifdef NS_IMPL_GNUSTEP
4689 Vwindow_system_version = build_string (gnustep_base_version);
4691 /*PSnextrelease (128, c); */
4692 char c[DBL_BUFSIZE_BOUND];
4693 int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4694 Vwindow_system_version = make_unibyte_string (c, len);
4698 delete_keyboard_wait_descriptor (0);
4700 ns_app_name = [[NSProcessInfo processInfo] processName];
4702 /* Set up OS X app menu */
4704 NSTRACE_MSG ("Menu init");
4706 #ifdef NS_IMPL_COCOA
4710 /* set up the application menu */
4711 svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4712 [svcsMenu setAutoenablesItems: NO];
4713 appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4714 [appMenu setAutoenablesItems: NO];
4715 mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4716 dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4718 [appMenu insertItemWithTitle: @"About Emacs"
4719 action: @selector (orderFrontStandardAboutPanel:)
4722 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4723 [appMenu insertItemWithTitle: @"Preferences..."
4724 action: @selector (showPreferencesWindow:)
4727 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4728 item = [appMenu insertItemWithTitle: @"Services"
4729 action: @selector (menuDown:)
4732 [appMenu setSubmenu: svcsMenu forItem: item];
4733 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4734 [appMenu insertItemWithTitle: @"Hide Emacs"
4735 action: @selector (hide:)
4738 item = [appMenu insertItemWithTitle: @"Hide Others"
4739 action: @selector (hideOtherApplications:)
4742 [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4743 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4744 [appMenu insertItemWithTitle: @"Quit Emacs"
4745 action: @selector (terminate:)
4749 item = [mainMenu insertItemWithTitle: ns_app_name
4750 action: @selector (menuDown:)
4753 [mainMenu setSubmenu: appMenu forItem: item];
4754 [dockMenu insertItemWithTitle: @"New Frame"
4755 action: @selector (newFrame:)
4759 [NSApp setMainMenu: mainMenu];
4760 [NSApp setAppleMenu: appMenu];
4761 [NSApp setServicesMenu: svcsMenu];
4762 /* Needed at least on Cocoa, to get dock menu to show windows */
4763 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4765 [[NSNotificationCenter defaultCenter]
4766 addObserver: mainMenu
4767 selector: @selector (trackingNotification:)
4768 name: NSMenuDidBeginTrackingNotification object: mainMenu];
4769 [[NSNotificationCenter defaultCenter]
4770 addObserver: mainMenu
4771 selector: @selector (trackingNotification:)
4772 name: NSMenuDidEndTrackingNotification object: mainMenu];
4774 #endif /* MAC OS X menu setup */
4776 /* Register our external input/output types, used for determining
4777 applicable services and also drag/drop eligibility. */
4779 NSTRACE_MSG ("Input/output types");
4781 ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
4782 ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
4784 ns_drag_types = [[NSArray arrayWithObjects:
4786 NSTabularTextPboardType,
4787 NSFilenamesPboardType,
4788 NSURLPboardType, nil] retain];
4790 /* If fullscreen is in init/default-frame-alist, focus isn't set
4791 right for fullscreen windows, so set this. */
4792 [NSApp activateIgnoringOtherApps:YES];
4794 NSTRACE_MSG ("Call NSApp run");
4797 ns_do_open_file = YES;
4799 #ifdef NS_IMPL_GNUSTEP
4800 /* GNUstep steals SIGCHLD for use in NSTask, but we don't use NSTask.
4801 We must re-catch it so subprocess works. */
4802 catch_child_signal ();
4805 NSTRACE_MSG ("ns_term_init done");
4814 ns_term_shutdown (int sig)
4816 [[NSUserDefaults standardUserDefaults] synchronize];
4818 /* code not reached in emacs.c after this is called by shut_down_emacs: */
4819 if (STRINGP (Vauto_save_list_file_name))
4820 unlink (SSDATA (Vauto_save_list_file_name));
4822 if (sig == 0 || sig == SIGTERM)
4824 [NSApp terminate: NSApp];
4826 else // force a stack trace to happen
4833 /* ==========================================================================
4835 EmacsApp implementation
4837 ========================================================================== */
4840 @implementation EmacsApp
4844 NSTRACE ("[EmacsApp init]");
4846 if ((self = [super init]))
4848 #ifdef NS_IMPL_COCOA
4849 self->isFirst = YES;
4851 #ifdef NS_IMPL_GNUSTEP
4852 self->applicationDidFinishLaunchingCalled = NO;
4859 #ifdef NS_IMPL_COCOA
4862 NSTRACE ("[EmacsApp run]");
4864 #ifndef NSAppKitVersionNumber10_9
4865 #define NSAppKitVersionNumber10_9 1265
4868 if ((int)NSAppKitVersionNumber != NSAppKitVersionNumber10_9)
4874 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
4876 if (isFirst) [self finishLaunching];
4879 shouldKeepRunning = YES;
4883 pool = [[NSAutoreleasePool alloc] init];
4886 [self nextEventMatchingMask:NSAnyEventMask
4887 untilDate:[NSDate distantFuture]
4888 inMode:NSDefaultRunLoopMode
4891 [self sendEvent:event];
4892 [self updateWindows];
4893 } while (shouldKeepRunning);
4898 - (void)stop: (id)sender
4900 NSTRACE ("[EmacsApp stop]");
4902 shouldKeepRunning = NO;
4903 // Stop possible dialog also. Noop if no dialog present.
4904 // The file dialog still leaks 7k - 10k on 10.9 though.
4905 [super stop:sender];
4907 #endif /* NS_IMPL_COCOA */
4909 - (void)logNotification: (NSNotification *)notification
4911 NSTRACE ("[EmacsApp logNotification]");
4913 const char *name = [[notification name] UTF8String];
4914 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4915 && !strstr (name, "WindowNumber"))
4916 NSLog (@"notification: '%@'", [notification name]);
4920 - (void)sendEvent: (NSEvent *)theEvent
4921 /* --------------------------------------------------------------------------
4922 Called when NSApp is running for each event received. Used to stop
4923 the loop when we choose, since there's no way to just run one iteration.
4924 -------------------------------------------------------------------------- */
4926 int type = [theEvent type];
4927 NSWindow *window = [theEvent window];
4929 NSTRACE ("[EmacsApp sendEvent]");
4930 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4932 #ifdef NS_IMPL_GNUSTEP
4933 // Keyboard events aren't propagated to file dialogs for some reason.
4934 if ([NSApp modalWindow] != nil &&
4935 (type == NSKeyDown || type == NSKeyUp || type == NSFlagsChanged))
4937 [[NSApp modalWindow] sendEvent: theEvent];
4942 if (represented_filename != nil && represented_frame)
4944 NSString *fstr = represented_filename;
4945 NSView *view = FRAME_NS_VIEW (represented_frame);
4946 #ifdef NS_IMPL_COCOA
4947 /* work around a bug observed on 10.3 and later where
4948 setTitleWithRepresentedFilename does not clear out previous state
4949 if given filename does not exist */
4950 if (! [[NSFileManager defaultManager] fileExistsAtPath: fstr])
4951 [[view window] setRepresentedFilename: @""];
4953 [[view window] setRepresentedFilename: fstr];
4954 [represented_filename release];
4955 represented_filename = nil;
4956 represented_frame = NULL;
4959 if (type == NSApplicationDefined)
4961 switch ([theEvent data2])
4963 #ifdef NS_IMPL_COCOA
4964 case NSAPP_DATA2_RUNASSCRIPT:
4969 case NSAPP_DATA2_RUNFILEDIALOG:
4970 ns_run_file_dialog ();
4976 if (type == NSCursorUpdate && window == nil)
4978 fprintf (stderr, "Dropping external cursor update event.\n");
4982 if (type == NSApplicationDefined)
4984 /* Events posted by ns_send_appdefined interrupt the run loop here.
4985 But, if a modal window is up, an appdefined can still come through,
4986 (e.g., from a makeKeyWindow event) but stopping self also stops the
4987 modal loop. Just defer it until later. */
4988 if ([NSApp modalWindow] == nil)
4990 last_appdefined_event_data = [theEvent data1];
4995 send_appdefined = YES;
5000 #ifdef NS_IMPL_COCOA
5001 /* If no dialog and none of our frames have focus and it is a move, skip it.
5002 It is a mouse move in an auxiliary menu, i.e. on the top right on OSX,
5003 such as Wifi, sound, date or similar.
5004 This prevents "spooky" highlighting in the frame under the menu. */
5005 if (type == NSMouseMoved && [NSApp modalWindow] == nil)
5007 struct ns_display_info *di;
5008 BOOL has_focus = NO;
5009 for (di = x_display_list; ! has_focus && di; di = di->next)
5010 has_focus = di->x_focus_frame != 0;
5016 [super sendEvent: theEvent];
5020 - (void)showPreferencesWindow: (id)sender
5022 struct frame *emacsframe = SELECTED_FRAME ();
5023 NSEvent *theEvent = [NSApp currentEvent];
5027 emacs_event->kind = NS_NONKEY_EVENT;
5028 emacs_event->code = KEY_NS_SHOW_PREFS;
5029 emacs_event->modifiers = 0;
5030 EV_TRAILER (theEvent);
5034 - (void)newFrame: (id)sender
5036 NSTRACE ("[EmacsApp newFrame]");
5038 struct frame *emacsframe = SELECTED_FRAME ();
5039 NSEvent *theEvent = [NSApp currentEvent];
5043 emacs_event->kind = NS_NONKEY_EVENT;
5044 emacs_event->code = KEY_NS_NEW_FRAME;
5045 emacs_event->modifiers = 0;
5046 EV_TRAILER (theEvent);
5050 /* Open a file (used by below, after going into queue read by ns_read_socket) */
5051 - (BOOL) openFile: (NSString *)fileName
5053 NSTRACE ("[EmacsApp openFile]");
5055 struct frame *emacsframe = SELECTED_FRAME ();
5056 NSEvent *theEvent = [NSApp currentEvent];
5061 emacs_event->kind = NS_NONKEY_EVENT;
5062 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
5063 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
5064 ns_input_line = Qnil; /* can be start or cons start,end */
5065 emacs_event->modifiers =0;
5066 EV_TRAILER (theEvent);
5072 /* **************************************************************************
5074 EmacsApp delegate implementation
5076 ************************************************************************** */
5078 - (void)applicationDidFinishLaunching: (NSNotification *)notification
5079 /* --------------------------------------------------------------------------
5080 When application is loaded, terminate event loop in ns_term_init
5081 -------------------------------------------------------------------------- */
5083 NSTRACE ("[EmacsApp applicationDidFinishLaunching]");
5085 #ifdef NS_IMPL_GNUSTEP
5086 ((EmacsApp *)self)->applicationDidFinishLaunchingCalled = YES;
5088 [NSApp setServicesProvider: NSApp];
5090 [self antialiasThresholdDidChange:nil];
5091 #ifdef NS_IMPL_COCOA
5092 [[NSNotificationCenter defaultCenter]
5094 selector:@selector(antialiasThresholdDidChange:)
5095 name:NSAntialiasThresholdChangedNotification
5099 ns_send_appdefined (-2);
5102 - (void)antialiasThresholdDidChange:(NSNotification *)notification
5104 #ifdef NS_IMPL_COCOA
5105 macfont_update_antialias_threshold ();
5110 /* Termination sequences:
5113 MenuBar | File | Exit:
5114 Select Quit from App menubar:
5116 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5119 Select Quit from Dock menu:
5122 Cancel -> Nothing else
5126 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5131 - (void) terminate: (id)sender
5133 NSTRACE ("[EmacsApp terminate]");
5135 struct frame *emacsframe = SELECTED_FRAME ();
5140 emacs_event->kind = NS_NONKEY_EVENT;
5141 emacs_event->code = KEY_NS_POWER_OFF;
5142 emacs_event->arg = Qt; /* mark as non-key event */
5143 EV_TRAILER ((id)nil);
5147 runAlertPanel(NSString *title,
5148 NSString *msgFormat,
5149 NSString *defaultButton,
5150 NSString *alternateButton)
5152 #if !defined (NS_IMPL_COCOA) || \
5153 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
5154 return NSRunAlertPanel(title, msgFormat, defaultButton, alternateButton, nil)
5155 == NSAlertDefaultReturn;
5157 NSAlert *alert = [[NSAlert alloc] init];
5158 [alert setAlertStyle: NSCriticalAlertStyle];
5159 [alert setMessageText: msgFormat];
5160 [alert addButtonWithTitle: defaultButton];
5161 [alert addButtonWithTitle: alternateButton];
5162 NSInteger ret = [alert runModal];
5164 return ret == NSAlertFirstButtonReturn;
5169 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
5171 NSTRACE ("[EmacsApp applicationShouldTerminate]");
5175 if (NILP (ns_confirm_quit)) // || ns_shutdown_properly --> TO DO
5176 return NSTerminateNow;
5178 ret = runAlertPanel(ns_app_name,
5179 @"Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?",
5180 @"Save Buffers and Exit", @"Cancel");
5183 return NSTerminateNow;
5185 return NSTerminateCancel;
5186 return NSTerminateNow; /* just in case */
5190 not_in_argv (NSString *arg)
5193 const char *a = [arg UTF8String];
5194 for (k = 1; k < initial_argc; ++k)
5195 if (strcmp (a, initial_argv[k]) == 0) return 0;
5199 /* Notification from the Workspace to open a file */
5200 - (BOOL)application: sender openFile: (NSString *)file
5202 if (ns_do_open_file || not_in_argv (file))
5203 [ns_pending_files addObject: file];
5208 /* Open a file as a temporary file */
5209 - (BOOL)application: sender openTempFile: (NSString *)file
5211 if (ns_do_open_file || not_in_argv (file))
5212 [ns_pending_files addObject: file];
5217 /* Notification from the Workspace to open a file noninteractively (?) */
5218 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
5220 if (ns_do_open_file || not_in_argv (file))
5221 [ns_pending_files addObject: file];
5225 /* Notification from the Workspace to open multiple files */
5226 - (void)application: sender openFiles: (NSArray *)fileList
5228 NSEnumerator *files = [fileList objectEnumerator];
5230 /* Don't open files from the command line unconditionally,
5231 Cocoa parses the command line wrong, --option value tries to open value
5232 if --option is the last option. */
5233 while ((file = [files nextObject]) != nil)
5234 if (ns_do_open_file || not_in_argv (file))
5235 [ns_pending_files addObject: file];
5237 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
5242 /* Handle dock menu requests. */
5243 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
5249 /* TODO: these may help w/IO switching btwn terminal and NSApp */
5250 - (void)applicationWillBecomeActive: (NSNotification *)notification
5252 NSTRACE ("[EmacsApp applicationWillBecomeActive]");
5253 //ns_app_active=YES;
5256 - (void)applicationDidBecomeActive: (NSNotification *)notification
5258 NSTRACE ("[EmacsApp applicationDidBecomeActive]");
5260 #ifdef NS_IMPL_GNUSTEP
5261 if (! applicationDidFinishLaunchingCalled)
5262 [self applicationDidFinishLaunching:notification];
5264 //ns_app_active=YES;
5266 ns_update_auto_hide_menu_bar ();
5267 // No constraining takes place when the application is not active.
5268 ns_constrain_all_frames ();
5270 - (void)applicationDidResignActive: (NSNotification *)notification
5272 NSTRACE ("[EmacsApp applicationDidResignActive]");
5275 ns_send_appdefined (-1);
5280 /* ==========================================================================
5282 EmacsApp aux handlers for managing event loop
5284 ========================================================================== */
5287 - (void)timeout_handler: (NSTimer *)timedEntry
5288 /* --------------------------------------------------------------------------
5289 The timeout specified to ns_select has passed.
5290 -------------------------------------------------------------------------- */
5292 /*NSTRACE ("timeout_handler"); */
5293 ns_send_appdefined (-2);
5296 #ifdef NS_IMPL_GNUSTEP
5297 - (void)sendFromMainThread:(id)unused
5299 ns_send_appdefined (nextappdefined);
5303 - (void)fd_handler:(id)unused
5304 /* --------------------------------------------------------------------------
5305 Check data waiting on file descriptors and terminate if so
5306 -------------------------------------------------------------------------- */
5309 int waiting = 1, nfds;
5312 fd_set readfds, writefds, *wfds;
5313 struct timespec timeout, *tmo;
5314 NSAutoreleasePool *pool = nil;
5316 /* NSTRACE ("fd_handler"); */
5321 pool = [[NSAutoreleasePool alloc] init];
5327 FD_SET (selfds[0], &fds);
5328 result = select (selfds[0]+1, &fds, NULL, NULL, NULL);
5329 if (result > 0 && read (selfds[0], &c, 1) == 1 && c == 'g')
5334 pthread_mutex_lock (&select_mutex);
5337 if (select_valid & SELECT_HAVE_READ)
5338 readfds = select_readfds;
5342 if (select_valid & SELECT_HAVE_WRITE)
5344 writefds = select_writefds;
5349 if (select_valid & SELECT_HAVE_TMO)
5351 timeout = select_timeout;
5357 pthread_mutex_unlock (&select_mutex);
5359 FD_SET (selfds[0], &readfds);
5360 if (selfds[0] >= nfds) nfds = selfds[0]+1;
5362 result = pselect (nfds, &readfds, wfds, NULL, tmo, NULL);
5365 ns_send_appdefined (-2);
5366 else if (result > 0)
5368 if (FD_ISSET (selfds[0], &readfds))
5370 if (read (selfds[0], &c, 1) == 1 && c == 's')
5375 pthread_mutex_lock (&select_mutex);
5376 if (select_valid & SELECT_HAVE_READ)
5377 select_readfds = readfds;
5378 if (select_valid & SELECT_HAVE_WRITE)
5379 select_writefds = writefds;
5380 if (select_valid & SELECT_HAVE_TMO)
5381 select_timeout = timeout;
5382 pthread_mutex_unlock (&select_mutex);
5384 ns_send_appdefined (result);
5394 /* ==========================================================================
5398 ========================================================================== */
5400 /* called from system: queue for next pass through event loop */
5401 - (void)requestService: (NSPasteboard *)pboard
5402 userData: (NSString *)userData
5403 error: (NSString **)error
5405 [ns_pending_service_names addObject: userData];
5406 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
5407 SSDATA (ns_string_from_pasteboard (pboard))]];
5411 /* called from ns_read_socket to clear queue */
5412 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
5414 struct frame *emacsframe = SELECTED_FRAME ();
5415 NSEvent *theEvent = [NSApp currentEvent];
5420 emacs_event->kind = NS_NONKEY_EVENT;
5421 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
5422 ns_input_spi_name = build_string ([name UTF8String]);
5423 ns_input_spi_arg = build_string ([arg UTF8String]);
5424 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5425 EV_TRAILER (theEvent);
5435 /* ==========================================================================
5437 EmacsView implementation
5439 ========================================================================== */
5442 @implementation EmacsView
5444 /* needed to inform when window closed from LISP */
5445 - (void) setWindowClosing: (BOOL)closing
5447 windowClosing = closing;
5453 NSTRACE ("EmacsView_dealloc");
5455 if (fs_state == FULLSCREEN_BOTH)
5456 [nonfs_window release];
5461 /* called on font panel selection */
5462 - (void)changeFont: (id)sender
5464 NSEvent *e = [[self window] currentEvent];
5465 struct face *face = FRAME_DEFAULT_FACE (emacsframe);
5466 struct font *font = face->font;
5471 NSTRACE ("changeFont");
5476 #ifdef NS_IMPL_GNUSTEP
5477 nsfont = ((struct nsfont_info *)font)->nsfont;
5479 #ifdef NS_IMPL_COCOA
5480 nsfont = (NSFont *) macfont_get_nsctfont (font);
5483 if ((newFont = [sender convertFont: nsfont]))
5485 SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
5487 emacs_event->kind = NS_NONKEY_EVENT;
5488 emacs_event->modifiers = 0;
5489 emacs_event->code = KEY_NS_CHANGE_FONT;
5491 size = [newFont pointSize];
5492 ns_input_fontsize = make_number (lrint (size));
5493 ns_input_font = build_string ([[newFont familyName] UTF8String]);
5499 - (BOOL)acceptsFirstResponder
5501 NSTRACE ("acceptsFirstResponder");
5506 - (void)resetCursorRects
5508 NSRect visible = [self visibleRect];
5509 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
5510 NSTRACE ("resetCursorRects");
5512 if (currentCursor == nil)
5513 currentCursor = [NSCursor arrowCursor];
5515 if (!NSIsEmptyRect (visible))
5516 [self addCursorRect: visible cursor: currentCursor];
5517 [currentCursor setOnMouseEntered: YES];
5522 /*****************************************************************************/
5523 /* Keyboard handling. */
5526 - (void)keyDown: (NSEvent *)theEvent
5528 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5530 unsigned fnKeysym = 0;
5531 static NSMutableArray *nsEvArray;
5533 unsigned int flags = [theEvent modifierFlags];
5535 NSTRACE ("keyDown");
5537 /* Rhapsody and OS X give up and down events for the arrow keys */
5538 if (ns_fake_keydown == YES)
5539 ns_fake_keydown = NO;
5540 else if ([theEvent type] != NSKeyDown)
5546 if (![[self window] isKeyWindow]
5547 && [[theEvent window] isKindOfClass: [EmacsWindow class]]
5548 /* we must avoid an infinite loop here. */
5549 && (EmacsView *)[[theEvent window] delegate] != self)
5551 /* XXX: There is an occasional condition in which, when Emacs display
5552 updates a different frame from the current one, and temporarily
5553 selects it, then processes some interrupt-driven input
5554 (dispnew.c:3878), OS will send the event to the correct NSWindow, but
5555 for some reason that window has its first responder set to the NSView
5556 most recently updated (I guess), which is not the correct one. */
5557 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
5561 if (nsEvArray == nil)
5562 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
5564 [NSCursor setHiddenUntilMouseMoves: YES];
5566 if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
5568 clear_mouse_face (hlinfo);
5569 hlinfo->mouse_face_hidden = 1;
5572 if (!processingCompose)
5574 /* When using screen sharing, no left or right information is sent,
5575 so use Left key in those cases. */
5576 int is_left_key, is_right_key;
5578 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
5579 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
5581 /* (Carbon way: [theEvent keyCode]) */
5583 /* is it a "function key"? */
5584 /* Note: Sometimes a plain key will have the NSNumericPadKeyMask
5585 flag set (this is probably a bug in the OS).
5587 if (code < 0x00ff && (flags&NSNumericPadKeyMask))
5589 fnKeysym = ns_convert_key ([theEvent keyCode] | NSNumericPadKeyMask);
5593 fnKeysym = ns_convert_key (code);
5598 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
5599 because Emacs treats Delete and KP-Delete same (in simple.el). */
5600 if ((fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
5601 #ifdef NS_IMPL_GNUSTEP
5602 /* GNUstep uses incompatible keycodes, even for those that are
5603 supposed to be hardware independent. Just check for delete.
5604 Keypad delete does not have keysym 0xFFFF.
5605 See http://savannah.gnu.org/bugs/?25395
5607 || (fnKeysym == 0xFFFF && code == 127)
5610 code = 0xFF08; /* backspace */
5615 /* are there modifiers? */
5616 emacs_event->modifiers = 0;
5618 if (flags & NSHelpKeyMask)
5619 emacs_event->modifiers |= hyper_modifier;
5621 if (flags & NSShiftKeyMask)
5622 emacs_event->modifiers |= shift_modifier;
5624 is_right_key = (flags & NSRightCommandKeyMask) == NSRightCommandKeyMask;
5625 is_left_key = (flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask
5626 || (! is_right_key && (flags & NSCommandKeyMask) == NSCommandKeyMask);
5629 emacs_event->modifiers |= parse_solitary_modifier
5630 (EQ (ns_right_command_modifier, Qleft)
5631 ? ns_command_modifier
5632 : ns_right_command_modifier);
5636 emacs_event->modifiers |= parse_solitary_modifier
5637 (ns_command_modifier);
5639 /* if super (default), take input manager's word so things like
5640 dvorak / qwerty layout work */
5641 if (EQ (ns_command_modifier, Qsuper)
5643 && [[theEvent characters] length] != 0)
5645 /* XXX: the code we get will be unshifted, so if we have
5646 a shift modifier, must convert ourselves */
5647 if (!(flags & NSShiftKeyMask))
5648 code = [[theEvent characters] characterAtIndex: 0];
5650 /* this is ugly and also requires linking w/Carbon framework
5651 (for LMGetKbdType) so for now leave this rare (?) case
5652 undealt with.. in future look into CGEvent methods */
5655 long smv = GetScriptManagerVariable (smKeyScript);
5656 Handle uchrHandle = GetResource
5657 ('uchr', GetScriptVariable (smv, smScriptKeys));
5659 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
5660 [[theEvent characters] characterAtIndex: 0],
5661 kUCKeyActionDisplay,
5662 (flags & ~NSCommandKeyMask) >> 8,
5663 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
5664 &dummy, 1, &dummy, &code);
5671 is_right_key = (flags & NSRightControlKeyMask) == NSRightControlKeyMask;
5672 is_left_key = (flags & NSLeftControlKeyMask) == NSLeftControlKeyMask
5673 || (! is_right_key && (flags & NSControlKeyMask) == NSControlKeyMask);
5676 emacs_event->modifiers |= parse_solitary_modifier
5677 (EQ (ns_right_control_modifier, Qleft)
5678 ? ns_control_modifier
5679 : ns_right_control_modifier);
5682 emacs_event->modifiers |= parse_solitary_modifier
5683 (ns_control_modifier);
5685 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
5686 emacs_event->modifiers |=
5687 parse_solitary_modifier (ns_function_modifier);
5689 left_is_none = NILP (ns_alternate_modifier)
5690 || EQ (ns_alternate_modifier, Qnone);
5692 is_right_key = (flags & NSRightAlternateKeyMask)
5693 == NSRightAlternateKeyMask;
5694 is_left_key = (flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask
5696 && (flags & NSAlternateKeyMask) == NSAlternateKeyMask);
5700 if ((NILP (ns_right_alternate_modifier)
5701 || EQ (ns_right_alternate_modifier, Qnone)
5702 || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
5704 { /* accept pre-interp alt comb */
5705 if ([[theEvent characters] length] > 0)
5706 code = [[theEvent characters] characterAtIndex: 0];
5707 /*HACK: clear lone shift modifier to stop next if from firing */
5708 if (emacs_event->modifiers == shift_modifier)
5709 emacs_event->modifiers = 0;
5712 emacs_event->modifiers |= parse_solitary_modifier
5713 (EQ (ns_right_alternate_modifier, Qleft)
5714 ? ns_alternate_modifier
5715 : ns_right_alternate_modifier);
5718 if (is_left_key) /* default = meta */
5720 if (left_is_none && !fnKeysym)
5721 { /* accept pre-interp alt comb */
5722 if ([[theEvent characters] length] > 0)
5723 code = [[theEvent characters] characterAtIndex: 0];
5724 /*HACK: clear lone shift modifier to stop next if from firing */
5725 if (emacs_event->modifiers == shift_modifier)
5726 emacs_event->modifiers = 0;
5729 emacs_event->modifiers |=
5730 parse_solitary_modifier (ns_alternate_modifier);
5734 fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
5735 code, fnKeysym, flags, emacs_event->modifiers);
5737 /* if it was a function key or had modifiers, pass it directly to emacs */
5738 if (fnKeysym || (emacs_event->modifiers
5739 && (emacs_event->modifiers != shift_modifier)
5740 && [[theEvent charactersIgnoringModifiers] length] > 0))
5741 /*[[theEvent characters] length] */
5743 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5745 code |= (1<<28)|(3<<16);
5746 else if (code == 0x7f)
5747 code |= (1<<28)|(3<<16);
5749 emacs_event->kind = code > 0xFF
5750 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5752 emacs_event->code = code;
5753 EV_TRAILER (theEvent);
5754 processingCompose = NO;
5760 if (NS_KEYLOG && !processingCompose)
5761 fprintf (stderr, "keyDown: Begin compose sequence.\n");
5763 processingCompose = YES;
5764 [nsEvArray addObject: theEvent];
5765 [self interpretKeyEvents: nsEvArray];
5766 [nsEvArray removeObject: theEvent];
5770 #ifdef NS_IMPL_COCOA
5771 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
5772 decided not to send key-down for.
5773 See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
5774 This only applies on Tiger and earlier.
5775 If it matches one of these, send it on to keyDown. */
5776 -(void)keyUp: (NSEvent *)theEvent
5778 int flags = [theEvent modifierFlags];
5779 int code = [theEvent keyCode];
5780 if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
5781 code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
5784 fprintf (stderr, "keyUp: passed test");
5785 ns_fake_keydown = YES;
5786 [self keyDown: theEvent];
5792 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
5795 /* <NSTextInput>: called when done composing;
5796 NOTE: also called when we delete over working text, followed immed.
5797 by doCommandBySelector: deleteBackward: */
5798 - (void)insertText: (id)aString
5801 int len = [(NSString *)aString length];
5805 NSLog (@"insertText '%@'\tlen = %d", aString, len);
5806 processingCompose = NO;
5811 /* first, clear any working text */
5812 if (workingText != nil)
5813 [self deleteWorkingText];
5815 /* now insert the string as keystrokes */
5816 for (i =0; i<len; i++)
5818 code = [aString characterAtIndex: i];
5819 /* TODO: still need this? */
5821 code = '~'; /* 0x7E */
5822 if (code != 32) /* Space */
5823 emacs_event->modifiers = 0;
5825 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5826 emacs_event->code = code;
5827 EV_TRAILER ((id)nil);
5832 /* <NSTextInput>: inserts display of composing characters */
5833 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
5835 NSString *str = [aString respondsToSelector: @selector (string)] ?
5836 [aString string] : aString;
5838 NSLog (@"setMarkedText '%@' len =%lu range %lu from %lu",
5839 str, (unsigned long)[str length],
5840 (unsigned long)selRange.length,
5841 (unsigned long)selRange.location);
5843 if (workingText != nil)
5844 [self deleteWorkingText];
5845 if ([str length] == 0)
5851 processingCompose = YES;
5852 workingText = [str copy];
5853 ns_working_text = build_string ([workingText UTF8String]);
5855 emacs_event->kind = NS_TEXT_EVENT;
5856 emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
5857 EV_TRAILER ((id)nil);
5861 /* delete display of composing characters [not in <NSTextInput>] */
5862 - (void)deleteWorkingText
5864 if (workingText == nil)
5867 NSLog(@"deleteWorkingText len =%lu\n", (unsigned long)[workingText length]);
5868 [workingText release];
5870 processingCompose = NO;
5875 emacs_event->kind = NS_TEXT_EVENT;
5876 emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
5877 EV_TRAILER ((id)nil);
5881 - (BOOL)hasMarkedText
5883 return workingText != nil;
5887 - (NSRange)markedRange
5889 NSRange rng = workingText != nil
5890 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
5892 NSLog (@"markedRange request");
5900 NSLog (@"unmark (accept) text");
5901 [self deleteWorkingText];
5902 processingCompose = NO;
5906 /* used to position char selection windows, etc. */
5907 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
5911 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
5913 NSLog (@"firstRectForCharRange request");
5915 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
5916 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
5917 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
5918 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
5919 +FRAME_LINE_HEIGHT (emacsframe));
5921 pt = [self convertPoint: pt toView: nil];
5922 pt = [[self window] convertBaseToScreen: pt];
5928 - (NSInteger)conversationIdentifier
5930 return (NSInteger)self;
5934 - (void)doCommandBySelector: (SEL)aSelector
5937 NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
5939 processingCompose = NO;
5940 if (aSelector == @selector (deleteBackward:))
5942 /* happens when user backspaces over an ongoing composition:
5943 throw a 'delete' into the event queue */
5946 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5947 emacs_event->code = 0xFF08;
5948 EV_TRAILER ((id)nil);
5952 - (NSArray *)validAttributesForMarkedText
5954 static NSArray *arr = nil;
5955 if (arr == nil) arr = [NSArray new];
5956 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
5960 - (NSRange)selectedRange
5963 NSLog (@"selectedRange request");
5964 return NSMakeRange (NSNotFound, 0);
5967 #if defined (NS_IMPL_COCOA) || GNUSTEP_GUI_MAJOR_VERSION > 0 || \
5968 GNUSTEP_GUI_MINOR_VERSION > 22
5969 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
5971 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
5975 NSLog (@"characterIndexForPoint request");
5979 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
5981 static NSAttributedString *str = nil;
5982 if (str == nil) str = [NSAttributedString new];
5984 NSLog (@"attributedSubstringFromRange request");
5988 /* End <NSTextInput> impl. */
5989 /*****************************************************************************/
5992 /* This is what happens when the user presses a mouse button. */
5993 - (void)mouseDown: (NSEvent *)theEvent
5995 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
5996 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5998 NSTRACE ("mouseDown");
6000 [self deleteWorkingText];
6005 dpyinfo->last_mouse_frame = emacsframe;
6006 /* appears to be needed to prevent spurious movement events generated on
6008 emacsframe->mouse_moved = 0;
6010 if ([theEvent type] == NSScrollWheel)
6012 CGFloat delta = [theEvent deltaY];
6013 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
6016 delta = [theEvent deltaX];
6019 NSTRACE ("deltaIsZero");
6022 emacs_event->kind = HORIZ_WHEEL_EVENT;
6025 emacs_event->kind = WHEEL_EVENT;
6027 emacs_event->code = 0;
6028 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
6029 ((delta > 0) ? up_modifier : down_modifier);
6033 emacs_event->kind = MOUSE_CLICK_EVENT;
6034 emacs_event->code = EV_BUTTON (theEvent);
6035 emacs_event->modifiers = EV_MODIFIERS (theEvent)
6036 | EV_UDMODIFIERS (theEvent);
6038 XSETINT (emacs_event->x, lrint (p.x));
6039 XSETINT (emacs_event->y, lrint (p.y));
6040 EV_TRAILER (theEvent);
6044 - (void)rightMouseDown: (NSEvent *)theEvent
6046 NSTRACE ("rightMouseDown");
6047 [self mouseDown: theEvent];
6051 - (void)otherMouseDown: (NSEvent *)theEvent
6053 NSTRACE ("otherMouseDown");
6054 [self mouseDown: theEvent];
6058 - (void)mouseUp: (NSEvent *)theEvent
6060 NSTRACE ("mouseUp");
6061 [self mouseDown: theEvent];
6065 - (void)rightMouseUp: (NSEvent *)theEvent
6067 NSTRACE ("rightMouseUp");
6068 [self mouseDown: theEvent];
6072 - (void)otherMouseUp: (NSEvent *)theEvent
6074 NSTRACE ("otherMouseUp");
6075 [self mouseDown: theEvent];
6079 - (void) scrollWheel: (NSEvent *)theEvent
6081 NSTRACE ("scrollWheel");
6082 [self mouseDown: theEvent];
6086 /* Tell emacs the mouse has moved. */
6087 - (void)mouseMoved: (NSEvent *)e
6089 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
6090 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6094 // NSTRACE ("mouseMoved");
6096 dpyinfo->last_mouse_movement_time = EV_TIMESTAMP (e);
6097 pt = [self convertPoint: [e locationInWindow] fromView: nil];
6098 dpyinfo->last_mouse_motion_x = pt.x;
6099 dpyinfo->last_mouse_motion_y = pt.y;
6101 /* update any mouse face */
6102 if (hlinfo->mouse_face_hidden)
6104 hlinfo->mouse_face_hidden = 0;
6105 clear_mouse_face (hlinfo);
6108 /* tooltip handling */
6109 previous_help_echo_string = help_echo_string;
6110 help_echo_string = Qnil;
6112 if (!NILP (Vmouse_autoselect_window))
6114 NSTRACE ("mouse_autoselect_window");
6115 static Lisp_Object last_mouse_window;
6117 = window_from_coordinates (emacsframe, pt.x, pt.y, 0, 0);
6119 if (WINDOWP (window)
6120 && !EQ (window, last_mouse_window)
6121 && !EQ (window, selected_window)
6122 && (focus_follows_mouse
6123 || (EQ (XWINDOW (window)->frame,
6124 XWINDOW (selected_window)->frame))))
6126 NSTRACE ("in_window");
6127 emacs_event->kind = SELECT_WINDOW_EVENT;
6128 emacs_event->frame_or_window = window;
6131 /* Remember the last window where we saw the mouse. */
6132 last_mouse_window = window;
6135 if (!note_mouse_movement (emacsframe, pt.x, pt.y))
6136 help_echo_string = previous_help_echo_string;
6138 XSETFRAME (frame, emacsframe);
6139 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
6141 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
6142 (note_mouse_highlight), which is called through the
6143 note_mouse_movement () call above */
6144 any_help_event_p = YES;
6145 gen_help_event (help_echo_string, frame, help_echo_window,
6146 help_echo_object, help_echo_pos);
6149 if (emacsframe->mouse_moved && send_appdefined)
6150 ns_send_appdefined (-1);
6154 - (void)mouseDragged: (NSEvent *)e
6156 NSTRACE ("mouseDragged");
6157 [self mouseMoved: e];
6161 - (void)rightMouseDragged: (NSEvent *)e
6163 NSTRACE ("rightMouseDragged");
6164 [self mouseMoved: e];
6168 - (void)otherMouseDragged: (NSEvent *)e
6170 NSTRACE ("otherMouseDragged");
6171 [self mouseMoved: e];
6175 - (BOOL)windowShouldClose: (id)sender
6177 NSEvent *e =[[self window] currentEvent];
6179 NSTRACE ("windowShouldClose");
6180 windowClosing = YES;
6183 emacs_event->kind = DELETE_WINDOW_EVENT;
6184 emacs_event->modifiers = 0;
6185 emacs_event->code = 0;
6187 /* Don't close this window, let this be done from lisp code. */
6191 - (void) updateFrameSize: (BOOL) delay;
6193 NSWindow *window = [self window];
6194 NSRect wr = [window frame];
6196 int oldc = cols, oldr = rows;
6197 int oldw = FRAME_PIXEL_WIDTH (emacsframe);
6198 int oldh = FRAME_PIXEL_HEIGHT (emacsframe);
6201 NSTRACE ("updateFrameSize");
6202 NSTRACE_SIZE ("Original size", NSMakeSize (oldw, oldh));
6203 NSTRACE_RECT ("Original frame", wr);
6204 NSTRACE_MSG ("Original columns: %d", cols);
6205 NSTRACE_MSG ("Original rows: %d", rows);
6207 if (! [self isFullscreen])
6209 #ifdef NS_IMPL_GNUSTEP
6210 // GNUstep does not always update the tool bar height. Force it.
6211 if (toolbar && [toolbar isVisible])
6212 update_frame_tool_bar (emacsframe);
6215 extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6216 + FRAME_TOOLBAR_HEIGHT (emacsframe);
6219 if (wait_for_tool_bar)
6221 if (FRAME_TOOLBAR_HEIGHT (emacsframe) == 0)
6223 NSTRACE_MSG ("Waiting for toolbar");
6226 wait_for_tool_bar = NO;
6229 neww = (int)wr.size.width - emacsframe->border_width;
6230 newh = (int)wr.size.height - extra;
6232 NSTRACE_SIZE ("New size", NSMakeSize (neww, newh));
6233 NSTRACE_MSG ("tool_bar_height: %d", emacsframe->tool_bar_height);
6235 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, neww);
6236 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, newh);
6238 if (cols < MINWIDTH)
6241 if (rows < MINHEIGHT)
6244 NSTRACE_MSG ("New columns: %d", cols);
6245 NSTRACE_MSG ("New rows: %d", rows);
6247 if (oldr != rows || oldc != cols || neww != oldw || newh != oldh)
6249 NSView *view = FRAME_NS_VIEW (emacsframe);
6250 NSWindow *win = [view window];
6252 change_frame_size (emacsframe,
6253 FRAME_PIXEL_TO_TEXT_WIDTH (emacsframe, neww),
6254 FRAME_PIXEL_TO_TEXT_HEIGHT (emacsframe, newh),
6256 SET_FRAME_GARBAGED (emacsframe);
6257 cancel_mouse_face (emacsframe);
6259 wr = NSMakeRect (0, 0, neww, newh);
6260 NSTRACE_RECT ("setFrame", wr);
6261 [view setFrame: wr];
6262 [self windowDidMove:nil]; // Update top/left.
6266 NSTRACE_MSG ("No change");
6270 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
6271 /* normalize frame to gridded text size */
6275 NSTRACE ("windowWillResize: toSize: " NSTRACE_FMT_SIZE,
6276 NSTRACE_ARG_SIZE (frameSize));
6277 NSTRACE_RECT ("[sender frame]", [sender frame]);
6278 NSTRACE_FSTYPE ("fs_state", fs_state);
6280 if (fs_state == FULLSCREEN_MAXIMIZED
6281 && (maximized_width != (int)frameSize.width
6282 || maximized_height != (int)frameSize.height))
6283 [self setFSValue: FULLSCREEN_NONE];
6284 else if (fs_state == FULLSCREEN_WIDTH
6285 && maximized_width != (int)frameSize.width)
6286 [self setFSValue: FULLSCREEN_NONE];
6287 else if (fs_state == FULLSCREEN_HEIGHT
6288 && maximized_height != (int)frameSize.height)
6289 [self setFSValue: FULLSCREEN_NONE];
6291 if (fs_state == FULLSCREEN_NONE)
6292 maximized_width = maximized_height = -1;
6294 if (! [self isFullscreen])
6296 extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6297 + FRAME_TOOLBAR_HEIGHT (emacsframe);
6300 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, frameSize.width);
6301 if (cols < MINWIDTH)
6304 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe,
6305 frameSize.height - extra);
6306 if (rows < MINHEIGHT)
6308 #ifdef NS_IMPL_COCOA
6310 /* this sets window title to have size in it; the wm does this under GS */
6311 NSRect r = [[self window] frame];
6312 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
6320 else if (fs_state == FULLSCREEN_NONE && ! maximizing_resize)
6323 NSWindow *window = [self window];
6326 char *t = strdup ([[[self window] title] UTF8String]);
6327 char *pos = strstr (t, " — ");
6332 size_title = xmalloc (strlen (old_title) + 40);
6333 esprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
6334 [window setTitle: [NSString stringWithUTF8String: size_title]];
6339 #endif /* NS_IMPL_COCOA */
6341 NSTRACE_MSG ("cols: %d rows: %d", cols, rows);
6343 /* Restrict the new size to the text gird.
6345 Don't restict the width if the user only adjusted the height, and
6346 vice versa. (Without this, the frame would shrink, and move
6347 slightly, if the window was resized by dragging one of its
6349 if (!frame_resize_pixelwise)
6351 NSRect r = [[self window] frame];
6353 if (r.size.width != frameSize.width)
6356 FRAME_TEXT_COLS_TO_PIXEL_WIDTH (emacsframe, cols);
6359 if (r.size.height != frameSize.height)
6362 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows) + extra;
6366 NSTRACE_RETURN_SIZE (frameSize);
6372 - (void)windowDidResize: (NSNotification *)notification
6374 NSTRACE ("windowDidResize");
6376 if (emacsframe->output_data.ns->in_animation)
6378 NSTRACE_MSG ("Ignored (in animation)");
6382 if (! [self fsIsNative])
6384 NSWindow *theWindow = [notification object];
6385 /* We can get notification on the non-FS window when in
6387 if ([self window] != theWindow) return;
6390 NSTRACE_RECT ("frame", [[notification object] frame]);
6392 #ifdef NS_IMPL_GNUSTEP
6393 NSWindow *theWindow = [notification object];
6395 /* In GNUstep, at least currently, it's possible to get a didResize
6396 without getting a willResize.. therefore we need to act as if we got
6397 the willResize now */
6398 NSSize sz = [theWindow frame].size;
6399 sz = [self windowWillResize: theWindow toSize: sz];
6400 #endif /* NS_IMPL_GNUSTEP */
6402 if (cols > 0 && rows > 0)
6404 [self updateFrameSize: YES];
6407 ns_send_appdefined (-1);
6410 #ifdef NS_IMPL_COCOA
6411 - (void)viewDidEndLiveResize
6413 [super viewDidEndLiveResize];
6416 [[self window] setTitle: [NSString stringWithUTF8String: old_title]];
6420 maximizing_resize = NO;
6422 #endif /* NS_IMPL_COCOA */
6425 - (void)windowDidBecomeKey: (NSNotification *)notification
6426 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6428 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6429 struct frame *old_focus = dpyinfo->x_focus_frame;
6431 NSTRACE ("windowDidBecomeKey");
6433 if (emacsframe != old_focus)
6434 dpyinfo->x_focus_frame = emacsframe;
6436 ns_frame_rehighlight (emacsframe);
6440 emacs_event->kind = FOCUS_IN_EVENT;
6441 EV_TRAILER ((id)nil);
6446 - (void)windowDidResignKey: (NSNotification *)notification
6447 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6449 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6450 BOOL is_focus_frame = dpyinfo->x_focus_frame == emacsframe;
6451 NSTRACE ("windowDidResignKey");
6454 dpyinfo->x_focus_frame = 0;
6456 emacsframe->mouse_moved = 0;
6457 ns_frame_rehighlight (emacsframe);
6459 /* FIXME: for some reason needed on second and subsequent clicks away
6460 from sole-frame Emacs to get hollow box to show */
6461 if (!windowClosing && [[self window] isVisible] == YES)
6463 x_update_cursor (emacsframe, 1);
6464 x_set_frame_alpha (emacsframe);
6467 if (any_help_event_p)
6470 XSETFRAME (frame, emacsframe);
6471 help_echo_string = Qnil;
6472 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
6475 if (emacs_event && is_focus_frame)
6477 [self deleteWorkingText];
6478 emacs_event->kind = FOCUS_OUT_EVENT;
6479 EV_TRAILER ((id)nil);
6484 - (void)windowWillMiniaturize: sender
6486 NSTRACE ("windowWillMiniaturize");
6502 - initFrameFromEmacs: (struct frame *)f
6510 NSTRACE ("initFrameFromEmacs");
6513 processingCompose = NO;
6514 scrollbarsNeedingUpdate = 0;
6515 fs_state = FULLSCREEN_NONE;
6516 fs_before_fs = next_maximized = -1;
6517 #ifdef HAVE_NATIVE_FS
6518 fs_is_native = ns_use_native_fullscreen;
6522 maximized_width = maximized_height = -1;
6525 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
6527 ns_userRect = NSMakeRect (0, 0, 0, 0);
6528 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
6529 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
6530 [self initWithFrame: r];
6531 [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
6533 FRAME_NS_VIEW (f) = self;
6535 #ifdef NS_IMPL_COCOA
6537 maximizing_resize = NO;
6540 win = [[EmacsWindow alloc]
6541 initWithContentRect: r
6542 styleMask: (NSResizableWindowMask |
6543 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6544 NSTitledWindowMask |
6546 NSMiniaturizableWindowMask |
6547 NSClosableWindowMask)
6548 backing: NSBackingStoreBuffered
6551 #ifdef HAVE_NATIVE_FS
6552 [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
6556 bwidth = f->border_width = wr.size.width - r.size.width;
6557 tibar_height = FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
6559 [win setAcceptsMouseMovedEvents: YES];
6560 [win setDelegate: self];
6561 #if !defined (NS_IMPL_COCOA) || \
6562 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6563 [win useOptimizedDrawing: YES];
6566 [[win contentView] addSubview: self];
6569 [self registerForDraggedTypes: ns_drag_types];
6572 name = [NSString stringWithUTF8String:
6573 NILP (tem) ? "Emacs" : SSDATA (tem)];
6574 [win setTitle: name];
6576 /* toolbar support */
6577 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
6578 [NSString stringWithFormat: @"Emacs Frame %d",
6580 [win setToolbar: toolbar];
6581 [toolbar setVisible: NO];
6583 /* Don't set frame garbaged until tool bar is up to date?
6584 This avoids an extra clear and redraw (flicker) at frame creation. */
6585 if (FRAME_EXTERNAL_TOOL_BAR (f)) wait_for_tool_bar = YES;
6586 else wait_for_tool_bar = NO;
6589 #ifdef NS_IMPL_COCOA
6591 NSButton *toggleButton;
6592 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
6593 [toggleButton setTarget: self];
6594 [toggleButton setAction: @selector (toggleToolbar: )];
6597 FRAME_TOOLBAR_HEIGHT (f) = 0;
6601 [win setMiniwindowTitle:
6602 [NSString stringWithUTF8String: SSDATA (tem)]];
6605 NSScreen *screen = [win screen];
6609 NSPoint pt = NSMakePoint
6610 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
6611 IN_BOUND (-SCREENMAX,
6612 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX));
6614 NSTRACE_POINT ("setFrameTopLeftPoint", pt);
6616 [win setFrameTopLeftPoint: pt];
6618 NSTRACE_RECT ("new frame", [win frame]);
6622 [win makeFirstResponder: self];
6624 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6625 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
6626 [win setBackgroundColor: col];
6627 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6628 [win setOpaque: NO];
6630 #if !defined (NS_IMPL_COCOA) || \
6631 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6632 [self allocateGState];
6634 [NSApp registerServicesMenuSendTypes: ns_send_types
6642 - (void)windowDidMove: sender
6644 NSWindow *win = [self window];
6645 NSRect r = [win frame];
6646 NSArray *screens = [NSScreen screens];
6647 NSScreen *screen = [screens objectAtIndex: 0];
6649 NSTRACE ("windowDidMove");
6651 if (!emacsframe->output_data.ns)
6655 emacsframe->left_pos = r.origin.x;
6656 emacsframe->top_pos =
6657 [screen frame].size.height - (r.origin.y + r.size.height);
6662 /* Called AFTER method below, but before our windowWillResize call there leads
6663 to windowDidResize -> x_set_window_size. Update emacs' notion of frame
6664 location so set_window_size moves the frame. */
6665 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
6667 NSTRACE (("[windowShouldZoom:win toFrame:" NSTRACE_FMT_RECT "]"
6668 NSTRACE_FMT_RETURN "YES"),
6669 NSTRACE_ARG_RECT (newFrame));
6671 emacsframe->output_data.ns->zooming = 1;
6676 /* Override to do something slightly nonstandard, but nice. First click on
6677 zoom button will zoom vertically. Second will zoom completely. Third
6678 returns to original. */
6679 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
6680 defaultFrame:(NSRect)defaultFrame
6682 // TODO: Rename to "currentFrame" and assign "result" properly in
6684 NSRect result = [sender frame];
6686 NSTRACE (("[windowWillUseStandardFrame: defaultFrame:"
6687 NSTRACE_FMT_RECT "]"),
6688 NSTRACE_ARG_RECT (defaultFrame));
6689 NSTRACE_FSTYPE ("fs_state", fs_state);
6690 NSTRACE_FSTYPE ("fs_before_fs", fs_before_fs);
6691 NSTRACE_FSTYPE ("next_maximized", next_maximized);
6692 NSTRACE_RECT ("ns_userRect", ns_userRect);
6693 NSTRACE_RECT ("[sender frame]", [sender frame]);
6695 if (fs_before_fs != -1) /* Entering fullscreen */
6697 NSTRACE_MSG ("Entering fullscreen");
6698 result = defaultFrame;
6702 // Save the window size and position (frame) before the resize.
6703 if (fs_state != FULLSCREEN_MAXIMIZED
6704 && fs_state != FULLSCREEN_WIDTH)
6706 ns_userRect.size.width = result.size.width;
6707 ns_userRect.origin.x = result.origin.x;
6710 if (fs_state != FULLSCREEN_MAXIMIZED
6711 && fs_state != FULLSCREEN_HEIGHT)
6713 ns_userRect.size.height = result.size.height;
6714 ns_userRect.origin.y = result.origin.y;
6717 NSTRACE_RECT ("ns_userRect (2)", ns_userRect);
6719 if (next_maximized == FULLSCREEN_HEIGHT
6720 || (next_maximized == -1
6721 && abs ((int)(defaultFrame.size.height - result.size.height))
6722 > FRAME_LINE_HEIGHT (emacsframe)))
6725 NSTRACE_MSG ("FULLSCREEN_HEIGHT");
6726 maximized_height = result.size.height = defaultFrame.size.height;
6727 maximized_width = -1;
6728 result.origin.y = defaultFrame.origin.y;
6729 if (ns_userRect.size.height != 0)
6731 result.origin.x = ns_userRect.origin.x;
6732 result.size.width = ns_userRect.size.width;
6734 [self setFSValue: FULLSCREEN_HEIGHT];
6735 #ifdef NS_IMPL_COCOA
6736 maximizing_resize = YES;
6739 else if (next_maximized == FULLSCREEN_WIDTH)
6741 NSTRACE_MSG ("FULLSCREEN_WIDTH");
6742 maximized_width = result.size.width = defaultFrame.size.width;
6743 maximized_height = -1;
6744 result.origin.x = defaultFrame.origin.x;
6745 if (ns_userRect.size.width != 0)
6747 result.origin.y = ns_userRect.origin.y;
6748 result.size.height = ns_userRect.size.height;
6750 [self setFSValue: FULLSCREEN_WIDTH];
6752 else if (next_maximized == FULLSCREEN_MAXIMIZED
6753 || (next_maximized == -1
6754 && abs ((int)(defaultFrame.size.width - result.size.width))
6755 > FRAME_COLUMN_WIDTH (emacsframe)))
6757 NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
6759 result = defaultFrame; /* second click */
6760 maximized_width = result.size.width;
6761 maximized_height = result.size.height;
6762 [self setFSValue: FULLSCREEN_MAXIMIZED];
6763 #ifdef NS_IMPL_COCOA
6764 maximizing_resize = YES;
6770 NSTRACE_MSG ("Restore");
6771 result = ns_userRect.size.height ? ns_userRect : result;
6772 NSTRACE_RECT ("restore (2)", result);
6773 ns_userRect = NSMakeRect (0, 0, 0, 0);
6774 #ifdef NS_IMPL_COCOA
6775 maximizing_resize = fs_state != FULLSCREEN_NONE;
6777 [self setFSValue: FULLSCREEN_NONE];
6778 maximized_width = maximized_height = -1;
6782 if (fs_before_fs == -1) next_maximized = -1;
6784 NSTRACE_RECT ("Final ns_userRect", ns_userRect);
6785 NSTRACE_MSG ("Final maximized_width: %d", maximized_width);
6786 NSTRACE_MSG ("Final maximized_height: %d", maximized_height);
6787 NSTRACE_FSTYPE ("Final next_maximized", next_maximized);
6789 [self windowWillResize: sender toSize: result.size];
6791 NSTRACE_RETURN_RECT (result);
6797 - (void)windowDidDeminiaturize: sender
6799 NSTRACE ("windowDidDeminiaturize");
6800 if (!emacsframe->output_data.ns)
6803 SET_FRAME_ICONIFIED (emacsframe, 0);
6804 SET_FRAME_VISIBLE (emacsframe, 1);
6805 windows_or_buffers_changed = 63;
6809 emacs_event->kind = DEICONIFY_EVENT;
6810 EV_TRAILER ((id)nil);
6815 - (void)windowDidExpose: sender
6817 NSTRACE ("windowDidExpose");
6818 if (!emacsframe->output_data.ns)
6821 SET_FRAME_VISIBLE (emacsframe, 1);
6822 SET_FRAME_GARBAGED (emacsframe);
6824 if (send_appdefined)
6825 ns_send_appdefined (-1);
6829 - (void)windowDidMiniaturize: sender
6831 NSTRACE ("windowDidMiniaturize");
6832 if (!emacsframe->output_data.ns)
6835 SET_FRAME_ICONIFIED (emacsframe, 1);
6836 SET_FRAME_VISIBLE (emacsframe, 0);
6840 emacs_event->kind = ICONIFY_EVENT;
6841 EV_TRAILER ((id)nil);
6845 #ifdef HAVE_NATIVE_FS
6846 - (NSApplicationPresentationOptions)window:(NSWindow *)window
6847 willUseFullScreenPresentationOptions:
6848 (NSApplicationPresentationOptions)proposedOptions
6850 return proposedOptions|NSApplicationPresentationAutoHideToolbar;
6854 - (void)windowWillEnterFullScreen:(NSNotification *)notification
6856 NSTRACE ("windowWillEnterFullScreen");
6857 fs_before_fs = fs_state;
6860 - (void)windowDidEnterFullScreen:(NSNotification *)notification
6862 NSTRACE ("windowDidEnterFullScreen");
6863 [self setFSValue: FULLSCREEN_BOTH];
6864 if (! [self fsIsNative])
6866 [self windowDidBecomeKey:notification];
6867 [nonfs_window orderOut:self];
6871 BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (emacsframe) ? YES : NO;
6872 #ifdef NS_IMPL_COCOA
6873 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6874 unsigned val = (unsigned)[NSApp presentationOptions];
6876 // OSX 10.7 bug fix, the menu won't appear without this.
6877 // val is non-zero on other OSX versions.
6880 NSApplicationPresentationOptions options
6881 = NSApplicationPresentationAutoHideDock
6882 | NSApplicationPresentationAutoHideMenuBar
6883 | NSApplicationPresentationFullScreen
6884 | NSApplicationPresentationAutoHideToolbar;
6886 [NSApp setPresentationOptions: options];
6890 [toolbar setVisible:tbar_visible];
6894 - (void)windowWillExitFullScreen:(NSNotification *)notification
6896 NSTRACE ("windowWillExitFullScreen");
6898 if (next_maximized != -1)
6899 fs_before_fs = next_maximized;
6902 - (void)windowDidExitFullScreen:(NSNotification *)notification
6904 NSTRACE ("windowDidExitFullScreen");
6906 [self setFSValue: fs_before_fs];
6908 #ifdef HAVE_NATIVE_FS
6909 [self updateCollectionBehavior];
6911 if (FRAME_EXTERNAL_TOOL_BAR (emacsframe))
6913 [toolbar setVisible:YES];
6914 update_frame_tool_bar (emacsframe);
6915 [self updateFrameSize:YES];
6916 [[self window] display];
6919 [toolbar setVisible:NO];
6921 if (next_maximized != -1)
6922 [[self window] performZoom:self];
6927 return fs_is_native;
6930 - (BOOL)isFullscreen
6932 if (! fs_is_native) return nonfs_window != nil;
6933 #ifdef HAVE_NATIVE_FS
6934 return ([[self window] styleMask] & NSFullScreenWindowMask) != 0;
6940 #ifdef HAVE_NATIVE_FS
6941 - (void)updateCollectionBehavior
6943 if (! [self isFullscreen])
6945 NSWindow *win = [self window];
6946 NSWindowCollectionBehavior b = [win collectionBehavior];
6947 if (ns_use_native_fullscreen)
6948 b |= NSWindowCollectionBehaviorFullScreenPrimary;
6950 b &= ~NSWindowCollectionBehaviorFullScreenPrimary;
6952 [win setCollectionBehavior: b];
6953 fs_is_native = ns_use_native_fullscreen;
6958 - (void)toggleFullScreen: (id)sender
6966 NSTRACE ("toggleFullScreen");
6970 #ifdef HAVE_NATIVE_FS
6971 [[self window] toggleFullScreen:sender];
6977 onFirstScreen = [[w screen] isEqual:[[NSScreen screens] objectAtIndex:0]];
6980 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6981 (FRAME_DEFAULT_FACE (f)),
6984 if (fs_state != FULLSCREEN_BOTH)
6986 NSScreen *screen = [w screen];
6988 #if defined (NS_IMPL_COCOA) && \
6989 MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
6990 /* Hide ghost menu bar on secondary monitor? */
6991 if (! onFirstScreen)
6992 onFirstScreen = [NSScreen screensHaveSeparateSpaces];
6994 /* Hide dock and menubar if we are on the primary screen. */
6997 #ifdef NS_IMPL_COCOA
6998 NSApplicationPresentationOptions options
6999 = NSApplicationPresentationAutoHideDock
7000 | NSApplicationPresentationAutoHideMenuBar;
7002 [NSApp setPresentationOptions: options];
7004 [NSMenu setMenuBarVisible:NO];
7008 fw = [[EmacsFSWindow alloc]
7009 initWithContentRect:[w contentRectForFrameRect:wr]
7010 styleMask:NSBorderlessWindowMask
7011 backing:NSBackingStoreBuffered
7015 [fw setContentView:[w contentView]];
7016 [fw setTitle:[w title]];
7017 [fw setDelegate:self];
7018 [fw setAcceptsMouseMovedEvents: YES];
7019 #if !defined (NS_IMPL_COCOA) || \
7020 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
7021 [fw useOptimizedDrawing: YES];
7023 [fw setBackgroundColor: col];
7024 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
7027 f->border_width = 0;
7028 FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
7029 tobar_height = FRAME_TOOLBAR_HEIGHT (f);
7030 FRAME_TOOLBAR_HEIGHT (f) = 0;
7034 [self windowWillEnterFullScreen:nil];
7035 [fw makeKeyAndOrderFront:NSApp];
7036 [fw makeFirstResponder:self];
7038 r = [fw frameRectForContentRect:[screen frame]];
7039 [fw setFrame: r display:YES animate:ns_use_fullscreen_animation];
7040 [self windowDidEnterFullScreen:nil];
7051 #ifdef NS_IMPL_COCOA
7052 [NSApp setPresentationOptions: NSApplicationPresentationDefault];
7054 [NSMenu setMenuBarVisible:YES];
7058 [w setContentView:[fw contentView]];
7059 [w setBackgroundColor: col];
7060 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
7063 f->border_width = bwidth;
7064 FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
7065 if (FRAME_EXTERNAL_TOOL_BAR (f))
7066 FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
7068 [self windowWillExitFullScreen:nil];
7069 [fw setFrame: [w frame] display:YES animate:ns_use_fullscreen_animation];
7071 [w makeKeyAndOrderFront:NSApp];
7072 [self windowDidExitFullScreen:nil];
7073 [self updateFrameSize:YES];
7079 NSTRACE ("handleFS");
7081 if (fs_state != emacsframe->want_fullscreen)
7083 if (fs_state == FULLSCREEN_BOTH)
7085 NSTRACE_MSG ("fs_state == FULLSCREEN_BOTH");
7086 [self toggleFullScreen:self];
7089 switch (emacsframe->want_fullscreen)
7091 case FULLSCREEN_BOTH:
7092 NSTRACE_MSG ("FULLSCREEN_BOTH");
7093 [self toggleFullScreen:self];
7095 case FULLSCREEN_WIDTH:
7096 NSTRACE_MSG ("FULLSCREEN_WIDTH");
7097 next_maximized = FULLSCREEN_WIDTH;
7098 if (fs_state != FULLSCREEN_BOTH)
7099 [[self window] performZoom:self];
7101 case FULLSCREEN_HEIGHT:
7102 NSTRACE_MSG ("FULLSCREEN_HEIGHT");
7103 next_maximized = FULLSCREEN_HEIGHT;
7104 if (fs_state != FULLSCREEN_BOTH)
7105 [[self window] performZoom:self];
7107 case FULLSCREEN_MAXIMIZED:
7108 NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
7109 next_maximized = FULLSCREEN_MAXIMIZED;
7110 if (fs_state != FULLSCREEN_BOTH)
7111 [[self window] performZoom:self];
7113 case FULLSCREEN_NONE:
7114 NSTRACE_MSG ("FULLSCREEN_NONE");
7115 if (fs_state != FULLSCREEN_BOTH)
7117 next_maximized = FULLSCREEN_NONE;
7118 [[self window] performZoom:self];
7123 emacsframe->want_fullscreen = FULLSCREEN_NONE;
7128 - (void) setFSValue: (int)value
7130 NSTRACE ("setFSValue");
7131 NSTRACE_FSTYPE ("value", value);
7133 Lisp_Object lval = Qnil;
7136 case FULLSCREEN_BOTH:
7139 case FULLSCREEN_WIDTH:
7142 case FULLSCREEN_HEIGHT:
7145 case FULLSCREEN_MAXIMIZED:
7149 store_frame_param (emacsframe, Qfullscreen, lval);
7153 - (void)mouseEntered: (NSEvent *)theEvent
7155 NSTRACE ("mouseEntered");
7157 FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7158 = EV_TIMESTAMP (theEvent);
7162 - (void)mouseExited: (NSEvent *)theEvent
7164 Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
7166 NSTRACE ("mouseExited");
7171 FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7172 = EV_TIMESTAMP (theEvent);
7174 if (emacsframe == hlinfo->mouse_face_mouse_frame)
7176 clear_mouse_face (hlinfo);
7177 hlinfo->mouse_face_mouse_frame = 0;
7184 NSTRACE ("menuDown");
7185 if (context_menu_value == -1)
7186 context_menu_value = [sender tag];
7189 NSInteger tag = [sender tag];
7190 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
7191 emacsframe->menu_bar_vector,
7195 ns_send_appdefined (-1);
7200 - (EmacsToolbar *)toolbar
7206 /* this gets called on toolbar button click */
7207 - toolbarClicked: (id)item
7210 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
7212 NSTRACE ("toolbarClicked");
7217 /* send first event (for some reason two needed) */
7218 theEvent = [[self window] currentEvent];
7219 emacs_event->kind = TOOL_BAR_EVENT;
7220 XSETFRAME (emacs_event->arg, emacsframe);
7221 EV_TRAILER (theEvent);
7223 emacs_event->kind = TOOL_BAR_EVENT;
7224 /* XSETINT (emacs_event->code, 0); */
7225 emacs_event->arg = AREF (emacsframe->tool_bar_items,
7226 idx + TOOL_BAR_ITEM_KEY);
7227 emacs_event->modifiers = EV_MODIFIERS (theEvent);
7228 EV_TRAILER (theEvent);
7233 - toggleToolbar: (id)sender
7238 emacs_event->kind = NS_NONKEY_EVENT;
7239 emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
7240 EV_TRAILER ((id)nil);
7245 - (void)drawRect: (NSRect)rect
7247 int x = NSMinX (rect), y = NSMinY (rect);
7248 int width = NSWidth (rect), height = NSHeight (rect);
7250 NSTRACE ("drawRect");
7251 NSTRACE_RECT ("input", rect);
7253 if (!emacsframe || !emacsframe->output_data.ns)
7256 ns_clear_frame_area (emacsframe, x, y, width, height);
7258 expose_frame (emacsframe, x, y, width, height);
7262 drawRect: may be called (at least in OS X 10.5) for invisible
7263 views as well for some reason. Thus, do not infer visibility
7266 emacsframe->async_visible = 1;
7267 emacsframe->async_iconified = 0;
7272 /* NSDraggingDestination protocol methods. Actually this is not really a
7273 protocol, but a category of Object. O well... */
7275 -(NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
7277 NSTRACE ("draggingEntered");
7278 return NSDragOperationGeneric;
7282 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
7288 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
7293 NSEvent *theEvent = [[self window] currentEvent];
7295 NSDragOperation op = [sender draggingSourceOperationMask];
7298 NSTRACE ("performDragOperation");
7303 position = [self convertPoint: [sender draggingLocation] fromView: nil];
7304 x = lrint (position.x); y = lrint (position.y);
7306 pb = [sender draggingPasteboard];
7307 type = [pb availableTypeFromArray: ns_drag_types];
7309 if (! (op & (NSDragOperationMove|NSDragOperationDelete)) &&
7310 // URL drags contain all operations (0xf), don't allow all to be set.
7313 if (op & NSDragOperationLink)
7314 modifiers |= NSControlKeyMask;
7315 if (op & NSDragOperationCopy)
7316 modifiers |= NSAlternateKeyMask;
7317 if (op & NSDragOperationGeneric)
7318 modifiers |= NSCommandKeyMask;
7321 modifiers = EV_MODIFIERS2 (modifiers);
7326 else if ([type isEqualToString: NSFilenamesPboardType])
7329 NSEnumerator *fenum;
7332 if (!(files = [pb propertyListForType: type]))
7335 fenum = [files objectEnumerator];
7336 while ( (file = [fenum nextObject]) )
7338 emacs_event->kind = DRAG_N_DROP_EVENT;
7339 XSETINT (emacs_event->x, x);
7340 XSETINT (emacs_event->y, y);
7341 ns_input_file = append2 (ns_input_file,
7342 build_string ([file UTF8String]));
7343 emacs_event->modifiers = modifiers;
7344 emacs_event->arg = list2 (Qfile, build_string ([file UTF8String]));
7345 EV_TRAILER (theEvent);
7349 else if ([type isEqualToString: NSURLPboardType])
7351 NSURL *url = [NSURL URLFromPasteboard: pb];
7352 if (url == nil) return NO;
7354 emacs_event->kind = DRAG_N_DROP_EVENT;
7355 XSETINT (emacs_event->x, x);
7356 XSETINT (emacs_event->y, y);
7357 emacs_event->modifiers = modifiers;
7358 emacs_event->arg = list2 (Qurl,
7359 build_string ([[url absoluteString]
7361 EV_TRAILER (theEvent);
7363 if ([url isFileURL] != NO)
7365 NSString *file = [url path];
7366 ns_input_file = append2 (ns_input_file,
7367 build_string ([file UTF8String]));
7371 else if ([type isEqualToString: NSStringPboardType]
7372 || [type isEqualToString: NSTabularTextPboardType])
7376 if (! (data = [pb stringForType: type]))
7379 emacs_event->kind = DRAG_N_DROP_EVENT;
7380 XSETINT (emacs_event->x, x);
7381 XSETINT (emacs_event->y, y);
7382 emacs_event->modifiers = modifiers;
7383 emacs_event->arg = list2 (Qnil, build_string ([data UTF8String]));
7384 EV_TRAILER (theEvent);
7389 fprintf (stderr, "Invalid data type in dragging pasteboard");
7395 - (id) validRequestorForSendType: (NSString *)typeSent
7396 returnType: (NSString *)typeReturned
7398 NSTRACE ("validRequestorForSendType");
7399 if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
7400 && typeReturned == nil)
7402 if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
7406 return [super validRequestorForSendType: typeSent
7407 returnType: typeReturned];
7411 /* The next two methods are part of NSServicesRequests informal protocol,
7412 supposedly called when a services menu item is chosen from this app.
7413 But this should not happen because we override the services menu with our
7414 own entries which call ns-perform-service.
7415 Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
7416 So let's at least stub them out until further investigation can be done. */
7418 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
7420 /* we could call ns_string_from_pasteboard(pboard) here but then it should
7421 be written into the buffer in place of the existing selection..
7422 ordinary service calls go through functions defined in ns-win.el */
7426 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
7428 NSArray *typesDeclared;
7431 /* We only support NSStringPboardType */
7432 if ([types containsObject:NSStringPboardType] == NO) {
7436 val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7437 if (CONSP (val) && SYMBOLP (XCAR (val)))
7440 if (CONSP (val) && NILP (XCDR (val)))
7443 if (! STRINGP (val))
7446 typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
7447 [pb declareTypes:typesDeclared owner:nil];
7448 ns_string_to_pasteboard (pb, val);
7453 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
7454 (gives a miniaturized version of the window); currently we use the latter for
7455 frames whose active buffer doesn't correspond to any file
7456 (e.g., '*scratch*') */
7457 - setMiniwindowImage: (BOOL) setMini
7459 id image = [[self window] miniwindowImage];
7460 NSTRACE ("setMiniwindowImage");
7462 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
7463 about "AppleDockIconEnabled" notwithstanding, however the set message
7464 below has its effect nonetheless. */
7465 if (image != emacsframe->output_data.ns->miniimage)
7467 if (image && [image isKindOfClass: [EmacsImage class]])
7469 [[self window] setMiniwindowImage:
7470 setMini ? emacsframe->output_data.ns->miniimage : nil];
7477 - (void) setRows: (int) r andColumns: (int) c
7479 NSTRACE ("[EmacsView setRows:%d andColumns:%d]", r, c);
7484 - (int) fullscreenState
7489 @end /* EmacsView */
7493 /* ==========================================================================
7495 EmacsWindow implementation
7497 ========================================================================== */
7499 @implementation EmacsWindow
7501 #ifdef NS_IMPL_COCOA
7502 - (id)accessibilityAttributeValue:(NSString *)attribute
7504 Lisp_Object str = Qnil;
7505 struct frame *f = SELECTED_FRAME ();
7506 struct buffer *curbuf = XBUFFER (XWINDOW (f->selected_window)->contents);
7508 if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
7509 return NSAccessibilityTextFieldRole;
7511 if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]
7512 && curbuf && ! NILP (BVAR (curbuf, mark_active)))
7514 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7516 else if (curbuf && [attribute isEqualToString:NSAccessibilityValueAttribute])
7518 if (! NILP (BVAR (curbuf, mark_active)))
7519 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7523 ptrdiff_t start_byte = BUF_BEGV_BYTE (curbuf);
7524 ptrdiff_t byte_range = BUF_ZV_BYTE (curbuf) - start_byte;
7525 ptrdiff_t range = BUF_ZV (curbuf) - BUF_BEGV (curbuf);
7527 if (! NILP (BVAR (curbuf, enable_multibyte_characters)))
7528 str = make_uninit_multibyte_string (range, byte_range);
7530 str = make_uninit_string (range);
7531 /* To check: This returns emacs-utf-8, which is a superset of utf-8.
7532 Is this a problem? */
7533 memcpy (SDATA (str), BYTE_POS_ADDR (start_byte), byte_range);
7540 if (CONSP (str) && SYMBOLP (XCAR (str)))
7543 if (CONSP (str) && NILP (XCDR (str)))
7548 const char *utfStr = SSDATA (str);
7549 NSString *nsStr = [NSString stringWithUTF8String: utfStr];
7554 return [super accessibilityAttributeValue:attribute];
7556 #endif /* NS_IMPL_COCOA */
7558 /* Constrain size and placement of a frame.
7560 By returning the original "frameRect", the frame is not
7561 contrained. This can lead to unwanted situations where, for
7562 example, the menu bar covers the frame.
7564 The default implementation (accessed using "super") constrains the
7565 frame to the visible area of SCREEN, minus the menu bar (if
7566 present) and the Dock. Note that default implementation also calls
7567 windowWillResize, with the frame it thinks should have. (This can
7568 make the frame exit maximized mode.)
7570 Note that this should work in situations where multiple monitors
7571 are present. Common configurations are side-by-side monitors and a
7572 monitor on top of another (e.g. when a laptop is placed under a
7574 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
7576 NSTRACE ("constrainFrameRect:" NSTRACE_FMT_RECT " toScreen:",
7577 NSTRACE_ARG_RECT (frameRect));
7579 #ifdef NS_IMPL_COCOA
7580 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7581 // If separate spaces is on, it is like each screen is independent. There is
7582 // no spanning of frames across screens.
7583 if ([NSScreen screensHaveSeparateSpaces])
7585 NSTRACE_MSG ("Screens have separate spaces");
7586 frameRect = [super constrainFrameRect:frameRect toScreen:screen];
7587 NSTRACE_RETURN_RECT (frameRect);
7593 return constrain_frame_rect(frameRect);
7597 - (void)performZoom:(id)sender
7599 NSTRACE ("performZoom");
7601 return [super performZoom:sender];
7604 - (void)zoom:(id)sender
7606 struct frame * f = SELECTED_FRAME ();
7610 ns_update_auto_hide_menu_bar();
7612 // Below are three zoom implementations. In the final commit, the
7613 // idea is that the last should be included.
7616 // Native zoom done using the standard zoom animation. Size of the
7617 // resulting frame reduced to accomodate the Dock and, if present,
7619 [super zoom:sender];
7622 // Native zoom done using the standard zoom animation, plus an
7623 // explicit resize to cover the full screen.
7624 [super zoom:sender];
7626 // After the native zoom, resize the resulting frame to fill the
7627 // entire screen, except the menu-bar.
7629 // This works for all practical purposes. (The only minor oddity is
7630 // when transiting from full-height frame to a maximized, the
7631 // animation reduces the height of the frame slighty (to the 4
7632 // pixels needed to accomodate the Doc) before it snaps back into
7633 // full height. The user would need a very trained eye to spot
7635 NSScreen * screen = [self screen];
7638 int fs_state = [(EmacsView *)[self delegate] fullscreenState];
7640 NSTRACE_FSTYPE ("fullscreenState", fs_state);
7642 NSRect sr = [screen frame];
7643 NSRect wr = [self frame];
7644 NSTRACE_RECT ("Rect after zoom", wr);
7648 if (fs_state == FULLSCREEN_MAXIMIZED
7649 || fs_state == FULLSCREEN_HEIGHT)
7652 newWr.size.height = sr.size.height - ns_menu_bar_height(screen);
7655 if (fs_state == FULLSCREEN_MAXIMIZED
7656 || fs_state == FULLSCREEN_WIDTH)
7659 newWr.size.width = sr.size.width;
7662 if (newWr.size.width != wr.size.width
7663 || newWr.size.height != wr.size.height
7664 || newWr.origin.x != wr.origin.x
7665 || newWr.origin.y != wr.origin.y)
7667 NSTRACE_RECT ("Corrected rect", newWr);
7668 [self setFrame: newWr display: NO];
7672 // Non-native zoom which is done instantaneous. The resulting frame
7673 // covert the entire scrren, except the menu-bar, if present.
7674 NSScreen * screen = [self screen];
7677 NSRect sr = [screen frame];
7678 sr.size.height -= ns_menu_bar_height (screen);
7680 sr = [[self delegate] windowWillUseStandardFrame:self
7682 [self setFrame: sr display: NO];
7687 @end /* EmacsWindow */
7690 @implementation EmacsFSWindow
7692 - (BOOL)canBecomeKeyWindow
7697 - (BOOL)canBecomeMainWindow
7704 /* ==========================================================================
7706 EmacsScroller implementation
7708 ========================================================================== */
7711 @implementation EmacsScroller
7713 /* for repeat button push */
7714 #define SCROLL_BAR_FIRST_DELAY 0.5
7715 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
7717 + (CGFloat) scrollerWidth
7719 /* TODO: if we want to allow variable widths, this is the place to do it,
7720 however neither GNUstep nor Cocoa support it very well */
7722 #if !defined (NS_IMPL_COCOA) || \
7723 MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
7724 r = [NSScroller scrollerWidth];
7726 r = [NSScroller scrollerWidthForControlSize: NSRegularControlSize
7727 scrollerStyle: NSScrollerStyleLegacy];
7733 - initFrame: (NSRect )r window: (Lisp_Object)nwin
7735 NSTRACE ("EmacsScroller_initFrame");
7737 r.size.width = [EmacsScroller scrollerWidth];
7738 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
7739 [self setContinuous: YES];
7740 [self setEnabled: YES];
7742 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
7743 locked against the top and bottom edges, and right edge on OS X, where
7744 scrollers are on right. */
7745 #ifdef NS_IMPL_GNUSTEP
7746 [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
7748 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
7751 window = XWINDOW (nwin);
7753 pixel_height = NSHeight (r);
7754 if (pixel_height == 0) pixel_height = 1;
7755 min_portion = 20 / pixel_height;
7757 frame = XFRAME (window->frame);
7758 if (FRAME_LIVE_P (frame))
7761 EmacsView *view = FRAME_NS_VIEW (frame);
7762 NSView *sview = [[view window] contentView];
7763 NSArray *subs = [sview subviews];
7765 /* disable optimization stopping redraw of other scrollbars */
7766 view->scrollbarsNeedingUpdate = 0;
7767 for (i =[subs count]-1; i >= 0; i--)
7768 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
7769 view->scrollbarsNeedingUpdate++;
7770 [sview addSubview: self];
7773 /* [self setFrame: r]; */
7779 - (void)setFrame: (NSRect)newRect
7781 NSTRACE ("EmacsScroller_setFrame");
7782 /* block_input (); */
7783 pixel_height = NSHeight (newRect);
7784 if (pixel_height == 0) pixel_height = 1;
7785 min_portion = 20 / pixel_height;
7786 [super setFrame: newRect];
7787 /* unblock_input (); */
7793 NSTRACE ("EmacsScroller_dealloc");
7795 wset_vertical_scroll_bar (window, Qnil);
7803 NSTRACE ("condemn");
7811 NSTRACE ("reprieve");
7820 bool ret = condemned;
7825 /* ensure other scrollbar updates after deletion */
7826 view = (EmacsView *)FRAME_NS_VIEW (frame);
7828 view->scrollbarsNeedingUpdate++;
7830 wset_vertical_scroll_bar (window, Qnil);
7832 [self removeFromSuperview];
7840 - (void)resetCursorRects
7842 NSRect visible = [self visibleRect];
7843 NSTRACE ("resetCursorRects");
7845 if (!NSIsEmptyRect (visible))
7846 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
7847 [[NSCursor arrowCursor] setOnMouseEntered: YES];
7851 - (int) checkSamePosition: (int) position portion: (int) portion
7854 return em_position ==position && em_portion ==portion && em_whole ==whole
7855 && portion != whole; /* needed for resize empty buf */
7859 - setPosition: (int)position portion: (int)portion whole: (int)whole
7861 NSTRACE ("setPosition");
7863 em_position = position;
7864 em_portion = portion;
7867 if (portion >= whole)
7869 #ifdef NS_IMPL_COCOA
7870 [self setKnobProportion: 1.0];
7871 [self setDoubleValue: 1.0];
7873 [self setFloatValue: 0.0 knobProportion: 1.0];
7880 portion = max ((float)whole*min_portion/pixel_height, portion);
7881 pos = (float)position / (whole - portion);
7882 por = (CGFloat)portion/whole;
7883 #ifdef NS_IMPL_COCOA
7884 [self setKnobProportion: por];
7885 [self setDoubleValue: pos];
7887 [self setFloatValue: pos knobProportion: por];
7894 /* set up emacs_event */
7895 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
7901 emacs_event->part = last_hit_part;
7902 emacs_event->code = 0;
7903 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
7904 XSETWINDOW (win, window);
7905 emacs_event->frame_or_window = win;
7906 emacs_event->timestamp = EV_TIMESTAMP (e);
7907 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
7908 emacs_event->arg = Qnil;
7909 XSETINT (emacs_event->x, loc * pixel_height);
7910 XSETINT (emacs_event->y, pixel_height-20);
7914 n_emacs_events_pending++;
7915 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
7918 hold_event (emacs_event);
7919 EVENT_INIT (*emacs_event);
7920 ns_send_appdefined (-1);
7924 /* called manually thru timer to implement repeated button action w/hold-down */
7925 - repeatScroll: (NSTimer *)scrollEntry
7927 NSEvent *e = [[self window] currentEvent];
7928 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
7929 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
7931 /* clear timer if need be */
7932 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
7934 [scroll_repeat_entry invalidate];
7935 [scroll_repeat_entry release];
7936 scroll_repeat_entry = nil;
7942 = [[NSTimer scheduledTimerWithTimeInterval:
7943 SCROLL_BAR_CONTINUOUS_DELAY
7945 selector: @selector (repeatScroll:)
7951 [self sendScrollEventAtLoc: 0 fromEvent: e];
7956 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
7957 mouseDragged events without going into a modal loop. */
7958 - (void)mouseDown: (NSEvent *)e
7961 /* hitPart is only updated AFTER event is passed on */
7962 NSScrollerPart part = [self testPart: [e locationInWindow]];
7963 CGFloat inc = 0.0, loc, kloc, pos;
7966 NSTRACE ("EmacsScroller_mouseDown");
7970 case NSScrollerDecrementPage:
7971 last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
7972 case NSScrollerIncrementPage:
7973 last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
7974 case NSScrollerDecrementLine:
7975 last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
7976 case NSScrollerIncrementLine:
7977 last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
7978 case NSScrollerKnob:
7979 last_hit_part = scroll_bar_handle; break;
7980 case NSScrollerKnobSlot: /* GNUstep-only */
7981 last_hit_part = scroll_bar_move_ratio; break;
7982 default: /* NSScrollerNoPart? */
7983 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
7990 pos = 0; /* ignored */
7992 /* set a timer to repeat, as we can't let superclass do this modally */
7994 = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
7996 selector: @selector (repeatScroll:)
8003 /* handle, or on GNUstep possibly slot */
8004 NSEvent *fake_event;
8006 /* compute float loc in slot and mouse offset on knob */
8007 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
8009 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
8015 else if (loc >= NSHeight (sr))
8017 loc = NSHeight (sr);
8025 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
8027 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
8029 last_mouse_offset = kloc;
8031 /* if knob, tell emacs a location offset by knob pos
8032 (to indicate top of handle) */
8033 if (part == NSScrollerKnob)
8034 pos = (loc - last_mouse_offset) / NSHeight (sr);
8036 /* else this is a slot click on GNUstep: go straight there */
8037 pos = loc / NSHeight (sr);
8039 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
8040 fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
8041 location: [e locationInWindow]
8042 modifierFlags: [e modifierFlags]
8043 timestamp: [e timestamp]
8044 windowNumber: [e windowNumber]
8045 context: [e context]
8046 eventNumber: [e eventNumber]
8047 clickCount: [e clickCount]
8048 pressure: [e pressure]];
8049 [super mouseUp: fake_event];
8052 if (part != NSScrollerKnob)
8053 [self sendScrollEventAtLoc: pos fromEvent: e];
8057 /* Called as we manually track scroller drags, rather than superclass. */
8058 - (void)mouseDragged: (NSEvent *)e
8063 NSTRACE ("EmacsScroller_mouseDragged");
8065 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
8067 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
8073 else if (loc >= NSHeight (sr) + last_mouse_offset)
8075 loc = NSHeight (sr) + last_mouse_offset;
8078 pos = (loc - last_mouse_offset) / NSHeight (sr);
8079 [self sendScrollEventAtLoc: pos fromEvent: e];
8083 - (void)mouseUp: (NSEvent *)e
8085 if (scroll_repeat_entry)
8087 [scroll_repeat_entry invalidate];
8088 [scroll_repeat_entry release];
8089 scroll_repeat_entry = nil;
8091 last_hit_part = scroll_bar_above_handle;
8095 /* treat scrollwheel events in the bar as though they were in the main window */
8096 - (void) scrollWheel: (NSEvent *)theEvent
8098 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
8099 [view mouseDown: theEvent];
8102 @end /* EmacsScroller */
8105 #ifdef NS_IMPL_GNUSTEP
8106 /* Dummy class to get rid of startup warnings. */
8107 @implementation EmacsDocument
8113 /* ==========================================================================
8115 Font-related functions; these used to be in nsfaces.m
8117 ========================================================================== */
8121 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
8123 struct font *font = XFONT_OBJECT (font_object);
8124 EmacsView *view = FRAME_NS_VIEW (f);
8125 int font_ascent, font_descent;
8128 fontset = fontset_from_font (font_object);
8129 FRAME_FONTSET (f) = fontset;
8131 if (FRAME_FONT (f) == font)
8132 /* This font is already set in frame F. There's nothing more to
8136 FRAME_FONT (f) = font;
8138 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
8139 FRAME_COLUMN_WIDTH (f) = font->average_width;
8140 get_font_ascent_descent (font, &font_ascent, &font_descent);
8141 FRAME_LINE_HEIGHT (f) = font_ascent + font_descent;
8143 /* Compute the scroll bar width in character columns. */
8144 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
8146 int wid = FRAME_COLUMN_WIDTH (f);
8147 FRAME_CONFIG_SCROLL_BAR_COLS (f)
8148 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
8152 int wid = FRAME_COLUMN_WIDTH (f);
8153 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
8156 /* Compute the scroll bar height in character lines. */
8157 if (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) > 0)
8159 int height = FRAME_LINE_HEIGHT (f);
8160 FRAME_CONFIG_SCROLL_BAR_LINES (f)
8161 = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + height - 1) / height;
8165 int height = FRAME_LINE_HEIGHT (f);
8166 FRAME_CONFIG_SCROLL_BAR_LINES (f) = (14 + height - 1) / height;
8169 /* Now make the frame display the given font. */
8170 if (FRAME_NS_WINDOW (f) != 0 && ! [view isFullscreen])
8171 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
8172 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 3,
8179 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
8180 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
8184 ns_xlfd_to_fontname (const char *xlfd)
8185 /* --------------------------------------------------------------------------
8186 Convert an X font name (XLFD) to an NS font name.
8187 Only family is used.
8188 The string returned is temporarily allocated.
8189 -------------------------------------------------------------------------- */
8191 char *name = xmalloc (180);
8195 if (!strncmp (xlfd, "--", 2))
8196 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
8198 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
8200 /* stopgap for malformed XLFD input */
8201 if (strlen (name) == 0)
8202 strcpy (name, "Monaco");
8204 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
8205 also uppercase after '-' or ' ' */
8206 name[0] = c_toupper (name[0]);
8207 for (len =strlen (name), i =0; i<len; i++)
8213 name[i+1] = c_toupper (name[i+1]);
8215 else if (name[i] == '_')
8219 name[i+1] = c_toupper (name[i+1]);
8222 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
8223 ret = [[NSString stringWithUTF8String: name] UTF8String];
8230 syms_of_nsterm (void)
8232 NSTRACE ("syms_of_nsterm");
8234 ns_antialias_threshold = 10.0;
8236 /* from 23+ we need to tell emacs what modifiers there are.. */
8237 DEFSYM (Qmodifier_value, "modifier-value");
8238 DEFSYM (Qalt, "alt");
8239 DEFSYM (Qhyper, "hyper");
8240 DEFSYM (Qmeta, "meta");
8241 DEFSYM (Qsuper, "super");
8242 DEFSYM (Qcontrol, "control");
8243 DEFSYM (QUTF8_STRING, "UTF8_STRING");
8245 DEFSYM (Qfile, "file");
8246 DEFSYM (Qurl, "url");
8248 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
8249 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
8250 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
8251 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
8252 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
8254 DEFVAR_LISP ("ns-input-file", ns_input_file,
8255 "The file specified in the last NS event.");
8256 ns_input_file =Qnil;
8258 DEFVAR_LISP ("ns-working-text", ns_working_text,
8259 "String for visualizing working composition sequence.");
8260 ns_working_text =Qnil;
8262 DEFVAR_LISP ("ns-input-font", ns_input_font,
8263 "The font specified in the last NS event.");
8264 ns_input_font =Qnil;
8266 DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
8267 "The fontsize specified in the last NS event.");
8268 ns_input_fontsize =Qnil;
8270 DEFVAR_LISP ("ns-input-line", ns_input_line,
8271 "The line specified in the last NS event.");
8272 ns_input_line =Qnil;
8274 DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
8275 "The service name specified in the last NS event.");
8276 ns_input_spi_name =Qnil;
8278 DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
8279 "The service argument specified in the last NS event.");
8280 ns_input_spi_arg =Qnil;
8282 DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
8283 "This variable describes the behavior of the alternate or option key.\n\
8284 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8285 Set to none means that the alternate / option key is not interpreted by Emacs\n\
8286 at all, allowing it to be used at a lower level for accented character entry.");
8287 ns_alternate_modifier = Qmeta;
8289 DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
8290 "This variable describes the behavior of the right alternate or option key.\n\
8291 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8292 Set to left means be the same key as `ns-alternate-modifier'.\n\
8293 Set to none means that the alternate / option key is not interpreted by Emacs\n\
8294 at all, allowing it to be used at a lower level for accented character entry.");
8295 ns_right_alternate_modifier = Qleft;
8297 DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
8298 "This variable describes the behavior of the command key.\n\
8299 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
8300 ns_command_modifier = Qsuper;
8302 DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
8303 "This variable describes the behavior of the right command key.\n\
8304 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8305 Set to left means be the same key as `ns-command-modifier'.\n\
8306 Set to none means that the command / option key is not interpreted by Emacs\n\
8307 at all, allowing it to be used at a lower level for accented character entry.");
8308 ns_right_command_modifier = Qleft;
8310 DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
8311 "This variable describes the behavior of the control key.\n\
8312 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
8313 ns_control_modifier = Qcontrol;
8315 DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
8316 "This variable describes the behavior of the right control key.\n\
8317 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8318 Set to left means be the same key as `ns-control-modifier'.\n\
8319 Set to none means that the control / option key is not interpreted by Emacs\n\
8320 at all, allowing it to be used at a lower level for accented character entry.");
8321 ns_right_control_modifier = Qleft;
8323 DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
8324 "This variable describes the behavior of the function key (on laptops).\n\
8325 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8326 Set to none means that the function key is not interpreted by Emacs at all,\n\
8327 allowing it to be used at a lower level for accented character entry.");
8328 ns_function_modifier = Qnone;
8330 DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
8331 "Non-nil (the default) means to render text antialiased.");
8332 ns_antialias_text = Qt;
8334 DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
8335 "Whether to confirm application quit using dialog.");
8336 ns_confirm_quit = Qnil;
8338 DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
8339 doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
8340 Only works on OSX 10.6 or later. */);
8341 ns_auto_hide_menu_bar = Qnil;
8343 DEFVAR_BOOL ("ns-use-native-fullscreen", ns_use_native_fullscreen,
8344 doc: /*Non-nil means to use native fullscreen on OSX >= 10.7.
8345 Nil means use fullscreen the old (< 10.7) way. The old way works better with
8346 multiple monitors, but lacks tool bar. This variable is ignored on OSX < 10.7.
8347 Default is t for OSX >= 10.7, nil otherwise. */);
8348 #ifdef HAVE_NATIVE_FS
8349 ns_use_native_fullscreen = YES;
8351 ns_use_native_fullscreen = NO;
8353 ns_last_use_native_fullscreen = ns_use_native_fullscreen;
8355 DEFVAR_BOOL ("ns-use-fullscreen-animation", ns_use_fullscreen_animation,
8356 doc: /*Non-nil means use animation on non-native fullscreen.
8357 For native fullscreen, this does nothing.
8358 Default is nil. */);
8359 ns_use_fullscreen_animation = NO;
8361 DEFVAR_BOOL ("ns-use-srgb-colorspace", ns_use_srgb_colorspace,
8362 doc: /*Non-nil means to use sRGB colorspace on OSX >= 10.7.
8363 Note that this does not apply to images.
8364 This variable is ignored on OSX < 10.7 and GNUstep. */);
8365 ns_use_srgb_colorspace = YES;
8367 /* TODO: move to common code */
8368 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
8369 doc: /* Which toolkit scroll bars Emacs uses, if any.
8370 A value of nil means Emacs doesn't use toolkit scroll bars.
8371 With the X Window system, the value is a symbol describing the
8372 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
8373 With MS Windows or Nextstep, the value is t. */);
8374 Vx_toolkit_scroll_bars = Qt;
8376 DEFVAR_BOOL ("x-use-underline-position-properties",
8377 x_use_underline_position_properties,
8378 doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
8379 A value of nil means ignore them. If you encounter fonts with bogus
8380 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
8381 to 4.1, set this to nil. */);
8382 x_use_underline_position_properties = 0;
8384 DEFVAR_BOOL ("x-underline-at-descent-line",
8385 x_underline_at_descent_line,
8386 doc: /* Non-nil means to draw the underline at the same place as the descent line.
8387 A value of nil means to draw the underline according to the value of the
8388 variable `x-use-underline-position-properties', which is usually at the
8389 baseline level. The default value is nil. */);
8390 x_underline_at_descent_line = 0;
8392 /* Tell Emacs about this window system. */
8393 Fprovide (Qns, Qnil);
8395 DEFSYM (Qcocoa, "cocoa");
8396 DEFSYM (Qgnustep, "gnustep");
8398 #ifdef NS_IMPL_COCOA
8399 Fprovide (Qcocoa, Qnil);
8402 Fprovide (Qgnustep, Qnil);