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");
847 FOR_EACH_FRAME (tail, frame)
849 struct frame *f = XFRAME (frame);
852 NSView *view = FRAME_NS_VIEW (f);
854 [[view window] setFrame:constrain_frame_rect([[view window] frame])
861 /* Show or hide the menu bar, based on user setting. */
864 ns_update_auto_hide_menu_bar (void)
867 NSTRACE ("ns_update_auto_hide_menu_bar");
871 if (NSApp != nil && [NSApp isActive])
873 // Note, "setPresentationOptions" triggers an error unless the
874 // application is active.
875 BOOL menu_bar_should_be_hidden = ns_menu_bar_should_be_hidden ();
877 if (menu_bar_should_be_hidden != ns_menu_bar_is_hidden)
879 NSApplicationPresentationOptions options
880 = NSApplicationPresentationDefault;
882 if (menu_bar_should_be_hidden)
883 options |= NSApplicationPresentationAutoHideMenuBar
884 | NSApplicationPresentationAutoHideDock;
886 [NSApp setPresentationOptions: options];
888 ns_menu_bar_is_hidden = menu_bar_should_be_hidden;
890 if (!ns_menu_bar_is_hidden)
892 ns_constrain_all_frames ();
903 ns_update_begin (struct frame *f)
904 /* --------------------------------------------------------------------------
905 Prepare for a grouped sequence of drawing calls
906 external (RIF) call; whole frame, called before update_window_begin
907 -------------------------------------------------------------------------- */
909 EmacsView *view = FRAME_NS_VIEW (f);
910 NSTRACE ("ns_update_begin");
912 ns_update_auto_hide_menu_bar ();
915 if ([view isFullscreen] && [view fsIsNative])
917 // Fix reappearing tool bar in fullscreen for OSX 10.7
918 BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (f) ? YES : NO;
919 NSToolbar *toolbar = [FRAME_NS_VIEW (f) toolbar];
920 if (! tbar_visible != ! [toolbar isVisible])
921 [toolbar setVisible: tbar_visible];
925 ns_updating_frame = f;
928 /* drawRect may have been called for say the minibuffer, and then clip path
929 is for the minibuffer. But the display engine may draw more because
930 we have set the frame as garbaged. So reset clip path to the whole
935 NSRect r = [view frame];
936 NSRect cr = [[view window] frame];
937 /* If a large frame size is set, r may be larger than the window frame
938 before constrained. In that case don't change the clip path, as we
939 will clear in to the tool bar and title bar. */
941 + FRAME_NS_TITLEBAR_HEIGHT (f)
942 + FRAME_TOOLBAR_HEIGHT (f) <= cr.size.height)
944 bp = [[NSBezierPath bezierPathWithRect: r] retain];
951 #ifdef NS_IMPL_GNUSTEP
952 uRect = NSMakeRect (0, 0, 0, 0);
958 ns_update_window_begin (struct window *w)
959 /* --------------------------------------------------------------------------
960 Prepare for a grouped sequence of drawing calls
961 external (RIF) call; for one window, called after update_begin
962 -------------------------------------------------------------------------- */
964 struct frame *f = XFRAME (WINDOW_FRAME (w));
965 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
967 NSTRACE ("ns_update_window_begin");
968 w->output_cursor = w->cursor;
972 if (f == hlinfo->mouse_face_mouse_frame)
974 /* Don't do highlighting for mouse motion during the update. */
975 hlinfo->mouse_face_defer = 1;
977 /* If the frame needs to be redrawn,
978 simply forget about any prior mouse highlighting. */
979 if (FRAME_GARBAGED_P (f))
980 hlinfo->mouse_face_window = Qnil;
982 /* (further code for mouse faces ifdef'd out in other terms elided) */
990 ns_update_window_end (struct window *w, bool cursor_on_p,
991 bool mouse_face_overwritten_p)
992 /* --------------------------------------------------------------------------
993 Finished a grouped sequence of drawing calls
994 external (RIF) call; for one window called before update_end
995 -------------------------------------------------------------------------- */
997 NSTRACE ("update_window_end");
999 /* note: this fn is nearly identical in all terms */
1000 if (!w->pseudo_window_p)
1005 display_and_set_cursor (w, 1,
1006 w->output_cursor.hpos, w->output_cursor.vpos,
1007 w->output_cursor.x, w->output_cursor.y);
1009 if (draw_window_fringes (w, 1))
1011 if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
1012 x_draw_right_divider (w);
1014 x_draw_vertical_border (w);
1020 /* If a row with mouse-face was overwritten, arrange for
1021 frame_up_to_date to redisplay the mouse highlight. */
1022 if (mouse_face_overwritten_p)
1023 reset_mouse_highlight (MOUSE_HL_INFO (XFRAME (w->frame)));
1028 ns_update_end (struct frame *f)
1029 /* --------------------------------------------------------------------------
1030 Finished a grouped sequence of drawing calls
1031 external (RIF) call; for whole frame, called after update_window_end
1032 -------------------------------------------------------------------------- */
1034 EmacsView *view = FRAME_NS_VIEW (f);
1036 NSTRACE ("ns_update_end");
1038 /* if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
1039 MOUSE_HL_INFO (f)->mouse_face_defer = 0;
1044 [[view window] flushWindow];
1047 ns_updating_frame = NULL;
1051 ns_focus (struct frame *f, NSRect *r, int n)
1052 /* --------------------------------------------------------------------------
1053 Internal: Focus on given frame. During small local updates this is used to
1054 draw, however during large updates, ns_update_begin and ns_update_end are
1055 called to wrap the whole thing, in which case these calls are stubbed out.
1056 Except, on GNUstep, we accumulate the rectangle being drawn into, because
1057 the back end won't do this automatically, and will just end up flushing
1059 -------------------------------------------------------------------------- */
1061 // NSTRACE ("ns_focus");
1063 fprintf (stderr, "focus: %d", c++);
1064 if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
1065 fprintf (stderr, "\n"); */
1067 if (f != ns_updating_frame)
1069 NSView *view = FRAME_NS_VIEW (f);
1070 if (view != focus_view)
1072 if (focus_view != NULL)
1074 [focus_view unlockFocus];
1075 [[focus_view window] flushWindow];
1082 /*if (view) debug_lock++; */
1089 [[NSGraphicsContext currentContext] saveGraphicsState];
1091 NSRectClipList (r, 2);
1100 ns_unfocus (struct frame *f)
1101 /* --------------------------------------------------------------------------
1102 Internal: Remove focus on given frame
1103 -------------------------------------------------------------------------- */
1105 // NSTRACE ("ns_unfocus");
1109 [[NSGraphicsContext currentContext] restoreGraphicsState];
1113 if (f != ns_updating_frame)
1115 if (focus_view != NULL)
1117 [focus_view unlockFocus];
1118 [[focus_view window] flushWindow];
1127 ns_clip_to_row (struct window *w, struct glyph_row *row,
1128 enum glyph_row_area area, BOOL gc)
1129 /* --------------------------------------------------------------------------
1130 Internal (but parallels other terms): Focus drawing on given row
1131 -------------------------------------------------------------------------- */
1133 struct frame *f = XFRAME (WINDOW_FRAME (w));
1135 int window_x, window_y, window_width;
1137 window_box (w, area, &window_x, &window_y, &window_width, 0);
1139 clip_rect.origin.x = window_x;
1140 clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
1141 clip_rect.origin.y = max (clip_rect.origin.y, window_y);
1142 clip_rect.size.width = window_width;
1143 clip_rect.size.height = row->visible_height;
1145 ns_focus (f, &clip_rect, 1);
1150 ns_ring_bell (struct frame *f)
1151 /* --------------------------------------------------------------------------
1153 -------------------------------------------------------------------------- */
1155 NSTRACE ("ns_ring_bell");
1158 NSAutoreleasePool *pool;
1159 struct frame *frame = SELECTED_FRAME ();
1163 pool = [[NSAutoreleasePool alloc] init];
1165 view = FRAME_NS_VIEW (frame);
1169 NSPoint dim = NSMakePoint (128, 128);
1172 r.origin.x += (r.size.width - dim.x) / 2;
1173 r.origin.y += (r.size.height - dim.y) / 2;
1174 r.size.width = dim.x;
1175 r.size.height = dim.y;
1176 surr = NSInsetRect (r, -2, -2);
1177 ns_focus (frame, &surr, 1);
1178 [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
1179 [ns_lookup_indexed_color (NS_FACE_FOREGROUND
1180 (FRAME_DEFAULT_FACE (frame)), frame) set];
1182 [[view window] flushWindow];
1183 ns_timeout (150000);
1184 [[view window] restoreCachedImage];
1185 [[view window] flushWindow];
1197 /* ==========================================================================
1199 Frame / window manager related functions
1201 ========================================================================== */
1205 ns_raise_frame (struct frame *f)
1206 /* --------------------------------------------------------------------------
1207 Bring window to foreground and make it active
1208 -------------------------------------------------------------------------- */
1211 check_window_system (f);
1212 view = FRAME_NS_VIEW (f);
1214 if (FRAME_VISIBLE_P (f))
1215 [[view window] makeKeyAndOrderFront: NSApp];
1221 ns_lower_frame (struct frame *f)
1222 /* --------------------------------------------------------------------------
1224 -------------------------------------------------------------------------- */
1227 check_window_system (f);
1228 view = FRAME_NS_VIEW (f);
1230 [[view window] orderBack: NSApp];
1236 ns_frame_raise_lower (struct frame *f, bool raise)
1237 /* --------------------------------------------------------------------------
1239 -------------------------------------------------------------------------- */
1241 NSTRACE ("ns_frame_raise_lower");
1251 ns_frame_rehighlight (struct frame *frame)
1252 /* --------------------------------------------------------------------------
1253 External (hook): called on things like window switching within frame
1254 -------------------------------------------------------------------------- */
1256 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
1257 struct frame *old_highlight = dpyinfo->x_highlight_frame;
1259 NSTRACE ("ns_frame_rehighlight");
1260 if (dpyinfo->x_focus_frame)
1262 dpyinfo->x_highlight_frame
1263 = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1264 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1265 : dpyinfo->x_focus_frame);
1266 if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
1268 fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
1269 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
1273 dpyinfo->x_highlight_frame = 0;
1275 if (dpyinfo->x_highlight_frame &&
1276 dpyinfo->x_highlight_frame != old_highlight)
1280 x_update_cursor (old_highlight, 1);
1281 x_set_frame_alpha (old_highlight);
1283 if (dpyinfo->x_highlight_frame)
1285 x_update_cursor (dpyinfo->x_highlight_frame, 1);
1286 x_set_frame_alpha (dpyinfo->x_highlight_frame);
1293 x_make_frame_visible (struct frame *f)
1294 /* --------------------------------------------------------------------------
1295 External: Show the window (X11 semantics)
1296 -------------------------------------------------------------------------- */
1298 NSTRACE ("x_make_frame_visible");
1299 /* XXX: at some points in past this was not needed, as the only place that
1300 called this (frame.c:Fraise_frame ()) also called raise_lower;
1301 if this ends up the case again, comment this out again. */
1302 if (!FRAME_VISIBLE_P (f))
1304 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1306 SET_FRAME_VISIBLE (f, 1);
1309 /* Making a new frame from a fullscreen frame will make the new frame
1310 fullscreen also. So skip handleFS as this will print an error. */
1311 if ([view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH
1312 && [view isFullscreen])
1315 if (f->want_fullscreen != FULLSCREEN_NONE)
1326 x_make_frame_invisible (struct frame *f)
1327 /* --------------------------------------------------------------------------
1328 External: Hide the window (X11 semantics)
1329 -------------------------------------------------------------------------- */
1332 NSTRACE ("x_make_frame_invisible");
1333 check_window_system (f);
1334 view = FRAME_NS_VIEW (f);
1335 [[view window] orderOut: NSApp];
1336 SET_FRAME_VISIBLE (f, 0);
1337 SET_FRAME_ICONIFIED (f, 0);
1342 x_iconify_frame (struct frame *f)
1343 /* --------------------------------------------------------------------------
1344 External: Iconify window
1345 -------------------------------------------------------------------------- */
1348 struct ns_display_info *dpyinfo;
1350 NSTRACE ("x_iconify_frame");
1351 check_window_system (f);
1352 view = FRAME_NS_VIEW (f);
1353 dpyinfo = FRAME_DISPLAY_INFO (f);
1355 if (dpyinfo->x_highlight_frame == f)
1356 dpyinfo->x_highlight_frame = 0;
1358 if ([[view window] windowNumber] <= 0)
1360 /* the window is still deferred. Make it very small, bring it
1361 on screen and order it out. */
1362 NSRect s = { { 100, 100}, {0, 0} };
1364 t = [[view window] frame];
1365 [[view window] setFrame: s display: NO];
1366 [[view window] orderBack: NSApp];
1367 [[view window] orderOut: NSApp];
1368 [[view window] setFrame: t display: NO];
1370 [[view window] miniaturize: NSApp];
1373 /* Free X resources of frame F. */
1376 x_free_frame_resources (struct frame *f)
1379 struct ns_display_info *dpyinfo;
1380 Mouse_HLInfo *hlinfo;
1382 NSTRACE ("x_free_frame_resources");
1383 check_window_system (f);
1384 view = FRAME_NS_VIEW (f);
1385 dpyinfo = FRAME_DISPLAY_INFO (f);
1386 hlinfo = MOUSE_HL_INFO (f);
1388 [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1392 free_frame_menubar (f);
1393 free_frame_faces (f);
1395 if (f == dpyinfo->x_focus_frame)
1396 dpyinfo->x_focus_frame = 0;
1397 if (f == dpyinfo->x_highlight_frame)
1398 dpyinfo->x_highlight_frame = 0;
1399 if (f == hlinfo->mouse_face_mouse_frame)
1400 reset_mouse_highlight (hlinfo);
1402 if (f->output_data.ns->miniimage != nil)
1403 [f->output_data.ns->miniimage release];
1405 [[view window] close];
1408 xfree (f->output_data.ns);
1414 x_destroy_window (struct frame *f)
1415 /* --------------------------------------------------------------------------
1416 External: Delete the window
1417 -------------------------------------------------------------------------- */
1419 NSTRACE ("x_destroy_window");
1420 check_window_system (f);
1421 x_free_frame_resources (f);
1427 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1428 /* --------------------------------------------------------------------------
1429 External: Position the window
1430 -------------------------------------------------------------------------- */
1432 NSView *view = FRAME_NS_VIEW (f);
1433 NSArray *screens = [NSScreen screens];
1434 NSScreen *fscreen = [screens objectAtIndex: 0];
1435 NSScreen *screen = [[view window] screen];
1437 NSTRACE ("x_set_offset");
1444 if (view != nil && screen && fscreen)
1446 f->left_pos = f->size_hint_flags & XNegative
1447 ? [screen visibleFrame].size.width + f->left_pos - FRAME_PIXEL_WIDTH (f)
1449 /* We use visibleFrame here to take menu bar into account.
1450 Ideally we should also adjust left/top with visibleFrame.origin. */
1452 f->top_pos = f->size_hint_flags & YNegative
1453 ? ([screen visibleFrame].size.height + f->top_pos
1454 - FRAME_PIXEL_HEIGHT (f) - FRAME_NS_TITLEBAR_HEIGHT (f)
1455 - FRAME_TOOLBAR_HEIGHT (f))
1457 #ifdef NS_IMPL_GNUSTEP
1458 if (f->left_pos < 100)
1459 f->left_pos = 100; /* don't overlap menu */
1461 /* Constrain the setFrameTopLeftPoint so we don't move behind the
1463 NSPoint pt = NSMakePoint (SCREENMAXBOUND (f->left_pos),
1464 SCREENMAXBOUND ([fscreen frame].size.height
1466 NSTRACE_POINT ("setFrameTopLeftPoint", pt);
1467 [[view window] setFrameTopLeftPoint: pt];
1468 f->size_hint_flags &= ~(XNegative|YNegative);
1476 x_set_window_size (struct frame *f,
1477 bool change_gravity,
1481 /* --------------------------------------------------------------------------
1482 Adjust window pixel size based on given character grid size
1483 Impl is a bit more complex than other terms, need to do some
1485 -------------------------------------------------------------------------- */
1487 EmacsView *view = FRAME_NS_VIEW (f);
1488 NSWindow *window = [view window];
1489 NSRect wr = [window frame];
1490 int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1491 int pixelwidth, pixelheight;
1493 int orig_height = wr.size.height;
1495 NSTRACE ("x_set_window_size");
1500 NSTRACE_RECT ("current", wr);
1502 /*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));*/
1508 pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
1509 pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
1510 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, pixelwidth);
1511 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, pixelheight);
1515 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, width);
1516 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, height);
1521 /* If we have a toolbar, take its height into account. */
1522 if (tb && ! [view isFullscreen])
1524 /* NOTE: previously this would generate wrong result if toolbar not
1525 yet displayed and fixing toolbar_height=32 helped, but
1526 now (200903) seems no longer needed */
1527 FRAME_TOOLBAR_HEIGHT (f) =
1528 NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1529 - FRAME_NS_TITLEBAR_HEIGHT (f);
1531 /* Only breaks things here, removed by martin 2015-09-30. */
1532 #ifdef NS_IMPL_GNUSTEP
1533 FRAME_TOOLBAR_HEIGHT (f) -= 3;
1538 FRAME_TOOLBAR_HEIGHT (f) = 0;
1540 wr.size.width = pixelwidth + f->border_width;
1541 wr.size.height = pixelheight;
1542 if (! [view isFullscreen])
1543 wr.size.height += FRAME_NS_TITLEBAR_HEIGHT (f)
1544 + FRAME_TOOLBAR_HEIGHT (f);
1546 /* Do not try to constrain to this screen. We may have multiple
1547 screens, and want Emacs to span those. Constraining to screen
1548 prevents that, and that is not nice to the user. */
1549 if (f->output_data.ns->zooming)
1550 f->output_data.ns->zooming = 0;
1552 wr.origin.y += orig_height - wr.size.height;
1554 frame_size_history_add
1555 (f, Qx_set_window_size_1, width, height,
1556 list5 (Fcons (make_number (pixelwidth), make_number (pixelheight)),
1557 Fcons (make_number (wr.size.width), make_number (wr.size.height)),
1558 make_number (f->border_width),
1559 make_number (FRAME_NS_TITLEBAR_HEIGHT (f)),
1560 make_number (FRAME_TOOLBAR_HEIGHT (f))));
1562 NSTRACE_RECT ("setFrame", wr);
1563 [window setFrame: wr display: YES];
1565 /* This is a trick to compensate for Emacs' managing the scrollbar area
1566 as a fixed number of standard character columns. Instead of leaving
1567 blank space for the extra, we chopped it off above. Now for
1568 left-hand scrollbars, we shift all rendering to the left by the
1569 difference between the real width and Emacs' imagined one. For
1570 right-hand bars, don't worry about it since the extra is never used.
1571 (Obviously doesn't work for vertically split windows tho..) */
1573 NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1574 ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1575 - NS_SCROLL_BAR_WIDTH (f), 0)
1576 : NSMakePoint (0, 0);
1577 NSTRACE_RECT ("setFrame", wr);
1578 [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1579 [view setBoundsOrigin: origin];
1582 [view updateFrameSize: NO];
1588 ns_fullscreen_hook (struct frame *f)
1590 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1592 NSTRACE ("ns_fullscreen_hook");
1594 if (!FRAME_VISIBLE_P (f))
1597 if (! [view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH)
1599 /* Old style fs don't initiate correctly if created from
1600 init/default-frame alist, so use a timer (not nice...).
1602 [NSTimer scheduledTimerWithTimeInterval: 0.5 target: view
1603 selector: @selector (handleFS)
1604 userInfo: nil repeats: NO];
1613 /* ==========================================================================
1617 ========================================================================== */
1621 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1623 struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1624 if (idx < 1 || idx >= color_table->avail)
1626 return color_table->colors[idx];
1631 ns_index_color (NSColor *color, struct frame *f)
1633 struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1637 if (!color_table->colors)
1639 color_table->size = NS_COLOR_CAPACITY;
1640 color_table->avail = 1; /* skip idx=0 as marker */
1641 color_table->colors = xmalloc (color_table->size * sizeof (NSColor *));
1642 color_table->colors[0] = nil;
1643 color_table->empty_indices = [[NSMutableSet alloc] init];
1646 /* Do we already have this color? */
1647 for (i = 1; i < color_table->avail; i++)
1648 if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1651 if ([color_table->empty_indices count] > 0)
1653 NSNumber *index = [color_table->empty_indices anyObject];
1654 [color_table->empty_indices removeObject: index];
1655 idx = [index unsignedLongValue];
1659 if (color_table->avail == color_table->size)
1660 color_table->colors =
1661 xpalloc (color_table->colors, &color_table->size, 1,
1662 min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1663 idx = color_table->avail++;
1666 color_table->colors[idx] = color;
1668 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1674 ns_free_indexed_color (unsigned long idx, struct frame *f)
1676 struct ns_color_table *color_table;
1683 color_table = FRAME_DISPLAY_INFO (f)->color_table;
1685 if (idx <= 0 || idx >= color_table->size) {
1686 message1 ("ns_free_indexed_color: Color index out of range.\n");
1690 index = [NSNumber numberWithUnsignedInt: idx];
1691 if ([color_table->empty_indices containsObject: index]) {
1692 message1 ("ns_free_indexed_color: attempt to free already freed color.\n");
1696 color = color_table->colors[idx];
1698 color_table->colors[idx] = nil;
1699 [color_table->empty_indices addObject: index];
1700 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1705 ns_get_color (const char *name, NSColor **col)
1706 /* --------------------------------------------------------------------------
1708 -------------------------------------------------------------------------- */
1709 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1710 X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1711 See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1714 static char hex[20];
1716 float r = -1.0, g, b;
1717 NSString *nsname = [NSString stringWithUTF8String: name];
1719 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1722 if ([nsname isEqualToString: @"ns_selection_bg_color"])
1724 #ifdef NS_IMPL_COCOA
1725 NSString *defname = [[NSUserDefaults standardUserDefaults]
1726 stringForKey: @"AppleHighlightColor"];
1731 if ((new = [NSColor selectedTextBackgroundColor]) != nil)
1733 *col = [new colorUsingDefaultColorSpace];
1738 nsname = NS_SELECTION_BG_COLOR_DEFAULT;
1740 name = [nsname UTF8String];
1742 else if ([nsname isEqualToString: @"ns_selection_fg_color"])
1744 /* NOTE: OSX applications normally don't set foreground selection, but
1745 text may be unreadable if we don't.
1747 if ((new = [NSColor selectedTextColor]) != nil)
1749 *col = [new colorUsingDefaultColorSpace];
1754 nsname = NS_SELECTION_FG_COLOR_DEFAULT;
1755 name = [nsname UTF8String];
1758 /* First, check for some sort of numeric specification. */
1761 if (name[0] == '0' || name[0] == '1' || name[0] == '.') /* RGB decimal */
1763 NSScanner *scanner = [NSScanner scannerWithString: nsname];
1764 [scanner scanFloat: &r];
1765 [scanner scanFloat: &g];
1766 [scanner scanFloat: &b];
1768 else if (!strncmp(name, "rgb:", 4)) /* A newer X11 format -- rgb:r/g/b */
1769 scaling = (snprintf (hex, sizeof hex, "%s", name + 4) - 2) / 3;
1770 else if (name[0] == '#') /* An old X11 format; convert to newer */
1772 int len = (strlen(name) - 1);
1773 int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1775 scaling = strlen(name+start) / 3;
1776 for (i = 0; i < 3; i++)
1777 sprintf (hex + i * (scaling + 1), "%.*s/", scaling,
1778 name + start + i * scaling);
1779 hex[3 * (scaling + 1) - 1] = '\0';
1785 float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1786 if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1796 *col = [NSColor colorForEmacsRed: r green: g blue: b alpha: 1.0];
1801 /* Otherwise, color is expected to be from a list */
1803 NSEnumerator *lenum, *cenum;
1807 #ifdef NS_IMPL_GNUSTEP
1808 /* XXX: who is wrong, the requestor or the implementation? */
1809 if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1811 nsname = @"highlightColor";
1814 lenum = [[NSColorList availableColorLists] objectEnumerator];
1815 while ( (clist = [lenum nextObject]) && new == nil)
1817 cenum = [[clist allKeys] objectEnumerator];
1818 while ( (name = [cenum nextObject]) && new == nil )
1820 if ([name compare: nsname
1821 options: NSCaseInsensitiveSearch] == NSOrderedSame )
1822 new = [clist colorWithKey: name];
1828 *col = [new colorUsingDefaultColorSpace];
1835 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1836 /* --------------------------------------------------------------------------
1837 Convert a Lisp string object to a NS color
1838 -------------------------------------------------------------------------- */
1840 NSTRACE ("ns_lisp_to_color");
1841 if (STRINGP (color))
1842 return ns_get_color (SSDATA (color), col);
1843 else if (SYMBOLP (color))
1844 return ns_get_color (SSDATA (SYMBOL_NAME (color)), col);
1850 ns_color_to_lisp (NSColor *col)
1851 /* --------------------------------------------------------------------------
1852 Convert a color to a lisp string with the RGB equivalent
1853 -------------------------------------------------------------------------- */
1855 EmacsCGFloat red, green, blue, alpha, gray;
1858 NSTRACE ("ns_color_to_lisp");
1861 if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1863 if ((str =[[col colorNameComponent] UTF8String]))
1866 return build_string ((char *)str);
1869 [[col colorUsingDefaultColorSpace]
1870 getRed: &red green: &green blue: &blue alpha: &alpha];
1871 if (red == green && red == blue)
1873 [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1874 getWhite: &gray alpha: &alpha];
1875 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1876 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1878 return build_string (buf);
1881 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1882 lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1885 return build_string (buf);
1890 ns_query_color(void *col, XColor *color_def, int setPixel)
1891 /* --------------------------------------------------------------------------
1892 Get ARGB values out of NSColor col and put them into color_def.
1893 If setPixel, set the pixel to a concatenated version.
1894 and set color_def pixel to the resulting index.
1895 -------------------------------------------------------------------------- */
1897 EmacsCGFloat r, g, b, a;
1899 [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1900 color_def->red = r * 65535;
1901 color_def->green = g * 65535;
1902 color_def->blue = b * 65535;
1904 if (setPixel == YES)
1906 = ARGB_TO_ULONG((int)(a*255),
1907 (int)(r*255), (int)(g*255), (int)(b*255));
1912 ns_defined_color (struct frame *f,
1917 /* --------------------------------------------------------------------------
1918 Return true if named color found, and set color_def rgb accordingly.
1919 If makeIndex and alloc are nonzero put the color in the color_table,
1920 and set color_def pixel to the resulting index.
1921 If makeIndex is zero, set color_def pixel to ARGB.
1922 Return false if not found
1923 -------------------------------------------------------------------------- */
1926 NSTRACE ("ns_defined_color");
1929 if (ns_get_color (name, &col) != 0) /* Color not found */
1934 if (makeIndex && alloc)
1935 color_def->pixel = ns_index_color (col, f);
1936 ns_query_color (col, color_def, !makeIndex);
1943 x_set_frame_alpha (struct frame *f)
1944 /* --------------------------------------------------------------------------
1945 change the entire-frame transparency
1946 -------------------------------------------------------------------------- */
1948 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1950 double alpha_min = 1.0;
1952 if (dpyinfo->x_highlight_frame == f)
1953 alpha = f->alpha[0];
1955 alpha = f->alpha[1];
1957 if (FLOATP (Vframe_alpha_lower_limit))
1958 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1959 else if (INTEGERP (Vframe_alpha_lower_limit))
1960 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1964 else if (1.0 < alpha)
1966 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1969 #ifdef NS_IMPL_COCOA
1971 EmacsView *view = FRAME_NS_VIEW (f);
1972 [[view window] setAlphaValue: alpha];
1978 /* ==========================================================================
1982 ========================================================================== */
1986 frame_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1987 /* --------------------------------------------------------------------------
1988 Programmatically reposition mouse pointer in pixel coordinates
1989 -------------------------------------------------------------------------- */
1991 NSTRACE ("frame_set_mouse_pixel_position");
1994 /* FIXME: this does not work, and what about GNUstep? */
1995 #ifdef NS_IMPL_COCOA
1996 [FRAME_NS_VIEW (f) lockFocus];
1997 PSsetmouse ((float)pix_x, (float)pix_y);
1998 [FRAME_NS_VIEW (f) unlockFocus];
2004 note_mouse_movement (struct frame *frame, CGFloat x, CGFloat y)
2005 /* ------------------------------------------------------------------------
2006 Called by EmacsView on mouseMovement events. Passes on
2007 to emacs mainstream code if we moved off of a rect of interest
2008 known as last_mouse_glyph.
2009 ------------------------------------------------------------------------ */
2011 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
2014 // NSTRACE ("note_mouse_movement");
2016 dpyinfo->last_mouse_motion_frame = frame;
2017 r = &dpyinfo->last_mouse_glyph;
2019 /* Note, this doesn't get called for enter/leave, since we don't have a
2020 position. Those are taken care of in the corresponding NSView methods. */
2022 /* has movement gone beyond last rect we were tracking? */
2023 if (x < r->origin.x || x >= r->origin.x + r->size.width
2024 || y < r->origin.y || y >= r->origin.y + r->size.height)
2026 ns_update_begin (frame);
2027 frame->mouse_moved = 1;
2028 note_mouse_highlight (frame, x, y);
2029 remember_mouse_glyph (frame, x, y, r);
2030 ns_update_end (frame);
2039 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
2040 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
2042 /* --------------------------------------------------------------------------
2043 External (hook): inform emacs about mouse position and hit parts.
2044 If a scrollbar is being dragged, set bar_window, part, x, y, time.
2045 x & y should be position in the scrollbar (the whole bar, not the handle)
2046 and length of scrollbar respectively
2047 -------------------------------------------------------------------------- */
2051 Lisp_Object frame, tail;
2053 struct ns_display_info *dpyinfo;
2055 NSTRACE ("ns_mouse_position");
2059 fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
2063 dpyinfo = FRAME_DISPLAY_INFO (*fp);
2067 /* Clear the mouse-moved flag for every frame on this display. */
2068 FOR_EACH_FRAME (tail, frame)
2069 if (FRAME_NS_P (XFRAME (frame))
2070 && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
2071 XFRAME (frame)->mouse_moved = 0;
2073 dpyinfo->last_mouse_scroll_bar = nil;
2074 if (dpyinfo->last_mouse_frame
2075 && FRAME_LIVE_P (dpyinfo->last_mouse_frame))
2076 f = dpyinfo->last_mouse_frame;
2078 f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame : SELECTED_FRAME ();
2080 if (f && FRAME_NS_P (f))
2082 view = FRAME_NS_VIEW (*fp);
2084 position = [[view window] mouseLocationOutsideOfEventStream];
2085 position = [view convertPoint: position fromView: nil];
2086 remember_mouse_glyph (f, position.x, position.y,
2087 &dpyinfo->last_mouse_glyph);
2088 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
2090 if (bar_window) *bar_window = Qnil;
2091 if (part) *part = scroll_bar_above_handle;
2093 if (x) XSETINT (*x, lrint (position.x));
2094 if (y) XSETINT (*y, lrint (position.y));
2096 *time = dpyinfo->last_mouse_movement_time;
2105 ns_frame_up_to_date (struct frame *f)
2106 /* --------------------------------------------------------------------------
2107 External (hook): Fix up mouse highlighting right after a full update.
2108 Can't use FRAME_MOUSE_UPDATE due to ns_frame_begin and ns_frame_end calls.
2109 -------------------------------------------------------------------------- */
2111 NSTRACE ("ns_frame_up_to_date");
2115 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
2116 if (f == hlinfo->mouse_face_mouse_frame)
2120 note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
2121 hlinfo->mouse_face_mouse_x,
2122 hlinfo->mouse_face_mouse_y);
2131 ns_define_frame_cursor (struct frame *f, Cursor cursor)
2132 /* --------------------------------------------------------------------------
2133 External (RIF): set frame mouse pointer type.
2134 -------------------------------------------------------------------------- */
2136 NSTRACE ("ns_define_frame_cursor");
2137 if (FRAME_POINTER_TYPE (f) != cursor)
2139 EmacsView *view = FRAME_NS_VIEW (f);
2140 FRAME_POINTER_TYPE (f) = cursor;
2141 [[view window] invalidateCursorRectsForView: view];
2142 /* Redisplay assumes this function also draws the changed frame
2143 cursor, but this function doesn't, so do it explicitly. */
2144 x_update_cursor (f, 1);
2150 /* ==========================================================================
2154 ========================================================================== */
2158 ns_convert_key (unsigned code)
2159 /* --------------------------------------------------------------------------
2160 Internal call used by NSView-keyDown.
2161 -------------------------------------------------------------------------- */
2163 const unsigned last_keysym = ARRAYELTS (convert_ns_to_X_keysym);
2165 /* An array would be faster, but less easy to read. */
2166 for (keysym = 0; keysym < last_keysym; keysym += 2)
2167 if (code == convert_ns_to_X_keysym[keysym])
2168 return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
2170 /* if decide to use keyCode and Carbon table, use this line:
2171 return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
2176 x_get_keysym_name (int keysym)
2177 /* --------------------------------------------------------------------------
2178 Called by keyboard.c. Not sure if the return val is important, except
2180 -------------------------------------------------------------------------- */
2182 static char value[16];
2183 NSTRACE ("x_get_keysym_name");
2184 sprintf (value, "%d", keysym);
2190 /* ==========================================================================
2192 Block drawing operations
2194 ========================================================================== */
2198 ns_redraw_scroll_bars (struct frame *f)
2202 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
2203 NSTRACE ("ns_redraw_scroll_bars");
2204 for (i =[subviews count]-1; i >= 0; i--)
2206 view = [subviews objectAtIndex: i];
2207 if (![view isKindOfClass: [EmacsScroller class]]) continue;
2214 ns_clear_frame (struct frame *f)
2215 /* --------------------------------------------------------------------------
2216 External (hook): Erase the entire frame
2217 -------------------------------------------------------------------------- */
2219 NSView *view = FRAME_NS_VIEW (f);
2222 NSTRACE ("ns_clear_frame");
2224 /* comes on initial frame because we have
2225 after-make-frame-functions = select-frame */
2226 if (!FRAME_DEFAULT_FACE (f))
2229 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2234 ns_focus (f, &r, 1);
2235 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
2239 /* as of 2006/11 or so this is now needed */
2240 ns_redraw_scroll_bars (f);
2246 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2247 /* --------------------------------------------------------------------------
2248 External (RIF): Clear section of frame
2249 -------------------------------------------------------------------------- */
2251 NSRect r = NSMakeRect (x, y, width, height);
2252 NSView *view = FRAME_NS_VIEW (f);
2253 struct face *face = FRAME_DEFAULT_FACE (f);
2258 NSTRACE ("ns_clear_frame_area");
2260 r = NSIntersectionRect (r, [view frame]);
2261 ns_focus (f, &r, 1);
2262 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2271 ns_copy_bits (struct frame *f, NSRect src, NSRect dest)
2273 if (FRAME_NS_VIEW (f))
2275 ns_focus (f, &dest, 1);
2276 [FRAME_NS_VIEW (f) scrollRect: src
2277 by: NSMakeSize (dest.origin.x - src.origin.x,
2278 dest.origin.y - src.origin.y)];
2284 ns_scroll_run (struct window *w, struct run *run)
2285 /* --------------------------------------------------------------------------
2286 External (RIF): Insert or delete n lines at line vpos
2287 -------------------------------------------------------------------------- */
2289 struct frame *f = XFRAME (w->frame);
2290 int x, y, width, height, from_y, to_y, bottom_y;
2292 NSTRACE ("ns_scroll_run");
2294 /* begin copy from other terms */
2295 /* Get frame-relative bounding box of the text display area of W,
2296 without mode lines. Include in this box the left and right
2298 window_box (w, ANY_AREA, &x, &y, &width, &height);
2300 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2301 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2302 bottom_y = y + height;
2306 /* Scrolling up. Make sure we don't copy part of the mode
2307 line at the bottom. */
2308 if (from_y + run->height > bottom_y)
2309 height = bottom_y - from_y;
2311 height = run->height;
2315 /* Scrolling down. Make sure we don't copy over the mode line.
2317 if (to_y + run->height > bottom_y)
2318 height = bottom_y - to_y;
2320 height = run->height;
2322 /* end copy from other terms */
2332 NSRect srcRect = NSMakeRect (x, from_y, width, height);
2333 NSRect dstRect = NSMakeRect (x, to_y, width, height);
2335 ns_copy_bits (f, srcRect , dstRect);
2343 ns_after_update_window_line (struct window *w, struct glyph_row *desired_row)
2344 /* --------------------------------------------------------------------------
2345 External (RIF): preparatory to fringe update after text was updated
2346 -------------------------------------------------------------------------- */
2351 NSTRACE ("ns_after_update_window_line");
2353 /* begin copy from other terms */
2356 if (!desired_row->mode_line_p && !w->pseudo_window_p)
2357 desired_row->redraw_fringe_bitmaps_p = 1;
2359 /* When a window has disappeared, make sure that no rest of
2360 full-width rows stays visible in the internal border. */
2361 if (windows_or_buffers_changed
2362 && desired_row->full_width_p
2363 && (f = XFRAME (w->frame),
2364 width = FRAME_INTERNAL_BORDER_WIDTH (f),
2366 && (height = desired_row->visible_height,
2369 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2372 ns_clear_frame_area (f, 0, y, width, height);
2373 ns_clear_frame_area (f,
2374 FRAME_PIXEL_WIDTH (f) - width,
2382 ns_shift_glyphs_for_insert (struct frame *f,
2383 int x, int y, int width, int height,
2385 /* --------------------------------------------------------------------------
2386 External (RIF): copy an area horizontally, don't worry about clearing src
2387 -------------------------------------------------------------------------- */
2389 NSRect srcRect = NSMakeRect (x, y, width, height);
2390 NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2392 NSTRACE ("ns_shift_glyphs_for_insert");
2394 ns_copy_bits (f, srcRect, dstRect);
2399 /* ==========================================================================
2401 Character encoding and metrics
2403 ========================================================================== */
2407 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2408 /* --------------------------------------------------------------------------
2409 External (RIF); compute left/right overhang of whole string and set in s
2410 -------------------------------------------------------------------------- */
2412 struct font *font = s->font;
2416 struct font_metrics metrics;
2417 unsigned int codes[2];
2418 codes[0] = *(s->char2b);
2419 codes[1] = *(s->char2b + s->nchars - 1);
2421 font->driver->text_extents (font, codes, 2, &metrics);
2422 s->left_overhang = -metrics.lbearing;
2424 = metrics.rbearing > metrics.width
2425 ? metrics.rbearing - metrics.width : 0;
2429 s->left_overhang = 0;
2430 if (EQ (font->driver->type, Qns))
2431 s->right_overhang = ((struct nsfont_info *)font)->ital ?
2432 FONT_HEIGHT (font) * 0.2 : 0;
2434 s->right_overhang = 0;
2440 /* ==========================================================================
2442 Fringe and cursor drawing
2444 ========================================================================== */
2447 extern int max_used_fringe_bitmap;
2449 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2450 struct draw_fringe_bitmap_params *p)
2451 /* --------------------------------------------------------------------------
2452 External (RIF); fringe-related
2453 -------------------------------------------------------------------------- */
2455 struct frame *f = XFRAME (WINDOW_FRAME (w));
2456 struct face *face = p->face;
2457 static EmacsImage **bimgs = NULL;
2458 static int nBimgs = 0;
2460 /* grow bimgs if needed */
2461 if (nBimgs < max_used_fringe_bitmap)
2463 bimgs = xrealloc (bimgs, max_used_fringe_bitmap * sizeof *bimgs);
2464 memset (bimgs + nBimgs, 0,
2465 (max_used_fringe_bitmap - nBimgs) * sizeof *bimgs);
2466 nBimgs = max_used_fringe_bitmap;
2469 /* Must clip because of partially visible lines. */
2470 ns_clip_to_row (w, row, ANY_AREA, YES);
2474 int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
2476 if (bx >= 0 && nx > 0)
2478 NSRect r = NSMakeRect (bx, by, nx, ny);
2480 [ns_lookup_indexed_color (face->background, f) set];
2487 NSRect r = NSMakeRect (p->x, p->y, p->wd, p->h);
2488 EmacsImage *img = bimgs[p->which - 1];
2492 unsigned short *bits = p->bits + p->dh;
2495 unsigned char *cbits = xmalloc (len);
2497 for (i = 0; i < len; i++)
2498 cbits[i] = ~(bits[i] & 0xff);
2499 img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2501 bimgs[p->which - 1] = img;
2506 /* Since we composite the bitmap instead of just blitting it, we need
2507 to erase the whole background. */
2508 [ns_lookup_indexed_color(face->background, f) set];
2514 bm_color = ns_lookup_indexed_color(face->foreground, f);
2515 else if (p->overlay_p)
2516 bm_color = ns_lookup_indexed_color(face->background, f);
2518 bm_color = f->output_data.ns->cursor_color;
2519 [img setXBMColor: bm_color];
2522 #ifdef NS_IMPL_COCOA
2524 fromRect: NSZeroRect
2525 operation: NSCompositeSourceOver
2531 NSPoint pt = r.origin;
2533 [img compositeToPoint: pt operation: NSCompositeSourceOver];
2542 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2543 int x, int y, enum text_cursor_kinds cursor_type,
2544 int cursor_width, bool on_p, bool active_p)
2545 /* --------------------------------------------------------------------------
2546 External call (RIF): draw cursor.
2547 Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2548 -------------------------------------------------------------------------- */
2551 int fx, fy, h, cursor_height;
2552 struct frame *f = WINDOW_XFRAME (w);
2553 struct glyph *phys_cursor_glyph;
2554 struct glyph *cursor_glyph;
2556 NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2558 /* If cursor is out of bounds, don't draw garbage. This can happen
2559 in mini-buffer windows when switching between echo area glyphs
2562 NSTRACE ("dumpcursor");
2567 w->phys_cursor_type = cursor_type;
2568 w->phys_cursor_on_p = on_p;
2570 if (cursor_type == NO_CURSOR)
2572 w->phys_cursor_width = 0;
2576 if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2578 if (glyph_row->exact_window_width_line_p
2579 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2581 glyph_row->cursor_in_fringe_p = 1;
2582 draw_fringe_bitmap (w, glyph_row, 0);
2587 /* We draw the cursor (with NSRectFill), then draw the glyph on top
2588 (other terminals do it the other way round). We must set
2589 w->phys_cursor_width to the cursor width. For bar cursors, that
2590 is CURSOR_WIDTH; for box cursors, it is the glyph width. */
2591 get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2593 /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2594 to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2595 if (cursor_type == BAR_CURSOR)
2597 if (cursor_width < 1)
2598 cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2599 w->phys_cursor_width = cursor_width;
2601 /* If we have an HBAR, "cursor_width" MAY specify height. */
2602 else if (cursor_type == HBAR_CURSOR)
2604 cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2605 if (cursor_height > glyph_row->height)
2606 cursor_height = glyph_row->height;
2607 if (h > cursor_height) // Cursor smaller than line height, move down
2608 fy += h - cursor_height;
2612 r.origin.x = fx, r.origin.y = fy;
2614 r.size.width = w->phys_cursor_width;
2616 /* TODO: only needed in rare cases with last-resort font in HELLO..
2617 should we do this more efficiently? */
2618 ns_clip_to_row (w, glyph_row, ANY_AREA, NO); /* do ns_focus(f, &r, 1); if remove */
2621 face = FACE_FROM_ID (f, phys_cursor_glyph->face_id);
2622 if (face && NS_FACE_BACKGROUND (face)
2623 == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2625 [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2626 hollow_color = FRAME_CURSOR_COLOR (f);
2629 [FRAME_CURSOR_COLOR (f) set];
2631 #ifdef NS_IMPL_COCOA
2632 /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2633 atomic. Cleaner ways of doing this should be investigated.
2634 One way would be to set a global variable DRAWING_CURSOR
2635 when making the call to draw_phys..(), don't focus in that
2636 case, then move the ns_unfocus() here after that call. */
2637 NSDisableScreenUpdates ();
2640 switch (cursor_type)
2642 case DEFAULT_CURSOR:
2645 case FILLED_BOX_CURSOR:
2648 case HOLLOW_BOX_CURSOR:
2651 NSRectFill (NSInsetRect (r, 1, 1));
2652 [FRAME_CURSOR_COLOR (f) set];
2659 /* If the character under cursor is R2L, draw the bar cursor
2660 on the right of its glyph, rather than on the left. */
2661 cursor_glyph = get_phys_cursor_glyph (w);
2662 if ((cursor_glyph->resolved_level & 1) != 0)
2663 s.origin.x += cursor_glyph->pixel_width - s.size.width;
2670 /* draw the character under the cursor */
2671 if (cursor_type != NO_CURSOR)
2672 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2674 #ifdef NS_IMPL_COCOA
2675 NSEnableScreenUpdates ();
2682 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2683 /* --------------------------------------------------------------------------
2684 External (RIF): Draw a vertical line.
2685 -------------------------------------------------------------------------- */
2687 struct frame *f = XFRAME (WINDOW_FRAME (w));
2689 NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2691 NSTRACE ("ns_draw_vertical_window_border");
2693 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2695 [ns_lookup_indexed_color(face->foreground, f) set];
2697 ns_focus (f, &r, 1);
2704 ns_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
2705 /* --------------------------------------------------------------------------
2706 External (RIF): Draw a window divider.
2707 -------------------------------------------------------------------------- */
2709 struct frame *f = XFRAME (WINDOW_FRAME (w));
2711 NSRect r = NSMakeRect (x0, y0, x1-x0, y1-y0);
2713 NSTRACE ("ns_draw_window_divider");
2715 face = FACE_FROM_ID (f, WINDOW_DIVIDER_FACE_ID);
2717 [ns_lookup_indexed_color(face->foreground, f) set];
2719 ns_focus (f, &r, 1);
2725 ns_show_hourglass (struct frame *f)
2727 /* TODO: add NSProgressIndicator to all frames. */
2731 ns_hide_hourglass (struct frame *f)
2733 /* TODO: remove NSProgressIndicator from all frames. */
2736 /* ==========================================================================
2738 Glyph drawing operations
2740 ========================================================================== */
2743 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2744 /* --------------------------------------------------------------------------
2745 Wrapper utility to account for internal border width on full-width lines,
2746 and allow top full-width rows to hit the frame top. nr should be pointer
2747 to two successive NSRects. Number of rects actually used is returned.
2748 -------------------------------------------------------------------------- */
2750 int n = get_glyph_string_clip_rects (s, nr, 2);
2754 /* --------------------------------------------------------------------
2755 Draw a wavy line under glyph string s. The wave fills wave_height
2762 wave_height = 3 | * * * *
2763 --------------------------------------------------------------------- */
2766 ns_draw_underwave (struct glyph_string *s, EmacsCGFloat width, EmacsCGFloat x)
2768 int wave_height = 3, wave_length = 2;
2769 int y, dx, dy, odd, xmax;
2774 dy = wave_height - 1;
2775 y = s->ybase - wave_height + 3;
2778 /* Find and set clipping rectangle */
2779 waveClip = NSMakeRect (x, y, width, wave_height);
2780 [[NSGraphicsContext currentContext] saveGraphicsState];
2781 NSRectClip (waveClip);
2783 /* Draw the waves */
2784 a.x = x - ((int)(x) % dx) + (EmacsCGFloat) 0.5;
2786 odd = (int)(a.x/dx) % 2;
2787 a.y = b.y = y + 0.5;
2796 [NSBezierPath strokeLineFromPoint:a toPoint:b];
2797 a.x = b.x, a.y = b.y;
2798 b.x += dx, b.y = y + 0.5 + odd*dy;
2802 /* Restore previous clipping rectangle(s) */
2803 [[NSGraphicsContext currentContext] restoreGraphicsState];
2809 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
2810 NSColor *defaultCol, CGFloat width, CGFloat x)
2811 /* --------------------------------------------------------------------------
2812 Draw underline, overline, and strike-through on glyph string s.
2813 -------------------------------------------------------------------------- */
2815 if (s->for_overlaps)
2819 if (face->underline_p)
2821 if (s->face->underline_type == FACE_UNDER_WAVE)
2823 if (face->underline_defaulted_p)
2826 [ns_lookup_indexed_color (face->underline_color, s->f) set];
2828 ns_draw_underwave (s, width, x);
2830 else if (s->face->underline_type == FACE_UNDER_LINE)
2834 unsigned long thickness, position;
2836 /* If the prev was underlined, match its appearance. */
2837 if (s->prev && s->prev->face->underline_p
2838 && s->prev->face->underline_type == FACE_UNDER_LINE
2839 && s->prev->underline_thickness > 0)
2841 thickness = s->prev->underline_thickness;
2842 position = s->prev->underline_position;
2847 unsigned long descent;
2850 descent = s->y + s->height - s->ybase;
2852 /* Use underline thickness of font, defaulting to 1. */
2853 thickness = (font && font->underline_thickness > 0)
2854 ? font->underline_thickness : 1;
2856 /* Determine the offset of underlining from the baseline. */
2857 if (x_underline_at_descent_line)
2858 position = descent - thickness;
2859 else if (x_use_underline_position_properties
2860 && font && font->underline_position >= 0)
2861 position = font->underline_position;
2863 position = lround (font->descent / 2);
2865 position = underline_minimum_offset;
2867 position = max (position, underline_minimum_offset);
2869 /* Ensure underlining is not cropped. */
2870 if (descent <= position)
2872 position = descent - 1;
2875 else if (descent < position + thickness)
2879 s->underline_thickness = thickness;
2880 s->underline_position = position;
2882 r = NSMakeRect (x, s->ybase + position, width, thickness);
2884 if (face->underline_defaulted_p)
2887 [ns_lookup_indexed_color (face->underline_color, s->f) set];
2891 /* Do overline. We follow other terms in using a thickness of 1
2892 and ignoring overline_margin. */
2893 if (face->overline_p)
2896 r = NSMakeRect (x, s->y, width, 1);
2898 if (face->overline_color_defaulted_p)
2901 [ns_lookup_indexed_color (face->overline_color, s->f) set];
2905 /* Do strike-through. We follow other terms for thickness and
2906 vertical position.*/
2907 if (face->strike_through_p)
2912 dy = lrint ((s->height - 1) / 2);
2913 r = NSMakeRect (x, s->y + dy, width, 1);
2915 if (face->strike_through_color_defaulted_p)
2918 [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
2924 ns_draw_box (NSRect r, CGFloat thickness, NSColor *col,
2925 char left_p, char right_p)
2926 /* --------------------------------------------------------------------------
2927 Draw an unfilled rect inside r, optionally leaving left and/or right open.
2928 Note we can't just use an NSDrawRect command, because of the possibility
2929 of some sides not being drawn, and because the rect will be filled.
2930 -------------------------------------------------------------------------- */
2936 s.size.height = thickness;
2938 s.origin.y += r.size.height - thickness;
2941 s.size.height = r.size.height;
2942 s.origin.y = r.origin.y;
2944 /* left, right (optional) */
2945 s.size.width = thickness;
2950 s.origin.x += r.size.width - thickness;
2957 ns_draw_relief (NSRect r, int thickness, char raised_p,
2958 char top_p, char bottom_p, char left_p, char right_p,
2959 struct glyph_string *s)
2960 /* --------------------------------------------------------------------------
2961 Draw a relief rect inside r, optionally leaving some sides open.
2962 Note we can't just use an NSDrawBezel command, because of the possibility
2963 of some sides not being drawn, and because the rect will be filled.
2964 -------------------------------------------------------------------------- */
2966 static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2967 NSColor *newBaseCol = nil;
2970 NSTRACE ("ns_draw_relief");
2974 if (s->face->use_box_color_for_shadows_p)
2976 newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2978 /* else if (s->first_glyph->type == IMAGE_GLYPH
2980 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2982 newBaseCol = IMAGE_BACKGROUND (s->img, s->f, 0);
2986 newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2989 if (newBaseCol == nil)
2990 newBaseCol = [NSColor grayColor];
2992 if (newBaseCol != baseCol) /* TODO: better check */
2995 baseCol = [newBaseCol retain];
2997 lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2999 darkCol = [[baseCol shadowWithLevel: 0.3] retain];
3002 [(raised_p ? lightCol : darkCol) set];
3004 /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
3007 sr.size.height = thickness;
3008 if (top_p) NSRectFill (sr);
3011 sr.size.height = r.size.height;
3012 sr.size.width = thickness;
3013 if (left_p) NSRectFill (sr);
3015 [(raised_p ? darkCol : lightCol) set];
3018 sr.size.width = r.size.width;
3019 sr.size.height = thickness;
3020 sr.origin.y += r.size.height - thickness;
3021 if (bottom_p) NSRectFill (sr);
3024 sr.size.height = r.size.height;
3025 sr.origin.y = r.origin.y;
3026 sr.size.width = thickness;
3027 sr.origin.x += r.size.width - thickness;
3028 if (right_p) NSRectFill (sr);
3033 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
3034 /* --------------------------------------------------------------------------
3035 Function modeled after x_draw_glyph_string_box ().
3036 Sets up parameters for drawing.
3037 -------------------------------------------------------------------------- */
3039 int right_x, last_x;
3040 char left_p, right_p;
3041 struct glyph *last_glyph;
3046 if (s->hl == DRAW_MOUSE_FACE)
3048 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3050 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3055 thickness = face->box_line_width;
3057 NSTRACE ("ns_dumpglyphs_box_or_relief");
3059 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
3060 ? WINDOW_RIGHT_EDGE_X (s->w)
3061 : window_box_right (s->w, s->area));
3062 last_glyph = (s->cmp || s->img
3063 ? s->first_glyph : s->first_glyph + s->nchars-1);
3065 right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
3066 ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
3068 left_p = (s->first_glyph->left_box_line_p
3069 || (s->hl == DRAW_MOUSE_FACE
3070 && (s->prev == NULL || s->prev->hl != s->hl)));
3071 right_p = (last_glyph->right_box_line_p
3072 || (s->hl == DRAW_MOUSE_FACE
3073 && (s->next == NULL || s->next->hl != s->hl)));
3075 r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
3077 /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
3078 if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
3080 ns_draw_box (r, abs (thickness),
3081 ns_lookup_indexed_color (face->box_color, s->f),
3086 ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
3087 1, 1, left_p, right_p, s);
3093 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
3094 /* --------------------------------------------------------------------------
3095 Modeled after x_draw_glyph_string_background, which draws BG in
3096 certain cases. Others are left to the text rendering routine.
3097 -------------------------------------------------------------------------- */
3099 NSTRACE ("ns_maybe_dumpglyphs_background");
3101 if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
3103 int box_line_width = max (s->face->box_line_width, 0);
3104 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
3105 /* When xdisp.c ignores FONT_HEIGHT, we cannot trust font
3106 dimensions, since the actual glyphs might be much
3107 smaller. So in that case we always clear the rectangle
3108 with background color. */
3109 || FONT_TOO_HIGH (s->font)
3110 || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
3113 if (s->hl == DRAW_MOUSE_FACE)
3115 face = FACE_FROM_ID (s->f,
3116 MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3118 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3121 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3123 [(NS_FACE_BACKGROUND (face) != 0
3124 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
3125 : FRAME_BACKGROUND_COLOR (s->f)) set];
3128 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (s->f);
3129 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
3132 if (s->hl != DRAW_CURSOR)
3134 NSRect r = NSMakeRect (s->x, s->y + box_line_width,
3135 s->background_width,
3136 s->height-2*box_line_width);
3140 s->background_filled_p = 1;
3147 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
3148 /* --------------------------------------------------------------------------
3149 Renders an image and associated borders.
3150 -------------------------------------------------------------------------- */
3152 EmacsImage *img = s->img->pixmap;
3153 int box_line_vwidth = max (s->face->box_line_width, 0);
3154 int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3155 int bg_x, bg_y, bg_height;
3162 NSTRACE ("ns_dumpglyphs_image");
3164 if (s->face->box != FACE_NO_BOX
3165 && s->first_glyph->left_box_line_p && s->slice.x == 0)
3166 x += abs (s->face->box_line_width);
3169 bg_y = s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
3170 bg_height = s->height;
3171 /* other terms have this, but was causing problems w/tabbar mode */
3172 /* - 2 * box_line_vwidth; */
3174 if (s->slice.x == 0) x += s->img->hmargin;
3175 if (s->slice.y == 0) y += s->img->vmargin;
3177 /* Draw BG: if we need larger area than image itself cleared, do that,
3178 otherwise, since we composite the image under NS (instead of mucking
3179 with its background color), we must clear just the image area. */
3180 if (s->hl == DRAW_MOUSE_FACE)
3182 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3184 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3187 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3189 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
3191 if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
3192 || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
3194 br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
3195 s->background_filled_p = 1;
3199 br = NSMakeRect (x, y, s->slice.width, s->slice.height);
3204 /* Draw the image.. do we need to draw placeholder if img ==nil? */
3207 #ifdef NS_IMPL_COCOA
3208 NSRect dr = NSMakeRect (x, y, s->slice.width, s->slice.height);
3209 NSRect ir = NSMakeRect (s->slice.x, s->slice.y,
3210 s->slice.width, s->slice.height);
3213 operation: NSCompositeSourceOver
3218 [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3219 operation: NSCompositeSourceOver];
3223 if (s->hl == DRAW_CURSOR)
3225 [FRAME_CURSOR_COLOR (s->f) set];
3226 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3227 tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3229 /* Currently on NS img->mask is always 0. Since
3230 get_window_cursor_type specifies a hollow box cursor when on
3231 a non-masked image we never reach this clause. But we put it
3232 in in anticipation of better support for image masks on
3234 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3238 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3241 /* Draw underline, overline, strike-through. */
3242 ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3244 /* Draw relief, if requested */
3245 if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3247 if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3249 th = tool_bar_button_relief >= 0 ?
3250 tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3251 raised_p = (s->hl == DRAW_IMAGE_RAISED);
3255 th = abs (s->img->relief);
3256 raised_p = (s->img->relief > 0);
3259 r.origin.x = x - th;
3260 r.origin.y = y - th;
3261 r.size.width = s->slice.width + 2*th-1;
3262 r.size.height = s->slice.height + 2*th-1;
3263 ns_draw_relief (r, th, raised_p,
3265 s->slice.y + s->slice.height == s->img->height,
3267 s->slice.x + s->slice.width == s->img->width, s);
3270 /* If there is no mask, the background won't be seen,
3271 so draw a rectangle on the image for the cursor.
3272 Do this for all images, getting transparency right is not reliable. */
3273 if (s->hl == DRAW_CURSOR)
3275 int thickness = abs (s->img->relief);
3276 if (thickness == 0) thickness = 1;
3277 ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3283 ns_dumpglyphs_stretch (struct glyph_string *s)
3288 NSColor *fgCol, *bgCol;
3290 if (!s->background_filled_p)
3292 n = ns_get_glyph_string_clip_rect (s, r);
3293 *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3295 ns_focus (s->f, r, n);
3297 if (s->hl == DRAW_MOUSE_FACE)
3299 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3301 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3304 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3306 bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3307 fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3309 for (i = 0; i < n; ++i)
3311 if (!s->row->full_width_p)
3313 int overrun, leftoverrun;
3315 /* truncate to avoid overwriting fringe and/or scrollbar */
3316 overrun = max (0, (s->x + s->background_width)
3317 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3318 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3319 r[i].size.width -= overrun;
3321 /* truncate to avoid overwriting to left of the window box */
3322 leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3323 + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3325 if (leftoverrun > 0)
3327 r[i].origin.x += leftoverrun;
3328 r[i].size.width -= leftoverrun;
3331 /* XXX: Try to work between problem where a stretch glyph on
3332 a partially-visible bottom row will clear part of the
3333 modeline, and another where list-buffers headers and similar
3334 rows erroneously have visible_height set to 0. Not sure
3335 where this is coming from as other terms seem not to show. */
3336 r[i].size.height = min (s->height, s->row->visible_height);
3341 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3342 overwriting cursor (usually when cursor on a tab) */
3343 if (s->hl == DRAW_CURSOR)
3348 width = s->w->phys_cursor_width;
3349 r[i].size.width -= width;
3350 r[i].origin.x += width;
3354 /* Draw overlining, etc. on the cursor. */
3355 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3356 ns_draw_text_decoration (s, face, bgCol, width, x);
3358 ns_draw_text_decoration (s, face, fgCol, width, x);
3365 /* Draw overlining, etc. on the stretch glyph (or the part
3366 of the stretch glyph after the cursor). */
3367 ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3371 s->background_filled_p = 1;
3377 ns_draw_composite_glyph_string_foreground (struct glyph_string *s)
3380 struct font *font = s->font;
3382 /* If first glyph of S has a left box line, start drawing the text
3383 of S to the right of that box line. */
3384 if (s->face && s->face->box != FACE_NO_BOX
3385 && s->first_glyph->left_box_line_p)
3386 x = s->x + eabs (s->face->box_line_width);
3390 /* S is a glyph string for a composition. S->cmp_from is the index
3391 of the first character drawn for glyphs of this composition.
3392 S->cmp_from == 0 means we are drawing the very first character of
3393 this composition. */
3395 /* Draw a rectangle for the composition if the font for the very
3396 first character of the composition could not be loaded. */
3397 if (s->font_not_found_p)
3399 if (s->cmp_from == 0)
3401 NSRect r = NSMakeRect (s->x, s->y, s->width-1, s->height -1);
3402 ns_draw_box (r, 1, FRAME_CURSOR_COLOR (s->f), 1, 1);
3405 else if (! s->first_glyph->u.cmp.automatic)
3409 for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
3410 /* TAB in a composition means display glyphs with padding
3411 space on the left or right. */
3412 if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
3414 int xx = x + s->cmp->offsets[j * 2];
3415 int yy = y - s->cmp->offsets[j * 2 + 1];
3417 font->driver->draw (s, j, j + 1, xx, yy, false);
3418 if (s->face->overstrike)
3419 font->driver->draw (s, j, j + 1, xx + 1, yy, false);
3424 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
3429 for (i = j = s->cmp_from; i < s->cmp_to; i++)
3431 glyph = LGSTRING_GLYPH (gstring, i);
3432 if (NILP (LGLYPH_ADJUSTMENT (glyph)))
3433 width += LGLYPH_WIDTH (glyph);
3436 int xoff, yoff, wadjust;
3440 font->driver->draw (s, j, i, x, y, false);
3441 if (s->face->overstrike)
3442 font->driver->draw (s, j, i, x + 1, y, false);
3445 xoff = LGLYPH_XOFF (glyph);
3446 yoff = LGLYPH_YOFF (glyph);
3447 wadjust = LGLYPH_WADJUST (glyph);
3448 font->driver->draw (s, i, i + 1, x + xoff, y + yoff, false);
3449 if (s->face->overstrike)
3450 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff,
3459 font->driver->draw (s, j, i, x, y, false);
3460 if (s->face->overstrike)
3461 font->driver->draw (s, j, i, x + 1, y, false);
3467 ns_draw_glyph_string (struct glyph_string *s)
3468 /* --------------------------------------------------------------------------
3469 External (RIF): Main draw-text call.
3470 -------------------------------------------------------------------------- */
3472 /* TODO (optimize): focus for box and contents draw */
3475 char box_drawn_p = 0;
3476 struct font *font = s->face->font;
3477 if (! font) font = FRAME_FONT (s->f);
3479 NSTRACE ("ns_draw_glyph_string");
3481 if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3484 struct glyph_string *next;
3486 for (width = 0, next = s->next;
3487 next && width < s->right_overhang;
3488 width += next->width, next = next->next)
3489 if (next->first_glyph->type != IMAGE_GLYPH)
3491 if (next->first_glyph->type != STRETCH_GLYPH)
3493 n = ns_get_glyph_string_clip_rect (s->next, r);
3494 ns_focus (s->f, r, n);
3495 ns_maybe_dumpglyphs_background (s->next, 1);
3500 ns_dumpglyphs_stretch (s->next);
3502 next->num_clips = 0;
3506 if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3507 && (s->first_glyph->type == CHAR_GLYPH
3508 || s->first_glyph->type == COMPOSITE_GLYPH))
3510 n = ns_get_glyph_string_clip_rect (s, r);
3511 ns_focus (s->f, r, n);
3512 ns_maybe_dumpglyphs_background (s, 1);
3513 ns_dumpglyphs_box_or_relief (s);
3518 switch (s->first_glyph->type)
3522 n = ns_get_glyph_string_clip_rect (s, r);
3523 ns_focus (s->f, r, n);
3524 ns_dumpglyphs_image (s, r[0]);
3529 ns_dumpglyphs_stretch (s);
3533 case COMPOSITE_GLYPH:
3534 n = ns_get_glyph_string_clip_rect (s, r);
3535 ns_focus (s->f, r, n);
3537 if (s->for_overlaps || (s->cmp_from > 0
3538 && ! s->first_glyph->u.cmp.automatic))
3539 s->background_filled_p = 1;
3541 ns_maybe_dumpglyphs_background
3542 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3544 flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3545 (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3546 (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3547 NS_DUMPGLYPH_NORMAL));
3549 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3551 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3552 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3553 NS_FACE_FOREGROUND (s->face) = tmp;
3557 BOOL isComposite = s->first_glyph->type == COMPOSITE_GLYPH;
3560 ns_draw_composite_glyph_string_foreground (s);
3563 (s, s->cmp_from, s->nchars, s->x, s->ybase,
3564 (flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3565 || flags == NS_DUMPGLYPH_MOUSEFACE);
3569 NSColor *col = (NS_FACE_FOREGROUND (s->face) != 0
3570 ? ns_lookup_indexed_color (NS_FACE_FOREGROUND (s->face),
3572 : FRAME_FOREGROUND_COLOR (s->f));
3575 /* Draw underline, overline, strike-through. */
3576 ns_draw_text_decoration (s, s->face, col, s->width, s->x);
3579 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3581 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3582 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3583 NS_FACE_FOREGROUND (s->face) = tmp;
3589 case GLYPHLESS_GLYPH:
3590 n = ns_get_glyph_string_clip_rect (s, r);
3591 ns_focus (s->f, r, n);
3593 if (s->for_overlaps || (s->cmp_from > 0
3594 && ! s->first_glyph->u.cmp.automatic))
3595 s->background_filled_p = 1;
3597 ns_maybe_dumpglyphs_background
3598 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3600 /* Not yet implemented. */
3609 /* Draw box if not done already. */
3610 if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3612 n = ns_get_glyph_string_clip_rect (s, r);
3613 ns_focus (s->f, r, n);
3614 ns_dumpglyphs_box_or_relief (s);
3623 /* ==========================================================================
3627 ========================================================================== */
3631 ns_send_appdefined (int value)
3632 /* --------------------------------------------------------------------------
3633 Internal: post an appdefined event which EmacsApp-sendEvent will
3634 recognize and take as a command to halt the event loop.
3635 -------------------------------------------------------------------------- */
3637 /*NSTRACE ("ns_send_appdefined"); */
3639 #ifdef NS_IMPL_GNUSTEP
3640 // GNUstep needs postEvent to happen on the main thread.
3641 if (! [[NSThread currentThread] isMainThread])
3643 EmacsApp *app = (EmacsApp *)NSApp;
3644 app->nextappdefined = value;
3645 [app performSelectorOnMainThread:@selector (sendFromMainThread:)
3652 /* Only post this event if we haven't already posted one. This will end
3653 the [NXApp run] main loop after having processed all events queued at
3656 #ifdef NS_IMPL_COCOA
3657 if (! send_appdefined)
3659 /* OSX 10.10.1 swallows the AppDefined event we are sending ourselves
3660 in certain situations (rapid incoming events).
3661 So check if we have one, if not add one. */
3662 NSEvent *appev = [NSApp nextEventMatchingMask:NSApplicationDefinedMask
3663 untilDate:[NSDate distantPast]
3664 inMode:NSDefaultRunLoopMode
3666 if (! appev) send_appdefined = YES;
3670 if (send_appdefined)
3674 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
3675 send_appdefined = NO;
3677 /* Don't need wakeup timer any more */
3680 [timed_entry invalidate];
3681 [timed_entry release];
3685 nxev = [NSEvent otherEventWithType: NSApplicationDefined
3686 location: NSMakePoint (0, 0)
3689 windowNumber: [[NSApp mainWindow] windowNumber]
3690 context: [NSApp context]
3695 /* Post an application defined event on the event queue. When this is
3696 received the [NXApp run] will return, thus having processed all
3697 events which are currently queued. */
3698 [NSApp postEvent: nxev atStart: NO];
3702 #ifdef HAVE_NATIVE_FS
3706 Lisp_Object frame, tail;
3708 if (ns_last_use_native_fullscreen == ns_use_native_fullscreen)
3711 ns_last_use_native_fullscreen = ns_use_native_fullscreen;
3713 FOR_EACH_FRAME (tail, frame)
3715 struct frame *f = XFRAME (frame);
3718 EmacsView *view = FRAME_NS_VIEW (f);
3719 [view updateCollectionBehavior];
3725 /* GNUstep does not have cancelTracking. */
3726 #ifdef NS_IMPL_COCOA
3727 /* Check if menu open should be canceled or continued as normal. */
3729 ns_check_menu_open (NSMenu *menu)
3731 /* Click in menu bar? */
3732 NSArray *a = [[NSApp mainMenu] itemArray];
3736 if (menu == nil) // Menu tracking ended.
3738 if (menu_will_open_state == MENU_OPENING)
3739 menu_will_open_state = MENU_NONE;
3743 for (i = 0; ! found && i < [a count]; i++)
3744 found = menu == [[a objectAtIndex:i] submenu];
3747 if (menu_will_open_state == MENU_NONE && emacs_event)
3749 NSEvent *theEvent = [NSApp currentEvent];
3750 struct frame *emacsframe = SELECTED_FRAME ();
3752 [menu cancelTracking];
3753 menu_will_open_state = MENU_PENDING;
3754 emacs_event->kind = MENU_BAR_ACTIVATE_EVENT;
3755 EV_TRAILER (theEvent);
3757 CGEventRef ourEvent = CGEventCreate (NULL);
3758 menu_mouse_point = CGEventGetLocation (ourEvent);
3759 CFRelease (ourEvent);
3761 else if (menu_will_open_state == MENU_OPENING)
3763 menu_will_open_state = MENU_NONE;
3768 /* Redo saved menu click if state is MENU_PENDING. */
3770 ns_check_pending_open_menu ()
3772 if (menu_will_open_state == MENU_PENDING)
3774 CGEventSourceRef source
3775 = CGEventSourceCreate (kCGEventSourceStateHIDSystemState);
3777 CGEventRef event = CGEventCreateMouseEvent (source,
3778 kCGEventLeftMouseDown,
3780 kCGMouseButtonLeft);
3781 CGEventSetType (event, kCGEventLeftMouseDown);
3782 CGEventPost (kCGHIDEventTap, event);
3786 menu_will_open_state = MENU_OPENING;
3789 #endif /* NS_IMPL_COCOA */
3792 unwind_apploopnr (Lisp_Object not_used)
3795 n_emacs_events_pending = 0;
3796 ns_finish_events ();
3801 ns_read_socket (struct terminal *terminal, struct input_event *hold_quit)
3802 /* --------------------------------------------------------------------------
3803 External (hook): Post an event to ourself and keep reading events until
3804 we read it back again. In effect process all events which were waiting.
3805 From 21+ we have to manage the event buffer ourselves.
3806 -------------------------------------------------------------------------- */
3808 struct input_event ev;
3811 /* NSTRACE ("ns_read_socket"); */
3813 #ifdef HAVE_NATIVE_FS
3817 if ([NSApp modalWindow] != nil)
3820 if (hold_event_q.nr > 0)
3823 for (i = 0; i < hold_event_q.nr; ++i)
3824 kbd_buffer_store_event_hold (&hold_event_q.q[i], hold_quit);
3825 hold_event_q.nr = 0;
3830 n_emacs_events_pending = 0;
3831 ns_init_events (&ev);
3832 q_event_ptr = hold_quit;
3834 /* we manage autorelease pools by allocate/reallocate each time around
3835 the loop; strict nesting is occasionally violated but seems not to
3836 matter.. earlier methods using full nesting caused major memory leaks */
3837 [outerpool release];
3838 outerpool = [[NSAutoreleasePool alloc] init];
3840 /* If have pending open-file requests, attend to the next one of those. */
3841 if (ns_pending_files && [ns_pending_files count] != 0
3842 && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3844 [ns_pending_files removeObjectAtIndex: 0];
3846 /* Deal with pending service requests. */
3847 else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3849 NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3850 withArg: [ns_pending_service_args objectAtIndex: 0]])
3852 [ns_pending_service_names removeObjectAtIndex: 0];
3853 [ns_pending_service_args removeObjectAtIndex: 0];
3857 ptrdiff_t specpdl_count = SPECPDL_INDEX ();
3858 /* Run and wait for events. We must always send one NX_APPDEFINED event
3859 to ourself, otherwise [NXApp run] will never exit. */
3860 send_appdefined = YES;
3861 ns_send_appdefined (-1);
3863 if (++apploopnr != 1)
3867 record_unwind_protect (unwind_apploopnr, Qt);
3869 unbind_to (specpdl_count, Qnil); /* calls unwind_apploopnr */
3872 nevents = n_emacs_events_pending;
3873 n_emacs_events_pending = 0;
3874 ns_finish_events ();
3883 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3884 fd_set *exceptfds, struct timespec const *timeout,
3885 sigset_t const *sigmask)
3886 /* --------------------------------------------------------------------------
3887 Replacement for select, checking for events
3888 -------------------------------------------------------------------------- */
3892 struct input_event event;
3895 /* NSTRACE ("ns_select"); */
3897 #ifdef HAVE_NATIVE_FS
3901 if (hold_event_q.nr > 0)
3903 /* We already have events pending. */
3909 for (k = 0; k < nfds+1; k++)
3911 if (readfds && FD_ISSET(k, readfds)) ++nr;
3912 if (writefds && FD_ISSET(k, writefds)) ++nr;
3916 || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0))
3917 return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
3919 [outerpool release];
3920 outerpool = [[NSAutoreleasePool alloc] init];
3923 send_appdefined = YES;
3926 pthread_mutex_lock (&select_mutex);
3931 select_readfds = *readfds;
3932 select_valid += SELECT_HAVE_READ;
3936 select_writefds = *writefds;
3937 select_valid += SELECT_HAVE_WRITE;
3942 select_timeout = *timeout;
3943 select_valid += SELECT_HAVE_TMO;
3946 pthread_mutex_unlock (&select_mutex);
3948 /* Inform fd_handler that select should be called */
3950 emacs_write_sig (selfds[1], &c, 1);
3952 else if (nr == 0 && timeout)
3954 /* No file descriptor, just a timeout, no need to wake fd_handler */
3955 double time = timespectod (*timeout);
3956 timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3959 @selector (timeout_handler:)
3964 else /* No timeout and no file descriptors, can this happen? */
3966 /* Send appdefined so we exit from the loop */
3967 ns_send_appdefined (-1);
3971 ns_init_events (&event);
3972 if (++apploopnr != 1)
3978 ptrdiff_t specpdl_count = SPECPDL_INDEX ();
3979 record_unwind_protect (unwind_apploopnr, Qt);
3981 unbind_to (specpdl_count, Qnil); /* calls unwind_apploopnr */
3984 ns_finish_events ();
3985 if (nr > 0 && readfds)
3988 emacs_write_sig (selfds[1], &c, 1);
3992 t = last_appdefined_event_data;
3994 if (t != NO_APPDEFINED_DATA)
3996 last_appdefined_event_data = NO_APPDEFINED_DATA;
4000 /* The NX_APPDEFINED event we received was a timeout. */
4005 /* The NX_APPDEFINED event we received was the result of
4006 at least one real input event arriving. */
4012 /* Received back from select () in fd_handler; copy the results */
4013 pthread_mutex_lock (&select_mutex);
4014 if (readfds) *readfds = select_readfds;
4015 if (writefds) *writefds = select_writefds;
4016 pthread_mutex_unlock (&select_mutex);
4031 /* ==========================================================================
4035 ========================================================================== */
4039 ns_set_vertical_scroll_bar (struct window *window,
4040 int portion, int whole, int position)
4041 /* --------------------------------------------------------------------------
4042 External (hook): Update or add scrollbar
4043 -------------------------------------------------------------------------- */
4047 struct frame *f = XFRAME (WINDOW_FRAME (window));
4048 EmacsView *view = FRAME_NS_VIEW (f);
4050 int window_y, window_height;
4051 int top, left, height, width;
4052 BOOL update_p = YES;
4054 /* optimization; display engine sends WAY too many of these.. */
4055 if (!NILP (window->vertical_scroll_bar))
4057 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4058 if ([bar checkSamePosition: position portion: portion whole: whole])
4060 if (view->scrollbarsNeedingUpdate == 0)
4062 if (!windows_or_buffers_changed)
4066 view->scrollbarsNeedingUpdate--;
4071 NSTRACE ("ns_set_vertical_scroll_bar");
4073 /* Get dimensions. */
4074 window_box (window, ANY_AREA, 0, &window_y, 0, &window_height);
4076 height = window_height;
4077 width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
4078 left = WINDOW_SCROLL_BAR_AREA_X (window);
4080 r = NSMakeRect (left, top, width, height);
4081 /* the parent view is flipped, so we need to flip y value */
4083 r.origin.y = (v.size.height - r.size.height - r.origin.y);
4085 XSETWINDOW (win, window);
4088 /* we want at least 5 lines to display a scrollbar */
4089 if (WINDOW_TOTAL_LINES (window) < 5)
4091 if (!NILP (window->vertical_scroll_bar))
4093 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4094 [bar removeFromSuperview];
4095 wset_vertical_scroll_bar (window, Qnil);
4098 ns_clear_frame_area (f, left, top, width, height);
4103 if (NILP (window->vertical_scroll_bar))
4105 if (width > 0 && height > 0)
4106 ns_clear_frame_area (f, left, top, width, height);
4108 bar = [[EmacsScroller alloc] initFrame: r window: win];
4109 wset_vertical_scroll_bar (window, make_save_ptr (bar));
4115 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4116 oldRect = [bar frame];
4117 r.size.width = oldRect.size.width;
4118 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4120 if (oldRect.origin.x != r.origin.x)
4121 ns_clear_frame_area (f, left, top, width, height);
4127 [bar setPosition: position portion: portion whole: whole];
4133 ns_set_horizontal_scroll_bar (struct window *window,
4134 int portion, int whole, int position)
4135 /* --------------------------------------------------------------------------
4136 External (hook): Update or add scrollbar
4137 -------------------------------------------------------------------------- */
4141 struct frame *f = XFRAME (WINDOW_FRAME (window));
4142 EmacsView *view = FRAME_NS_VIEW (f);
4144 int top, height, left, width;
4145 int window_x, window_width;
4146 BOOL update_p = YES;
4148 /* optimization; display engine sends WAY too many of these.. */
4149 if (!NILP (window->horizontal_scroll_bar))
4151 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4152 if ([bar checkSamePosition: position portion: portion whole: whole])
4154 if (view->scrollbarsNeedingUpdate == 0)
4156 if (!windows_or_buffers_changed)
4160 view->scrollbarsNeedingUpdate--;
4165 NSTRACE ("ns_set_horizontal_scroll_bar");
4167 /* Get dimensions. */
4168 window_box (window, ANY_AREA, 0, &window_x, &window_width, 0);
4170 width = window_width;
4171 height = WINDOW_CONFIG_SCROLL_BAR_LINES (window) * FRAME_LINE_HEIGHT (f);
4172 top = WINDOW_SCROLL_BAR_AREA_Y (window);
4174 r = NSMakeRect (left, top, width, height);
4175 /* the parent view is flipped, so we need to flip y value */
4177 /* ??????? PXW/scrollbars !!!!!!!!!!!!!!!!!!!! */
4178 r.origin.y = (v.size.height - r.size.height - r.origin.y);
4180 XSETWINDOW (win, window);
4183 if (WINDOW_TOTAL_COLS (window) < 5)
4185 if (!NILP (window->horizontal_scroll_bar))
4187 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4188 [bar removeFromSuperview];
4189 wset_horizontal_scroll_bar (window, Qnil);
4191 ns_clear_frame_area (f, left, top, width, height);
4196 if (NILP (window->horizontal_scroll_bar))
4198 if (width > 0 && height > 0)
4199 ns_clear_frame_area (f, left, top, width, height);
4201 bar = [[EmacsScroller alloc] initFrame: r window: win];
4202 wset_horizontal_scroll_bar (window, make_save_ptr (bar));
4208 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4209 oldRect = [bar frame];
4210 r.size.width = oldRect.size.width;
4211 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4213 if (oldRect.origin.x != r.origin.x)
4214 ns_clear_frame_area (f, left, top, width, height);
4221 [bar setPosition: position portion: portion whole: whole];
4227 ns_condemn_scroll_bars (struct frame *f)
4228 /* --------------------------------------------------------------------------
4229 External (hook): arrange for all frame's scrollbars to be removed
4230 at next call to judge_scroll_bars, except for those redeemed.
4231 -------------------------------------------------------------------------- */
4235 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
4237 NSTRACE ("ns_condemn_scroll_bars");
4239 for (i =[subviews count]-1; i >= 0; i--)
4241 view = [subviews objectAtIndex: i];
4242 if ([view isKindOfClass: [EmacsScroller class]])
4249 ns_redeem_scroll_bar (struct window *window)
4250 /* --------------------------------------------------------------------------
4251 External (hook): arrange to spare this window's scrollbar
4252 at next call to judge_scroll_bars.
4253 -------------------------------------------------------------------------- */
4256 NSTRACE ("ns_redeem_scroll_bar");
4257 if (!NILP (window->vertical_scroll_bar))
4259 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4263 if (!NILP (window->horizontal_scroll_bar))
4265 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4272 ns_judge_scroll_bars (struct frame *f)
4273 /* --------------------------------------------------------------------------
4274 External (hook): destroy all scrollbars on frame that weren't
4275 redeemed after call to condemn_scroll_bars.
4276 -------------------------------------------------------------------------- */
4280 EmacsView *eview = FRAME_NS_VIEW (f);
4281 NSArray *subviews = [[eview superview] subviews];
4284 NSTRACE ("ns_judge_scroll_bars");
4285 for (i = [subviews count]-1; i >= 0; --i)
4287 view = [subviews objectAtIndex: i];
4288 if (![view isKindOfClass: [EmacsScroller class]]) continue;
4294 [eview updateFrameSize: NO];
4297 /* ==========================================================================
4301 ========================================================================== */
4304 x_display_pixel_height (struct ns_display_info *dpyinfo)
4306 NSArray *screens = [NSScreen screens];
4307 NSEnumerator *enumerator = [screens objectEnumerator];
4312 while ((screen = [enumerator nextObject]) != nil)
4313 frame = NSUnionRect (frame, [screen frame]);
4315 return NSHeight (frame);
4319 x_display_pixel_width (struct ns_display_info *dpyinfo)
4321 NSArray *screens = [NSScreen screens];
4322 NSEnumerator *enumerator = [screens objectEnumerator];
4327 while ((screen = [enumerator nextObject]) != nil)
4328 frame = NSUnionRect (frame, [screen frame]);
4330 return NSWidth (frame);
4334 static Lisp_Object ns_string_to_lispmod (const char *s)
4335 /* --------------------------------------------------------------------------
4336 Convert modifier name to lisp symbol
4337 -------------------------------------------------------------------------- */
4339 if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
4341 else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
4343 else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
4345 else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
4347 else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
4349 else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
4357 ns_default (const char *parameter, Lisp_Object *result,
4358 Lisp_Object yesval, Lisp_Object noval,
4359 BOOL is_float, BOOL is_modstring)
4360 /* --------------------------------------------------------------------------
4361 Check a parameter value in user's preferences
4362 -------------------------------------------------------------------------- */
4364 const char *value = ns_get_defaults_value (parameter);
4370 if (c_strcasecmp (value, "YES") == 0)
4372 else if (c_strcasecmp (value, "NO") == 0)
4374 else if (is_float && (f = strtod (value, &pos), pos != value))
4375 *result = make_float (f);
4376 else if (is_modstring && value)
4377 *result = ns_string_to_lispmod (value);
4378 else fprintf (stderr,
4379 "Bad value for default \"%s\": \"%s\"\n", parameter, value);
4385 ns_initialize_display_info (struct ns_display_info *dpyinfo)
4386 /* --------------------------------------------------------------------------
4387 Initialize global info and storage for display.
4388 -------------------------------------------------------------------------- */
4390 NSScreen *screen = [NSScreen mainScreen];
4391 NSWindowDepth depth = [screen depth];
4393 dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
4394 dpyinfo->resy = 72.27;
4395 dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
4396 NSColorSpaceFromDepth (depth)]
4397 && ![NSCalibratedWhiteColorSpace isEqualToString:
4398 NSColorSpaceFromDepth (depth)];
4399 dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
4400 dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
4401 dpyinfo->color_table->colors = NULL;
4402 dpyinfo->root_window = 42; /* a placeholder.. */
4403 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
4404 dpyinfo->n_fonts = 0;
4405 dpyinfo->smallest_font_height = 1;
4406 dpyinfo->smallest_char_width = 1;
4408 reset_mouse_highlight (&dpyinfo->mouse_highlight);
4412 /* This and next define (many of the) public functions in this file. */
4413 /* x_... are generic versions in xdisp.c that we, and other terms, get away
4414 with using despite presence in the "system dependent" redisplay
4415 interface. In addition, many of the ns_ methods have code that is
4416 shared with all terms, indicating need for further refactoring. */
4417 extern frame_parm_handler ns_frame_parm_handlers[];
4418 static struct redisplay_interface ns_redisplay_interface =
4420 ns_frame_parm_handlers,
4424 x_clear_end_of_line,
4426 ns_after_update_window_line,
4427 ns_update_window_begin,
4428 ns_update_window_end,
4429 0, /* flush_display */
4430 x_clear_window_mouse_face,
4431 x_get_glyph_overhangs,
4432 x_fix_overlapping_area,
4433 ns_draw_fringe_bitmap,
4434 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
4435 0, /* destroy_fringe_bitmap */
4436 ns_compute_glyph_string_overhangs,
4437 ns_draw_glyph_string,
4438 ns_define_frame_cursor,
4439 ns_clear_frame_area,
4440 ns_draw_window_cursor,
4441 ns_draw_vertical_window_border,
4442 ns_draw_window_divider,
4443 ns_shift_glyphs_for_insert,
4450 ns_delete_display (struct ns_display_info *dpyinfo)
4456 /* This function is called when the last frame on a display is deleted. */
4458 ns_delete_terminal (struct terminal *terminal)
4460 struct ns_display_info *dpyinfo = terminal->display_info.ns;
4462 NSTRACE ("ns_delete_terminal");
4464 /* Protect against recursive calls. delete_frame in
4465 delete_terminal calls us back when it deletes our last frame. */
4466 if (!terminal->name)
4471 x_destroy_all_bitmaps (dpyinfo);
4472 ns_delete_display (dpyinfo);
4477 static struct terminal *
4478 ns_create_terminal (struct ns_display_info *dpyinfo)
4479 /* --------------------------------------------------------------------------
4480 Set up use of NS before we make the first connection.
4481 -------------------------------------------------------------------------- */
4483 struct terminal *terminal;
4485 NSTRACE ("ns_create_terminal");
4487 terminal = create_terminal (output_ns, &ns_redisplay_interface);
4489 terminal->display_info.ns = dpyinfo;
4490 dpyinfo->terminal = terminal;
4492 terminal->clear_frame_hook = ns_clear_frame;
4493 terminal->ring_bell_hook = ns_ring_bell;
4494 terminal->update_begin_hook = ns_update_begin;
4495 terminal->update_end_hook = ns_update_end;
4496 terminal->read_socket_hook = ns_read_socket;
4497 terminal->frame_up_to_date_hook = ns_frame_up_to_date;
4498 terminal->mouse_position_hook = ns_mouse_position;
4499 terminal->frame_rehighlight_hook = ns_frame_rehighlight;
4500 terminal->frame_raise_lower_hook = ns_frame_raise_lower;
4501 terminal->fullscreen_hook = ns_fullscreen_hook;
4502 terminal->menu_show_hook = ns_menu_show;
4503 terminal->popup_dialog_hook = ns_popup_dialog;
4504 terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
4505 terminal->set_horizontal_scroll_bar_hook = ns_set_horizontal_scroll_bar;
4506 terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
4507 terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
4508 terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
4509 terminal->delete_frame_hook = x_destroy_window;
4510 terminal->delete_terminal_hook = ns_delete_terminal;
4511 /* Other hooks are NULL by default. */
4517 struct ns_display_info *
4518 ns_term_init (Lisp_Object display_name)
4519 /* --------------------------------------------------------------------------
4520 Start the Application and get things rolling.
4521 -------------------------------------------------------------------------- */
4523 struct terminal *terminal;
4524 struct ns_display_info *dpyinfo;
4525 static int ns_initialized = 0;
4528 if (ns_initialized) return x_display_list;
4531 NSTRACE ("ns_term_init");
4533 [outerpool release];
4534 outerpool = [[NSAutoreleasePool alloc] init];
4536 /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4537 /*GSDebugAllocationActive (YES); */
4541 Fset_input_interrupt_mode (Qnil);
4543 if (selfds[0] == -1)
4545 if (emacs_pipe (selfds) != 0)
4547 fprintf (stderr, "Failed to create pipe: %s\n",
4548 emacs_strerror (errno));
4552 fcntl (selfds[0], F_SETFL, O_NONBLOCK|fcntl (selfds[0], F_GETFL));
4553 FD_ZERO (&select_readfds);
4554 FD_ZERO (&select_writefds);
4555 pthread_mutex_init (&select_mutex, NULL);
4558 ns_pending_files = [[NSMutableArray alloc] init];
4559 ns_pending_service_names = [[NSMutableArray alloc] init];
4560 ns_pending_service_args = [[NSMutableArray alloc] init];
4562 /* Start app and create the main menu, window, view.
4563 Needs to be here because ns_initialize_display_info () uses AppKit classes.
4564 The view will then ask the NSApp to stop and return to Emacs. */
4565 [EmacsApp sharedApplication];
4568 [NSApp setDelegate: NSApp];
4570 /* Start the select thread. */
4571 [NSThread detachNewThreadSelector:@selector (fd_handler:)
4575 /* debugging: log all notifications */
4576 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
4577 selector: @selector (logNotification:)
4578 name: nil object: nil]; */
4580 dpyinfo = xzalloc (sizeof *dpyinfo);
4582 ns_initialize_display_info (dpyinfo);
4583 terminal = ns_create_terminal (dpyinfo);
4585 terminal->kboard = allocate_kboard (Qns);
4586 /* Don't let the initial kboard remain current longer than necessary.
4587 That would cause problems if a file loaded on startup tries to
4588 prompt in the mini-buffer. */
4589 if (current_kboard == initial_kboard)
4590 current_kboard = terminal->kboard;
4591 terminal->kboard->reference_count++;
4593 dpyinfo->next = x_display_list;
4594 x_display_list = dpyinfo;
4596 dpyinfo->name_list_element = Fcons (display_name, Qnil);
4598 terminal->name = xlispstrdup (display_name);
4602 if (!inhibit_x_resources)
4604 ns_default ("GSFontAntiAlias", &ns_antialias_text,
4607 /* this is a standard variable */
4608 ns_default ("AppleAntiAliasingThreshold", &tmp,
4609 make_float (10.0), make_float (6.0), YES, NO);
4610 ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4613 NSTRACE_MSG ("Colors");
4616 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4620 Lisp_Object color_file, color_map, color;
4624 color_file = Fexpand_file_name (build_string ("rgb.txt"),
4625 Fsymbol_value (intern ("data-directory")));
4627 color_map = Fx_load_color_file (color_file);
4628 if (NILP (color_map))
4629 fatal ("Could not read %s.\n", SDATA (color_file));
4631 cl = [[NSColorList alloc] initWithName: @"Emacs"];
4632 for ( ; CONSP (color_map); color_map = XCDR (color_map))
4634 color = XCAR (color_map);
4635 name = SSDATA (XCAR (color));
4636 c = XINT (XCDR (color));
4638 [NSColor colorForEmacsRed: RED_FROM_ULONG (c) / 255.0
4639 green: GREEN_FROM_ULONG (c) / 255.0
4640 blue: BLUE_FROM_ULONG (c) / 255.0
4642 forKey: [NSString stringWithUTF8String: name]];
4644 [cl writeToFile: nil];
4648 NSTRACE_MSG ("Versions");
4651 #ifdef NS_IMPL_GNUSTEP
4652 Vwindow_system_version = build_string (gnustep_base_version);
4654 /*PSnextrelease (128, c); */
4655 char c[DBL_BUFSIZE_BOUND];
4656 int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4657 Vwindow_system_version = make_unibyte_string (c, len);
4661 delete_keyboard_wait_descriptor (0);
4663 ns_app_name = [[NSProcessInfo processInfo] processName];
4665 /* Set up OS X app menu */
4667 NSTRACE_MSG ("Menu init");
4669 #ifdef NS_IMPL_COCOA
4673 /* set up the application menu */
4674 svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4675 [svcsMenu setAutoenablesItems: NO];
4676 appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4677 [appMenu setAutoenablesItems: NO];
4678 mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4679 dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4681 [appMenu insertItemWithTitle: @"About Emacs"
4682 action: @selector (orderFrontStandardAboutPanel:)
4685 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4686 [appMenu insertItemWithTitle: @"Preferences..."
4687 action: @selector (showPreferencesWindow:)
4690 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4691 item = [appMenu insertItemWithTitle: @"Services"
4692 action: @selector (menuDown:)
4695 [appMenu setSubmenu: svcsMenu forItem: item];
4696 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4697 [appMenu insertItemWithTitle: @"Hide Emacs"
4698 action: @selector (hide:)
4701 item = [appMenu insertItemWithTitle: @"Hide Others"
4702 action: @selector (hideOtherApplications:)
4705 [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4706 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4707 [appMenu insertItemWithTitle: @"Quit Emacs"
4708 action: @selector (terminate:)
4712 item = [mainMenu insertItemWithTitle: ns_app_name
4713 action: @selector (menuDown:)
4716 [mainMenu setSubmenu: appMenu forItem: item];
4717 [dockMenu insertItemWithTitle: @"New Frame"
4718 action: @selector (newFrame:)
4722 [NSApp setMainMenu: mainMenu];
4723 [NSApp setAppleMenu: appMenu];
4724 [NSApp setServicesMenu: svcsMenu];
4725 /* Needed at least on Cocoa, to get dock menu to show windows */
4726 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4728 [[NSNotificationCenter defaultCenter]
4729 addObserver: mainMenu
4730 selector: @selector (trackingNotification:)
4731 name: NSMenuDidBeginTrackingNotification object: mainMenu];
4732 [[NSNotificationCenter defaultCenter]
4733 addObserver: mainMenu
4734 selector: @selector (trackingNotification:)
4735 name: NSMenuDidEndTrackingNotification object: mainMenu];
4737 #endif /* MAC OS X menu setup */
4739 /* Register our external input/output types, used for determining
4740 applicable services and also drag/drop eligibility. */
4742 NSTRACE_MSG ("Input/output types");
4744 ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
4745 ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
4747 ns_drag_types = [[NSArray arrayWithObjects:
4749 NSTabularTextPboardType,
4750 NSFilenamesPboardType,
4751 NSURLPboardType, nil] retain];
4753 /* If fullscreen is in init/default-frame-alist, focus isn't set
4754 right for fullscreen windows, so set this. */
4755 [NSApp activateIgnoringOtherApps:YES];
4757 NSTRACE_MSG ("Call NSApp run");
4760 ns_do_open_file = YES;
4762 #ifdef NS_IMPL_GNUSTEP
4763 /* GNUstep steals SIGCHLD for use in NSTask, but we don't use NSTask.
4764 We must re-catch it so subprocess works. */
4765 catch_child_signal ();
4768 NSTRACE_MSG ("ns_term_init done");
4775 ns_term_shutdown (int sig)
4777 [[NSUserDefaults standardUserDefaults] synchronize];
4779 /* code not reached in emacs.c after this is called by shut_down_emacs: */
4780 if (STRINGP (Vauto_save_list_file_name))
4781 unlink (SSDATA (Vauto_save_list_file_name));
4783 if (sig == 0 || sig == SIGTERM)
4785 [NSApp terminate: NSApp];
4787 else // force a stack trace to happen
4794 /* ==========================================================================
4796 EmacsApp implementation
4798 ========================================================================== */
4801 @implementation EmacsApp
4805 if ((self = [super init]))
4807 #ifdef NS_IMPL_COCOA
4808 self->isFirst = YES;
4810 #ifdef NS_IMPL_GNUSTEP
4811 self->applicationDidFinishLaunchingCalled = NO;
4818 #ifdef NS_IMPL_COCOA
4821 #ifndef NSAppKitVersionNumber10_9
4822 #define NSAppKitVersionNumber10_9 1265
4825 if ((int)NSAppKitVersionNumber != NSAppKitVersionNumber10_9)
4831 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
4833 if (isFirst) [self finishLaunching];
4836 shouldKeepRunning = YES;
4840 pool = [[NSAutoreleasePool alloc] init];
4843 [self nextEventMatchingMask:NSAnyEventMask
4844 untilDate:[NSDate distantFuture]
4845 inMode:NSDefaultRunLoopMode
4848 [self sendEvent:event];
4849 [self updateWindows];
4850 } while (shouldKeepRunning);
4855 - (void)stop: (id)sender
4857 shouldKeepRunning = NO;
4858 // Stop possible dialog also. Noop if no dialog present.
4859 // The file dialog still leaks 7k - 10k on 10.9 though.
4860 [super stop:sender];
4862 #endif /* NS_IMPL_COCOA */
4864 - (void)logNotification: (NSNotification *)notification
4866 const char *name = [[notification name] UTF8String];
4867 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4868 && !strstr (name, "WindowNumber"))
4869 NSLog (@"notification: '%@'", [notification name]);
4873 - (void)sendEvent: (NSEvent *)theEvent
4874 /* --------------------------------------------------------------------------
4875 Called when NSApp is running for each event received. Used to stop
4876 the loop when we choose, since there's no way to just run one iteration.
4877 -------------------------------------------------------------------------- */
4879 int type = [theEvent type];
4880 NSWindow *window = [theEvent window];
4882 /* NSTRACE ("sendEvent"); */
4883 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4885 #ifdef NS_IMPL_GNUSTEP
4886 // Keyboard events aren't propagated to file dialogs for some reason.
4887 if ([NSApp modalWindow] != nil &&
4888 (type == NSKeyDown || type == NSKeyUp || type == NSFlagsChanged))
4890 [[NSApp modalWindow] sendEvent: theEvent];
4895 if (represented_filename != nil && represented_frame)
4897 NSString *fstr = represented_filename;
4898 NSView *view = FRAME_NS_VIEW (represented_frame);
4899 #ifdef NS_IMPL_COCOA
4900 /* work around a bug observed on 10.3 and later where
4901 setTitleWithRepresentedFilename does not clear out previous state
4902 if given filename does not exist */
4903 if (! [[NSFileManager defaultManager] fileExistsAtPath: fstr])
4904 [[view window] setRepresentedFilename: @""];
4906 [[view window] setRepresentedFilename: fstr];
4907 [represented_filename release];
4908 represented_filename = nil;
4909 represented_frame = NULL;
4912 if (type == NSApplicationDefined)
4914 switch ([theEvent data2])
4916 #ifdef NS_IMPL_COCOA
4917 case NSAPP_DATA2_RUNASSCRIPT:
4922 case NSAPP_DATA2_RUNFILEDIALOG:
4923 ns_run_file_dialog ();
4929 if (type == NSCursorUpdate && window == nil)
4931 fprintf (stderr, "Dropping external cursor update event.\n");
4935 if (type == NSApplicationDefined)
4937 /* Events posted by ns_send_appdefined interrupt the run loop here.
4938 But, if a modal window is up, an appdefined can still come through,
4939 (e.g., from a makeKeyWindow event) but stopping self also stops the
4940 modal loop. Just defer it until later. */
4941 if ([NSApp modalWindow] == nil)
4943 last_appdefined_event_data = [theEvent data1];
4948 send_appdefined = YES;
4953 #ifdef NS_IMPL_COCOA
4954 /* If no dialog and none of our frames have focus and it is a move, skip it.
4955 It is a mouse move in an auxiliary menu, i.e. on the top right on OSX,
4956 such as Wifi, sound, date or similar.
4957 This prevents "spooky" highlighting in the frame under the menu. */
4958 if (type == NSMouseMoved && [NSApp modalWindow] == nil)
4960 struct ns_display_info *di;
4961 BOOL has_focus = NO;
4962 for (di = x_display_list; ! has_focus && di; di = di->next)
4963 has_focus = di->x_focus_frame != 0;
4969 [super sendEvent: theEvent];
4973 - (void)showPreferencesWindow: (id)sender
4975 struct frame *emacsframe = SELECTED_FRAME ();
4976 NSEvent *theEvent = [NSApp currentEvent];
4980 emacs_event->kind = NS_NONKEY_EVENT;
4981 emacs_event->code = KEY_NS_SHOW_PREFS;
4982 emacs_event->modifiers = 0;
4983 EV_TRAILER (theEvent);
4987 - (void)newFrame: (id)sender
4989 struct frame *emacsframe = SELECTED_FRAME ();
4990 NSEvent *theEvent = [NSApp currentEvent];
4994 emacs_event->kind = NS_NONKEY_EVENT;
4995 emacs_event->code = KEY_NS_NEW_FRAME;
4996 emacs_event->modifiers = 0;
4997 EV_TRAILER (theEvent);
5001 /* Open a file (used by below, after going into queue read by ns_read_socket) */
5002 - (BOOL) openFile: (NSString *)fileName
5004 struct frame *emacsframe = SELECTED_FRAME ();
5005 NSEvent *theEvent = [NSApp currentEvent];
5010 emacs_event->kind = NS_NONKEY_EVENT;
5011 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
5012 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
5013 ns_input_line = Qnil; /* can be start or cons start,end */
5014 emacs_event->modifiers =0;
5015 EV_TRAILER (theEvent);
5021 /* **************************************************************************
5023 EmacsApp delegate implementation
5025 ************************************************************************** */
5027 - (void)applicationDidFinishLaunching: (NSNotification *)notification
5028 /* --------------------------------------------------------------------------
5029 When application is loaded, terminate event loop in ns_term_init
5030 -------------------------------------------------------------------------- */
5032 NSTRACE ("applicationDidFinishLaunching");
5033 #ifdef NS_IMPL_GNUSTEP
5034 ((EmacsApp *)self)->applicationDidFinishLaunchingCalled = YES;
5036 [NSApp setServicesProvider: NSApp];
5038 [self antialiasThresholdDidChange:nil];
5039 #ifdef NS_IMPL_COCOA
5040 [[NSNotificationCenter defaultCenter]
5042 selector:@selector(antialiasThresholdDidChange:)
5043 name:NSAntialiasThresholdChangedNotification
5047 ns_send_appdefined (-2);
5050 - (void)antialiasThresholdDidChange:(NSNotification *)notification
5052 #ifdef NS_IMPL_COCOA
5053 macfont_update_antialias_threshold ();
5058 /* Termination sequences:
5061 MenuBar | File | Exit:
5062 Select Quit from App menubar:
5064 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5067 Select Quit from Dock menu:
5070 Cancel -> Nothing else
5074 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5079 - (void) terminate: (id)sender
5081 struct frame *emacsframe = SELECTED_FRAME ();
5086 emacs_event->kind = NS_NONKEY_EVENT;
5087 emacs_event->code = KEY_NS_POWER_OFF;
5088 emacs_event->arg = Qt; /* mark as non-key event */
5089 EV_TRAILER ((id)nil);
5093 runAlertPanel(NSString *title,
5094 NSString *msgFormat,
5095 NSString *defaultButton,
5096 NSString *alternateButton)
5098 #if !defined (NS_IMPL_COCOA) || \
5099 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
5100 return NSRunAlertPanel(title, msgFormat, defaultButton, alternateButton, nil)
5101 == NSAlertDefaultReturn;
5103 NSAlert *alert = [[NSAlert alloc] init];
5104 [alert setAlertStyle: NSCriticalAlertStyle];
5105 [alert setMessageText: msgFormat];
5106 [alert addButtonWithTitle: defaultButton];
5107 [alert addButtonWithTitle: alternateButton];
5108 NSInteger ret = [alert runModal];
5110 return ret == NSAlertFirstButtonReturn;
5115 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
5119 if (NILP (ns_confirm_quit)) // || ns_shutdown_properly --> TO DO
5120 return NSTerminateNow;
5122 ret = runAlertPanel(ns_app_name,
5123 @"Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?",
5124 @"Save Buffers and Exit", @"Cancel");
5127 return NSTerminateNow;
5129 return NSTerminateCancel;
5130 return NSTerminateNow; /* just in case */
5134 not_in_argv (NSString *arg)
5137 const char *a = [arg UTF8String];
5138 for (k = 1; k < initial_argc; ++k)
5139 if (strcmp (a, initial_argv[k]) == 0) return 0;
5143 /* Notification from the Workspace to open a file */
5144 - (BOOL)application: sender openFile: (NSString *)file
5146 if (ns_do_open_file || not_in_argv (file))
5147 [ns_pending_files addObject: file];
5152 /* Open a file as a temporary file */
5153 - (BOOL)application: sender openTempFile: (NSString *)file
5155 if (ns_do_open_file || not_in_argv (file))
5156 [ns_pending_files addObject: file];
5161 /* Notification from the Workspace to open a file noninteractively (?) */
5162 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
5164 if (ns_do_open_file || not_in_argv (file))
5165 [ns_pending_files addObject: file];
5169 /* Notification from the Workspace to open multiple files */
5170 - (void)application: sender openFiles: (NSArray *)fileList
5172 NSEnumerator *files = [fileList objectEnumerator];
5174 /* Don't open files from the command line unconditionally,
5175 Cocoa parses the command line wrong, --option value tries to open value
5176 if --option is the last option. */
5177 while ((file = [files nextObject]) != nil)
5178 if (ns_do_open_file || not_in_argv (file))
5179 [ns_pending_files addObject: file];
5181 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
5186 /* Handle dock menu requests. */
5187 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
5193 /* TODO: these may help w/IO switching btwn terminal and NSApp */
5194 - (void)applicationWillBecomeActive: (NSNotification *)notification
5196 //ns_app_active=YES;
5198 - (void)applicationDidBecomeActive: (NSNotification *)notification
5200 NSTRACE ("applicationDidBecomeActive");
5202 #ifdef NS_IMPL_GNUSTEP
5203 if (! applicationDidFinishLaunchingCalled)
5204 [self applicationDidFinishLaunching:notification];
5206 //ns_app_active=YES;
5208 ns_update_auto_hide_menu_bar ();
5209 // No constraining takes place when the application is not active.
5210 ns_constrain_all_frames ();
5212 - (void)applicationDidResignActive: (NSNotification *)notification
5215 ns_send_appdefined (-1);
5220 /* ==========================================================================
5222 EmacsApp aux handlers for managing event loop
5224 ========================================================================== */
5227 - (void)timeout_handler: (NSTimer *)timedEntry
5228 /* --------------------------------------------------------------------------
5229 The timeout specified to ns_select has passed.
5230 -------------------------------------------------------------------------- */
5232 /*NSTRACE ("timeout_handler"); */
5233 ns_send_appdefined (-2);
5236 #ifdef NS_IMPL_GNUSTEP
5237 - (void)sendFromMainThread:(id)unused
5239 ns_send_appdefined (nextappdefined);
5243 - (void)fd_handler:(id)unused
5244 /* --------------------------------------------------------------------------
5245 Check data waiting on file descriptors and terminate if so
5246 -------------------------------------------------------------------------- */
5249 int waiting = 1, nfds;
5252 fd_set readfds, writefds, *wfds;
5253 struct timespec timeout, *tmo;
5254 NSAutoreleasePool *pool = nil;
5256 /* NSTRACE ("fd_handler"); */
5261 pool = [[NSAutoreleasePool alloc] init];
5267 FD_SET (selfds[0], &fds);
5268 result = select (selfds[0]+1, &fds, NULL, NULL, NULL);
5269 if (result > 0 && read (selfds[0], &c, 1) == 1 && c == 'g')
5274 pthread_mutex_lock (&select_mutex);
5277 if (select_valid & SELECT_HAVE_READ)
5278 readfds = select_readfds;
5282 if (select_valid & SELECT_HAVE_WRITE)
5284 writefds = select_writefds;
5289 if (select_valid & SELECT_HAVE_TMO)
5291 timeout = select_timeout;
5297 pthread_mutex_unlock (&select_mutex);
5299 FD_SET (selfds[0], &readfds);
5300 if (selfds[0] >= nfds) nfds = selfds[0]+1;
5302 result = pselect (nfds, &readfds, wfds, NULL, tmo, NULL);
5305 ns_send_appdefined (-2);
5306 else if (result > 0)
5308 if (FD_ISSET (selfds[0], &readfds))
5310 if (read (selfds[0], &c, 1) == 1 && c == 's')
5315 pthread_mutex_lock (&select_mutex);
5316 if (select_valid & SELECT_HAVE_READ)
5317 select_readfds = readfds;
5318 if (select_valid & SELECT_HAVE_WRITE)
5319 select_writefds = writefds;
5320 if (select_valid & SELECT_HAVE_TMO)
5321 select_timeout = timeout;
5322 pthread_mutex_unlock (&select_mutex);
5324 ns_send_appdefined (result);
5334 /* ==========================================================================
5338 ========================================================================== */
5340 /* called from system: queue for next pass through event loop */
5341 - (void)requestService: (NSPasteboard *)pboard
5342 userData: (NSString *)userData
5343 error: (NSString **)error
5345 [ns_pending_service_names addObject: userData];
5346 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
5347 SSDATA (ns_string_from_pasteboard (pboard))]];
5351 /* called from ns_read_socket to clear queue */
5352 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
5354 struct frame *emacsframe = SELECTED_FRAME ();
5355 NSEvent *theEvent = [NSApp currentEvent];
5360 emacs_event->kind = NS_NONKEY_EVENT;
5361 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
5362 ns_input_spi_name = build_string ([name UTF8String]);
5363 ns_input_spi_arg = build_string ([arg UTF8String]);
5364 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5365 EV_TRAILER (theEvent);
5375 /* ==========================================================================
5377 EmacsView implementation
5379 ========================================================================== */
5382 @implementation EmacsView
5384 /* needed to inform when window closed from LISP */
5385 - (void) setWindowClosing: (BOOL)closing
5387 windowClosing = closing;
5393 NSTRACE ("EmacsView_dealloc");
5395 if (fs_state == FULLSCREEN_BOTH)
5396 [nonfs_window release];
5401 /* called on font panel selection */
5402 - (void)changeFont: (id)sender
5404 NSEvent *e = [[self window] currentEvent];
5405 struct face *face = FRAME_DEFAULT_FACE (emacsframe);
5406 struct font *font = face->font;
5411 NSTRACE ("changeFont");
5416 #ifdef NS_IMPL_GNUSTEP
5417 nsfont = ((struct nsfont_info *)font)->nsfont;
5419 #ifdef NS_IMPL_COCOA
5420 nsfont = (NSFont *) macfont_get_nsctfont (font);
5423 if ((newFont = [sender convertFont: nsfont]))
5425 SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
5427 emacs_event->kind = NS_NONKEY_EVENT;
5428 emacs_event->modifiers = 0;
5429 emacs_event->code = KEY_NS_CHANGE_FONT;
5431 size = [newFont pointSize];
5432 ns_input_fontsize = make_number (lrint (size));
5433 ns_input_font = build_string ([[newFont familyName] UTF8String]);
5439 - (BOOL)acceptsFirstResponder
5441 NSTRACE ("acceptsFirstResponder");
5446 - (void)resetCursorRects
5448 NSRect visible = [self visibleRect];
5449 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
5450 NSTRACE ("resetCursorRects");
5452 if (currentCursor == nil)
5453 currentCursor = [NSCursor arrowCursor];
5455 if (!NSIsEmptyRect (visible))
5456 [self addCursorRect: visible cursor: currentCursor];
5457 [currentCursor setOnMouseEntered: YES];
5462 /*****************************************************************************/
5463 /* Keyboard handling. */
5466 - (void)keyDown: (NSEvent *)theEvent
5468 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5470 unsigned fnKeysym = 0;
5471 static NSMutableArray *nsEvArray;
5473 unsigned int flags = [theEvent modifierFlags];
5475 NSTRACE ("keyDown");
5477 /* Rhapsody and OS X give up and down events for the arrow keys */
5478 if (ns_fake_keydown == YES)
5479 ns_fake_keydown = NO;
5480 else if ([theEvent type] != NSKeyDown)
5486 if (![[self window] isKeyWindow]
5487 && [[theEvent window] isKindOfClass: [EmacsWindow class]]
5488 /* we must avoid an infinite loop here. */
5489 && (EmacsView *)[[theEvent window] delegate] != self)
5491 /* XXX: There is an occasional condition in which, when Emacs display
5492 updates a different frame from the current one, and temporarily
5493 selects it, then processes some interrupt-driven input
5494 (dispnew.c:3878), OS will send the event to the correct NSWindow, but
5495 for some reason that window has its first responder set to the NSView
5496 most recently updated (I guess), which is not the correct one. */
5497 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
5501 if (nsEvArray == nil)
5502 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
5504 [NSCursor setHiddenUntilMouseMoves: YES];
5506 if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
5508 clear_mouse_face (hlinfo);
5509 hlinfo->mouse_face_hidden = 1;
5512 if (!processingCompose)
5514 /* When using screen sharing, no left or right information is sent,
5515 so use Left key in those cases. */
5516 int is_left_key, is_right_key;
5518 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
5519 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
5521 /* (Carbon way: [theEvent keyCode]) */
5523 /* is it a "function key"? */
5524 /* Note: Sometimes a plain key will have the NSNumericPadKeyMask
5525 flag set (this is probably a bug in the OS).
5527 if (code < 0x00ff && (flags&NSNumericPadKeyMask))
5529 fnKeysym = ns_convert_key ([theEvent keyCode] | NSNumericPadKeyMask);
5533 fnKeysym = ns_convert_key (code);
5538 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
5539 because Emacs treats Delete and KP-Delete same (in simple.el). */
5540 if ((fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
5541 #ifdef NS_IMPL_GNUSTEP
5542 /* GNUstep uses incompatible keycodes, even for those that are
5543 supposed to be hardware independent. Just check for delete.
5544 Keypad delete does not have keysym 0xFFFF.
5545 See http://savannah.gnu.org/bugs/?25395
5547 || (fnKeysym == 0xFFFF && code == 127)
5550 code = 0xFF08; /* backspace */
5555 /* are there modifiers? */
5556 emacs_event->modifiers = 0;
5558 if (flags & NSHelpKeyMask)
5559 emacs_event->modifiers |= hyper_modifier;
5561 if (flags & NSShiftKeyMask)
5562 emacs_event->modifiers |= shift_modifier;
5564 is_right_key = (flags & NSRightCommandKeyMask) == NSRightCommandKeyMask;
5565 is_left_key = (flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask
5566 || (! is_right_key && (flags & NSCommandKeyMask) == NSCommandKeyMask);
5569 emacs_event->modifiers |= parse_solitary_modifier
5570 (EQ (ns_right_command_modifier, Qleft)
5571 ? ns_command_modifier
5572 : ns_right_command_modifier);
5576 emacs_event->modifiers |= parse_solitary_modifier
5577 (ns_command_modifier);
5579 /* if super (default), take input manager's word so things like
5580 dvorak / qwerty layout work */
5581 if (EQ (ns_command_modifier, Qsuper)
5583 && [[theEvent characters] length] != 0)
5585 /* XXX: the code we get will be unshifted, so if we have
5586 a shift modifier, must convert ourselves */
5587 if (!(flags & NSShiftKeyMask))
5588 code = [[theEvent characters] characterAtIndex: 0];
5590 /* this is ugly and also requires linking w/Carbon framework
5591 (for LMGetKbdType) so for now leave this rare (?) case
5592 undealt with.. in future look into CGEvent methods */
5595 long smv = GetScriptManagerVariable (smKeyScript);
5596 Handle uchrHandle = GetResource
5597 ('uchr', GetScriptVariable (smv, smScriptKeys));
5599 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
5600 [[theEvent characters] characterAtIndex: 0],
5601 kUCKeyActionDisplay,
5602 (flags & ~NSCommandKeyMask) >> 8,
5603 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
5604 &dummy, 1, &dummy, &code);
5611 is_right_key = (flags & NSRightControlKeyMask) == NSRightControlKeyMask;
5612 is_left_key = (flags & NSLeftControlKeyMask) == NSLeftControlKeyMask
5613 || (! is_right_key && (flags & NSControlKeyMask) == NSControlKeyMask);
5616 emacs_event->modifiers |= parse_solitary_modifier
5617 (EQ (ns_right_control_modifier, Qleft)
5618 ? ns_control_modifier
5619 : ns_right_control_modifier);
5622 emacs_event->modifiers |= parse_solitary_modifier
5623 (ns_control_modifier);
5625 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
5626 emacs_event->modifiers |=
5627 parse_solitary_modifier (ns_function_modifier);
5629 left_is_none = NILP (ns_alternate_modifier)
5630 || EQ (ns_alternate_modifier, Qnone);
5632 is_right_key = (flags & NSRightAlternateKeyMask)
5633 == NSRightAlternateKeyMask;
5634 is_left_key = (flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask
5636 && (flags & NSAlternateKeyMask) == NSAlternateKeyMask);
5640 if ((NILP (ns_right_alternate_modifier)
5641 || EQ (ns_right_alternate_modifier, Qnone)
5642 || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
5644 { /* accept pre-interp alt comb */
5645 if ([[theEvent characters] length] > 0)
5646 code = [[theEvent characters] characterAtIndex: 0];
5647 /*HACK: clear lone shift modifier to stop next if from firing */
5648 if (emacs_event->modifiers == shift_modifier)
5649 emacs_event->modifiers = 0;
5652 emacs_event->modifiers |= parse_solitary_modifier
5653 (EQ (ns_right_alternate_modifier, Qleft)
5654 ? ns_alternate_modifier
5655 : ns_right_alternate_modifier);
5658 if (is_left_key) /* default = meta */
5660 if (left_is_none && !fnKeysym)
5661 { /* accept pre-interp alt comb */
5662 if ([[theEvent characters] length] > 0)
5663 code = [[theEvent characters] characterAtIndex: 0];
5664 /*HACK: clear lone shift modifier to stop next if from firing */
5665 if (emacs_event->modifiers == shift_modifier)
5666 emacs_event->modifiers = 0;
5669 emacs_event->modifiers |=
5670 parse_solitary_modifier (ns_alternate_modifier);
5674 fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
5675 code, fnKeysym, flags, emacs_event->modifiers);
5677 /* if it was a function key or had modifiers, pass it directly to emacs */
5678 if (fnKeysym || (emacs_event->modifiers
5679 && (emacs_event->modifiers != shift_modifier)
5680 && [[theEvent charactersIgnoringModifiers] length] > 0))
5681 /*[[theEvent characters] length] */
5683 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5685 code |= (1<<28)|(3<<16);
5686 else if (code == 0x7f)
5687 code |= (1<<28)|(3<<16);
5689 emacs_event->kind = code > 0xFF
5690 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5692 emacs_event->code = code;
5693 EV_TRAILER (theEvent);
5694 processingCompose = NO;
5700 if (NS_KEYLOG && !processingCompose)
5701 fprintf (stderr, "keyDown: Begin compose sequence.\n");
5703 processingCompose = YES;
5704 [nsEvArray addObject: theEvent];
5705 [self interpretKeyEvents: nsEvArray];
5706 [nsEvArray removeObject: theEvent];
5710 #ifdef NS_IMPL_COCOA
5711 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
5712 decided not to send key-down for.
5713 See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
5714 This only applies on Tiger and earlier.
5715 If it matches one of these, send it on to keyDown. */
5716 -(void)keyUp: (NSEvent *)theEvent
5718 int flags = [theEvent modifierFlags];
5719 int code = [theEvent keyCode];
5720 if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
5721 code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
5724 fprintf (stderr, "keyUp: passed test");
5725 ns_fake_keydown = YES;
5726 [self keyDown: theEvent];
5732 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
5735 /* <NSTextInput>: called when done composing;
5736 NOTE: also called when we delete over working text, followed immed.
5737 by doCommandBySelector: deleteBackward: */
5738 - (void)insertText: (id)aString
5741 int len = [(NSString *)aString length];
5745 NSLog (@"insertText '%@'\tlen = %d", aString, len);
5746 processingCompose = NO;
5751 /* first, clear any working text */
5752 if (workingText != nil)
5753 [self deleteWorkingText];
5755 /* now insert the string as keystrokes */
5756 for (i =0; i<len; i++)
5758 code = [aString characterAtIndex: i];
5759 /* TODO: still need this? */
5761 code = '~'; /* 0x7E */
5762 if (code != 32) /* Space */
5763 emacs_event->modifiers = 0;
5765 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5766 emacs_event->code = code;
5767 EV_TRAILER ((id)nil);
5772 /* <NSTextInput>: inserts display of composing characters */
5773 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
5775 NSString *str = [aString respondsToSelector: @selector (string)] ?
5776 [aString string] : aString;
5778 NSLog (@"setMarkedText '%@' len =%lu range %lu from %lu",
5779 str, (unsigned long)[str length],
5780 (unsigned long)selRange.length,
5781 (unsigned long)selRange.location);
5783 if (workingText != nil)
5784 [self deleteWorkingText];
5785 if ([str length] == 0)
5791 processingCompose = YES;
5792 workingText = [str copy];
5793 ns_working_text = build_string ([workingText UTF8String]);
5795 emacs_event->kind = NS_TEXT_EVENT;
5796 emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
5797 EV_TRAILER ((id)nil);
5801 /* delete display of composing characters [not in <NSTextInput>] */
5802 - (void)deleteWorkingText
5804 if (workingText == nil)
5807 NSLog(@"deleteWorkingText len =%lu\n", (unsigned long)[workingText length]);
5808 [workingText release];
5810 processingCompose = NO;
5815 emacs_event->kind = NS_TEXT_EVENT;
5816 emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
5817 EV_TRAILER ((id)nil);
5821 - (BOOL)hasMarkedText
5823 return workingText != nil;
5827 - (NSRange)markedRange
5829 NSRange rng = workingText != nil
5830 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
5832 NSLog (@"markedRange request");
5840 NSLog (@"unmark (accept) text");
5841 [self deleteWorkingText];
5842 processingCompose = NO;
5846 /* used to position char selection windows, etc. */
5847 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
5851 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
5853 NSLog (@"firstRectForCharRange request");
5855 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
5856 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
5857 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
5858 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
5859 +FRAME_LINE_HEIGHT (emacsframe));
5861 pt = [self convertPoint: pt toView: nil];
5862 pt = [[self window] convertBaseToScreen: pt];
5868 - (NSInteger)conversationIdentifier
5870 return (NSInteger)self;
5874 - (void)doCommandBySelector: (SEL)aSelector
5877 NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
5879 processingCompose = NO;
5880 if (aSelector == @selector (deleteBackward:))
5882 /* happens when user backspaces over an ongoing composition:
5883 throw a 'delete' into the event queue */
5886 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5887 emacs_event->code = 0xFF08;
5888 EV_TRAILER ((id)nil);
5892 - (NSArray *)validAttributesForMarkedText
5894 static NSArray *arr = nil;
5895 if (arr == nil) arr = [NSArray new];
5896 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
5900 - (NSRange)selectedRange
5903 NSLog (@"selectedRange request");
5904 return NSMakeRange (NSNotFound, 0);
5907 #if defined (NS_IMPL_COCOA) || GNUSTEP_GUI_MAJOR_VERSION > 0 || \
5908 GNUSTEP_GUI_MINOR_VERSION > 22
5909 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
5911 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
5915 NSLog (@"characterIndexForPoint request");
5919 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
5921 static NSAttributedString *str = nil;
5922 if (str == nil) str = [NSAttributedString new];
5924 NSLog (@"attributedSubstringFromRange request");
5928 /* End <NSTextInput> impl. */
5929 /*****************************************************************************/
5932 /* This is what happens when the user presses a mouse button. */
5933 - (void)mouseDown: (NSEvent *)theEvent
5935 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
5936 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5938 NSTRACE ("mouseDown");
5940 [self deleteWorkingText];
5945 dpyinfo->last_mouse_frame = emacsframe;
5946 /* appears to be needed to prevent spurious movement events generated on
5948 emacsframe->mouse_moved = 0;
5950 if ([theEvent type] == NSScrollWheel)
5952 CGFloat delta = [theEvent deltaY];
5953 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
5956 delta = [theEvent deltaX];
5959 NSTRACE ("deltaIsZero");
5962 emacs_event->kind = HORIZ_WHEEL_EVENT;
5965 emacs_event->kind = WHEEL_EVENT;
5967 emacs_event->code = 0;
5968 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
5969 ((delta > 0) ? up_modifier : down_modifier);
5973 emacs_event->kind = MOUSE_CLICK_EVENT;
5974 emacs_event->code = EV_BUTTON (theEvent);
5975 emacs_event->modifiers = EV_MODIFIERS (theEvent)
5976 | EV_UDMODIFIERS (theEvent);
5978 XSETINT (emacs_event->x, lrint (p.x));
5979 XSETINT (emacs_event->y, lrint (p.y));
5980 EV_TRAILER (theEvent);
5984 - (void)rightMouseDown: (NSEvent *)theEvent
5986 NSTRACE ("rightMouseDown");
5987 [self mouseDown: theEvent];
5991 - (void)otherMouseDown: (NSEvent *)theEvent
5993 NSTRACE ("otherMouseDown");
5994 [self mouseDown: theEvent];
5998 - (void)mouseUp: (NSEvent *)theEvent
6000 NSTRACE ("mouseUp");
6001 [self mouseDown: theEvent];
6005 - (void)rightMouseUp: (NSEvent *)theEvent
6007 NSTRACE ("rightMouseUp");
6008 [self mouseDown: theEvent];
6012 - (void)otherMouseUp: (NSEvent *)theEvent
6014 NSTRACE ("otherMouseUp");
6015 [self mouseDown: theEvent];
6019 - (void) scrollWheel: (NSEvent *)theEvent
6021 NSTRACE ("scrollWheel");
6022 [self mouseDown: theEvent];
6026 /* Tell emacs the mouse has moved. */
6027 - (void)mouseMoved: (NSEvent *)e
6029 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
6030 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6034 // NSTRACE ("mouseMoved");
6036 dpyinfo->last_mouse_movement_time = EV_TIMESTAMP (e);
6037 pt = [self convertPoint: [e locationInWindow] fromView: nil];
6038 dpyinfo->last_mouse_motion_x = pt.x;
6039 dpyinfo->last_mouse_motion_y = pt.y;
6041 /* update any mouse face */
6042 if (hlinfo->mouse_face_hidden)
6044 hlinfo->mouse_face_hidden = 0;
6045 clear_mouse_face (hlinfo);
6048 /* tooltip handling */
6049 previous_help_echo_string = help_echo_string;
6050 help_echo_string = Qnil;
6052 if (!NILP (Vmouse_autoselect_window))
6054 NSTRACE ("mouse_autoselect_window");
6055 static Lisp_Object last_mouse_window;
6057 = window_from_coordinates (emacsframe, pt.x, pt.y, 0, 0);
6059 if (WINDOWP (window)
6060 && !EQ (window, last_mouse_window)
6061 && !EQ (window, selected_window)
6062 && (focus_follows_mouse
6063 || (EQ (XWINDOW (window)->frame,
6064 XWINDOW (selected_window)->frame))))
6066 NSTRACE ("in_window");
6067 emacs_event->kind = SELECT_WINDOW_EVENT;
6068 emacs_event->frame_or_window = window;
6071 /* Remember the last window where we saw the mouse. */
6072 last_mouse_window = window;
6075 if (!note_mouse_movement (emacsframe, pt.x, pt.y))
6076 help_echo_string = previous_help_echo_string;
6078 XSETFRAME (frame, emacsframe);
6079 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
6081 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
6082 (note_mouse_highlight), which is called through the
6083 note_mouse_movement () call above */
6084 any_help_event_p = YES;
6085 gen_help_event (help_echo_string, frame, help_echo_window,
6086 help_echo_object, help_echo_pos);
6089 if (emacsframe->mouse_moved && send_appdefined)
6090 ns_send_appdefined (-1);
6094 - (void)mouseDragged: (NSEvent *)e
6096 NSTRACE ("mouseDragged");
6097 [self mouseMoved: e];
6101 - (void)rightMouseDragged: (NSEvent *)e
6103 NSTRACE ("rightMouseDragged");
6104 [self mouseMoved: e];
6108 - (void)otherMouseDragged: (NSEvent *)e
6110 NSTRACE ("otherMouseDragged");
6111 [self mouseMoved: e];
6115 - (BOOL)windowShouldClose: (id)sender
6117 NSEvent *e =[[self window] currentEvent];
6119 NSTRACE ("windowShouldClose");
6120 windowClosing = YES;
6123 emacs_event->kind = DELETE_WINDOW_EVENT;
6124 emacs_event->modifiers = 0;
6125 emacs_event->code = 0;
6127 /* Don't close this window, let this be done from lisp code. */
6131 - (void) updateFrameSize: (BOOL) delay;
6133 NSWindow *window = [self window];
6134 NSRect wr = [window frame];
6136 int oldc = cols, oldr = rows;
6137 int oldw = FRAME_PIXEL_WIDTH (emacsframe);
6138 int oldh = FRAME_PIXEL_HEIGHT (emacsframe);
6141 NSTRACE ("updateFrameSize");
6142 NSTRACE_SIZE ("Original size", NSMakeSize (oldw, oldh));
6143 NSTRACE_RECT ("Original frame", wr);
6144 NSTRACE_MSG ("Original columns: %d", cols);
6145 NSTRACE_MSG ("Original rows: %d", rows);
6147 if (! [self isFullscreen])
6149 #ifdef NS_IMPL_GNUSTEP
6150 // GNUstep does not always update the tool bar height. Force it.
6151 if (toolbar && [toolbar isVisible])
6152 update_frame_tool_bar (emacsframe);
6155 extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6156 + FRAME_TOOLBAR_HEIGHT (emacsframe);
6159 if (wait_for_tool_bar)
6161 if (FRAME_TOOLBAR_HEIGHT (emacsframe) == 0)
6163 NSTRACE_MSG ("Waiting for toolbar");
6166 wait_for_tool_bar = NO;
6169 neww = (int)wr.size.width - emacsframe->border_width;
6170 newh = (int)wr.size.height - extra;
6172 NSTRACE_SIZE ("New size", NSMakeSize (neww, newh));
6173 NSTRACE_MSG ("tool_bar_height: %d", emacsframe->tool_bar_height);
6175 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, neww);
6176 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, newh);
6178 if (cols < MINWIDTH)
6181 if (rows < MINHEIGHT)
6184 NSTRACE_MSG ("New columns: %d", cols);
6185 NSTRACE_MSG ("New rows: %d", rows);
6187 if (oldr != rows || oldc != cols || neww != oldw || newh != oldh)
6189 NSView *view = FRAME_NS_VIEW (emacsframe);
6190 NSWindow *win = [view window];
6192 change_frame_size (emacsframe,
6193 FRAME_PIXEL_TO_TEXT_WIDTH (emacsframe, neww),
6194 FRAME_PIXEL_TO_TEXT_HEIGHT (emacsframe, newh),
6196 SET_FRAME_GARBAGED (emacsframe);
6197 cancel_mouse_face (emacsframe);
6199 wr = NSMakeRect (0, 0, neww, newh);
6200 NSTRACE_RECT ("setFrame", wr);
6201 [view setFrame: wr];
6202 [self windowDidMove:nil]; // Update top/left.
6206 NSTRACE_MSG ("No change");
6210 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
6211 /* normalize frame to gridded text size */
6215 NSTRACE ("windowWillResize: toSize: " NSTRACE_FMT_SIZE,
6216 NSTRACE_ARG_SIZE (frameSize));
6217 NSTRACE_RECT ("[sender frame]", [sender frame]);
6218 NSTRACE_FSTYPE ("fs_state", fs_state);
6220 if (fs_state == FULLSCREEN_MAXIMIZED
6221 && (maximized_width != (int)frameSize.width
6222 || maximized_height != (int)frameSize.height))
6223 [self setFSValue: FULLSCREEN_NONE];
6224 else if (fs_state == FULLSCREEN_WIDTH
6225 && maximized_width != (int)frameSize.width)
6226 [self setFSValue: FULLSCREEN_NONE];
6227 else if (fs_state == FULLSCREEN_HEIGHT
6228 && maximized_height != (int)frameSize.height)
6229 [self setFSValue: FULLSCREEN_NONE];
6231 if (fs_state == FULLSCREEN_NONE)
6232 maximized_width = maximized_height = -1;
6234 if (! [self isFullscreen])
6236 extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6237 + FRAME_TOOLBAR_HEIGHT (emacsframe);
6240 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, frameSize.width);
6241 if (cols < MINWIDTH)
6244 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe,
6245 frameSize.height - extra);
6246 if (rows < MINHEIGHT)
6248 #ifdef NS_IMPL_COCOA
6250 /* this sets window title to have size in it; the wm does this under GS */
6251 NSRect r = [[self window] frame];
6252 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
6260 else if (fs_state == FULLSCREEN_NONE && ! maximizing_resize)
6263 NSWindow *window = [self window];
6266 char *t = strdup ([[[self window] title] UTF8String]);
6267 char *pos = strstr (t, " — ");
6272 size_title = xmalloc (strlen (old_title) + 40);
6273 esprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
6274 [window setTitle: [NSString stringWithUTF8String: size_title]];
6279 #endif /* NS_IMPL_COCOA */
6281 NSTRACE_MSG ("cols: %d rows: %d", cols, rows);
6283 /* Restrict the new size to the text gird.
6285 Don't restict the width if the user only adjusted the height, and
6286 vice versa. (Without this, the frame would shrink, and move
6287 slightly, if the window was resized by dragging one of its
6289 if (!frame_resize_pixelwise)
6291 NSRect r = [[self window] frame];
6293 if (r.size.width != frameSize.width)
6296 FRAME_TEXT_COLS_TO_PIXEL_WIDTH (emacsframe, cols);
6299 if (r.size.height != frameSize.height)
6302 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows) + extra;
6306 NSTRACE_RETURN_SIZE (frameSize);
6312 - (void)windowDidResize: (NSNotification *)notification
6314 NSTRACE ("windowDidResize");
6316 if (emacsframe->output_data.ns->in_animation)
6318 NSTRACE_MSG ("Ignored (in animation)");
6322 if (! [self fsIsNative])
6324 NSWindow *theWindow = [notification object];
6325 /* We can get notification on the non-FS window when in
6327 if ([self window] != theWindow) return;
6330 NSTRACE_RECT ("frame", [[notification object] frame]);
6332 #ifdef NS_IMPL_GNUSTEP
6333 NSWindow *theWindow = [notification object];
6335 /* In GNUstep, at least currently, it's possible to get a didResize
6336 without getting a willResize.. therefore we need to act as if we got
6337 the willResize now */
6338 NSSize sz = [theWindow frame].size;
6339 sz = [self windowWillResize: theWindow toSize: sz];
6340 #endif /* NS_IMPL_GNUSTEP */
6342 if (cols > 0 && rows > 0)
6344 [self updateFrameSize: YES];
6347 ns_send_appdefined (-1);
6350 #ifdef NS_IMPL_COCOA
6351 - (void)viewDidEndLiveResize
6353 [super viewDidEndLiveResize];
6356 [[self window] setTitle: [NSString stringWithUTF8String: old_title]];
6360 maximizing_resize = NO;
6362 #endif /* NS_IMPL_COCOA */
6365 - (void)windowDidBecomeKey: (NSNotification *)notification
6366 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6368 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6369 struct frame *old_focus = dpyinfo->x_focus_frame;
6371 NSTRACE ("windowDidBecomeKey");
6373 if (emacsframe != old_focus)
6374 dpyinfo->x_focus_frame = emacsframe;
6376 ns_frame_rehighlight (emacsframe);
6380 emacs_event->kind = FOCUS_IN_EVENT;
6381 EV_TRAILER ((id)nil);
6386 - (void)windowDidResignKey: (NSNotification *)notification
6387 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6389 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6390 BOOL is_focus_frame = dpyinfo->x_focus_frame == emacsframe;
6391 NSTRACE ("windowDidResignKey");
6394 dpyinfo->x_focus_frame = 0;
6396 emacsframe->mouse_moved = 0;
6397 ns_frame_rehighlight (emacsframe);
6399 /* FIXME: for some reason needed on second and subsequent clicks away
6400 from sole-frame Emacs to get hollow box to show */
6401 if (!windowClosing && [[self window] isVisible] == YES)
6403 x_update_cursor (emacsframe, 1);
6404 x_set_frame_alpha (emacsframe);
6407 if (any_help_event_p)
6410 XSETFRAME (frame, emacsframe);
6411 help_echo_string = Qnil;
6412 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
6415 if (emacs_event && is_focus_frame)
6417 [self deleteWorkingText];
6418 emacs_event->kind = FOCUS_OUT_EVENT;
6419 EV_TRAILER ((id)nil);
6424 - (void)windowWillMiniaturize: sender
6426 NSTRACE ("windowWillMiniaturize");
6442 - initFrameFromEmacs: (struct frame *)f
6450 NSTRACE ("initFrameFromEmacs");
6453 processingCompose = NO;
6454 scrollbarsNeedingUpdate = 0;
6455 fs_state = FULLSCREEN_NONE;
6456 fs_before_fs = next_maximized = -1;
6457 #ifdef HAVE_NATIVE_FS
6458 fs_is_native = ns_use_native_fullscreen;
6462 maximized_width = maximized_height = -1;
6465 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
6467 ns_userRect = NSMakeRect (0, 0, 0, 0);
6468 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
6469 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
6470 [self initWithFrame: r];
6471 [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
6473 FRAME_NS_VIEW (f) = self;
6475 #ifdef NS_IMPL_COCOA
6477 maximizing_resize = NO;
6480 win = [[EmacsWindow alloc]
6481 initWithContentRect: r
6482 styleMask: (NSResizableWindowMask |
6483 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6484 NSTitledWindowMask |
6486 NSMiniaturizableWindowMask |
6487 NSClosableWindowMask)
6488 backing: NSBackingStoreBuffered
6491 #ifdef HAVE_NATIVE_FS
6492 [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
6496 bwidth = f->border_width = wr.size.width - r.size.width;
6497 tibar_height = FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
6499 [win setAcceptsMouseMovedEvents: YES];
6500 [win setDelegate: self];
6501 #if !defined (NS_IMPL_COCOA) || \
6502 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6503 [win useOptimizedDrawing: YES];
6506 [[win contentView] addSubview: self];
6509 [self registerForDraggedTypes: ns_drag_types];
6512 name = [NSString stringWithUTF8String:
6513 NILP (tem) ? "Emacs" : SSDATA (tem)];
6514 [win setTitle: name];
6516 /* toolbar support */
6517 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
6518 [NSString stringWithFormat: @"Emacs Frame %d",
6520 [win setToolbar: toolbar];
6521 [toolbar setVisible: NO];
6523 /* Don't set frame garbaged until tool bar is up to date?
6524 This avoids an extra clear and redraw (flicker) at frame creation. */
6525 if (FRAME_EXTERNAL_TOOL_BAR (f)) wait_for_tool_bar = YES;
6526 else wait_for_tool_bar = NO;
6529 #ifdef NS_IMPL_COCOA
6531 NSButton *toggleButton;
6532 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
6533 [toggleButton setTarget: self];
6534 [toggleButton setAction: @selector (toggleToolbar: )];
6537 FRAME_TOOLBAR_HEIGHT (f) = 0;
6541 [win setMiniwindowTitle:
6542 [NSString stringWithUTF8String: SSDATA (tem)]];
6545 NSScreen *screen = [win screen];
6549 NSPoint pt = NSMakePoint
6550 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
6551 IN_BOUND (-SCREENMAX,
6552 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX));
6554 NSTRACE_POINT ("setFrameTopLeftPoint", pt);
6556 [win setFrameTopLeftPoint: pt];
6558 NSTRACE_RECT ("new frame", [win frame]);
6562 [win makeFirstResponder: self];
6564 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6565 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
6566 [win setBackgroundColor: col];
6567 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6568 [win setOpaque: NO];
6570 #if !defined (NS_IMPL_COCOA) || \
6571 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6572 [self allocateGState];
6574 [NSApp registerServicesMenuSendTypes: ns_send_types
6582 - (void)windowDidMove: sender
6584 NSWindow *win = [self window];
6585 NSRect r = [win frame];
6586 NSArray *screens = [NSScreen screens];
6587 NSScreen *screen = [screens objectAtIndex: 0];
6589 NSTRACE ("windowDidMove");
6591 if (!emacsframe->output_data.ns)
6595 emacsframe->left_pos = r.origin.x;
6596 emacsframe->top_pos =
6597 [screen frame].size.height - (r.origin.y + r.size.height);
6602 /* Called AFTER method below, but before our windowWillResize call there leads
6603 to windowDidResize -> x_set_window_size. Update emacs' notion of frame
6604 location so set_window_size moves the frame. */
6605 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
6607 NSTRACE (("[windowShouldZoom:win toFrame:" NSTRACE_FMT_RECT "]"
6608 NSTRACE_FMT_RETURN "YES"),
6609 NSTRACE_ARG_RECT (newFrame));
6611 emacsframe->output_data.ns->zooming = 1;
6616 /* Override to do something slightly nonstandard, but nice. First click on
6617 zoom button will zoom vertically. Second will zoom completely. Third
6618 returns to original. */
6619 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
6620 defaultFrame:(NSRect)defaultFrame
6622 // TODO: Rename to "currentFrame" and assign "result" properly in
6624 NSRect result = [sender frame];
6626 NSTRACE (("[windowWillUseStandardFrame: defaultFrame:"
6627 NSTRACE_FMT_RECT "]"),
6628 NSTRACE_ARG_RECT (defaultFrame));
6629 NSTRACE_FSTYPE ("fs_state", fs_state);
6630 NSTRACE_FSTYPE ("fs_before_fs", fs_before_fs);
6631 NSTRACE_FSTYPE ("next_maximized", next_maximized);
6632 NSTRACE_RECT ("ns_userRect", ns_userRect);
6633 NSTRACE_RECT ("[sender frame]", [sender frame]);
6635 if (fs_before_fs != -1) /* Entering fullscreen */
6637 NSTRACE_MSG ("Entering fullscreen");
6638 result = defaultFrame;
6642 // Save the window size and position (frame) before the resize.
6643 if (fs_state != FULLSCREEN_MAXIMIZED
6644 && fs_state != FULLSCREEN_WIDTH)
6646 ns_userRect.size.width = result.size.width;
6647 ns_userRect.origin.x = result.origin.x;
6650 if (fs_state != FULLSCREEN_MAXIMIZED
6651 && fs_state != FULLSCREEN_HEIGHT)
6653 ns_userRect.size.height = result.size.height;
6654 ns_userRect.origin.y = result.origin.y;
6657 NSTRACE_RECT ("ns_userRect (2)", ns_userRect);
6659 if (next_maximized == FULLSCREEN_HEIGHT
6660 || (next_maximized == -1
6661 && abs ((int)(defaultFrame.size.height - result.size.height))
6662 > FRAME_LINE_HEIGHT (emacsframe)))
6665 NSTRACE_MSG ("FULLSCREEN_HEIGHT");
6666 maximized_height = result.size.height = defaultFrame.size.height;
6667 maximized_width = -1;
6668 result.origin.y = defaultFrame.origin.y;
6669 if (ns_userRect.size.height != 0)
6671 result.origin.x = ns_userRect.origin.x;
6672 result.size.width = ns_userRect.size.width;
6674 [self setFSValue: FULLSCREEN_HEIGHT];
6675 #ifdef NS_IMPL_COCOA
6676 maximizing_resize = YES;
6679 else if (next_maximized == FULLSCREEN_WIDTH)
6681 NSTRACE_MSG ("FULLSCREEN_WIDTH");
6682 maximized_width = result.size.width = defaultFrame.size.width;
6683 maximized_height = -1;
6684 result.origin.x = defaultFrame.origin.x;
6685 if (ns_userRect.size.width != 0)
6687 result.origin.y = ns_userRect.origin.y;
6688 result.size.height = ns_userRect.size.height;
6690 [self setFSValue: FULLSCREEN_WIDTH];
6692 else if (next_maximized == FULLSCREEN_MAXIMIZED
6693 || (next_maximized == -1
6694 && abs ((int)(defaultFrame.size.width - result.size.width))
6695 > FRAME_COLUMN_WIDTH (emacsframe)))
6697 NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
6699 result = defaultFrame; /* second click */
6700 maximized_width = result.size.width;
6701 maximized_height = result.size.height;
6702 [self setFSValue: FULLSCREEN_MAXIMIZED];
6703 #ifdef NS_IMPL_COCOA
6704 maximizing_resize = YES;
6710 NSTRACE_MSG ("Restore");
6711 result = ns_userRect.size.height ? ns_userRect : result;
6712 NSTRACE_RECT ("restore (2)", result);
6713 ns_userRect = NSMakeRect (0, 0, 0, 0);
6714 #ifdef NS_IMPL_COCOA
6715 maximizing_resize = fs_state != FULLSCREEN_NONE;
6717 [self setFSValue: FULLSCREEN_NONE];
6718 maximized_width = maximized_height = -1;
6722 if (fs_before_fs == -1) next_maximized = -1;
6724 NSTRACE_RECT ("Final ns_userRect", ns_userRect);
6725 NSTRACE_MSG ("Final maximized_width: %d", maximized_width);
6726 NSTRACE_MSG ("Final maximized_height: %d", maximized_height);
6727 NSTRACE_FSTYPE ("Final next_maximized", next_maximized);
6729 [self windowWillResize: sender toSize: result.size];
6731 NSTRACE_RETURN_RECT (result);
6737 - (void)windowDidDeminiaturize: sender
6739 NSTRACE ("windowDidDeminiaturize");
6740 if (!emacsframe->output_data.ns)
6743 SET_FRAME_ICONIFIED (emacsframe, 0);
6744 SET_FRAME_VISIBLE (emacsframe, 1);
6745 windows_or_buffers_changed = 63;
6749 emacs_event->kind = DEICONIFY_EVENT;
6750 EV_TRAILER ((id)nil);
6755 - (void)windowDidExpose: sender
6757 NSTRACE ("windowDidExpose");
6758 if (!emacsframe->output_data.ns)
6761 SET_FRAME_VISIBLE (emacsframe, 1);
6762 SET_FRAME_GARBAGED (emacsframe);
6764 if (send_appdefined)
6765 ns_send_appdefined (-1);
6769 - (void)windowDidMiniaturize: sender
6771 NSTRACE ("windowDidMiniaturize");
6772 if (!emacsframe->output_data.ns)
6775 SET_FRAME_ICONIFIED (emacsframe, 1);
6776 SET_FRAME_VISIBLE (emacsframe, 0);
6780 emacs_event->kind = ICONIFY_EVENT;
6781 EV_TRAILER ((id)nil);
6785 #ifdef HAVE_NATIVE_FS
6786 - (NSApplicationPresentationOptions)window:(NSWindow *)window
6787 willUseFullScreenPresentationOptions:
6788 (NSApplicationPresentationOptions)proposedOptions
6790 return proposedOptions|NSApplicationPresentationAutoHideToolbar;
6794 - (void)windowWillEnterFullScreen:(NSNotification *)notification
6796 NSTRACE ("windowWillEnterFullScreen");
6797 fs_before_fs = fs_state;
6800 - (void)windowDidEnterFullScreen:(NSNotification *)notification
6802 NSTRACE ("windowDidEnterFullScreen");
6803 [self setFSValue: FULLSCREEN_BOTH];
6804 if (! [self fsIsNative])
6806 [self windowDidBecomeKey:notification];
6807 [nonfs_window orderOut:self];
6811 BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (emacsframe) ? YES : NO;
6812 #ifdef NS_IMPL_COCOA
6813 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6814 unsigned val = (unsigned)[NSApp presentationOptions];
6816 // OSX 10.7 bug fix, the menu won't appear without this.
6817 // val is non-zero on other OSX versions.
6820 NSApplicationPresentationOptions options
6821 = NSApplicationPresentationAutoHideDock
6822 | NSApplicationPresentationAutoHideMenuBar
6823 | NSApplicationPresentationFullScreen
6824 | NSApplicationPresentationAutoHideToolbar;
6826 [NSApp setPresentationOptions: options];
6830 [toolbar setVisible:tbar_visible];
6834 - (void)windowWillExitFullScreen:(NSNotification *)notification
6836 NSTRACE ("windowWillExitFullScreen");
6838 if (next_maximized != -1)
6839 fs_before_fs = next_maximized;
6842 - (void)windowDidExitFullScreen:(NSNotification *)notification
6844 NSTRACE ("windowDidExitFullScreen");
6846 [self setFSValue: fs_before_fs];
6848 #ifdef HAVE_NATIVE_FS
6849 [self updateCollectionBehavior];
6851 if (FRAME_EXTERNAL_TOOL_BAR (emacsframe))
6853 [toolbar setVisible:YES];
6854 update_frame_tool_bar (emacsframe);
6855 [self updateFrameSize:YES];
6856 [[self window] display];
6859 [toolbar setVisible:NO];
6861 if (next_maximized != -1)
6862 [[self window] performZoom:self];
6867 return fs_is_native;
6870 - (BOOL)isFullscreen
6872 if (! fs_is_native) return nonfs_window != nil;
6873 #ifdef HAVE_NATIVE_FS
6874 return ([[self window] styleMask] & NSFullScreenWindowMask) != 0;
6880 #ifdef HAVE_NATIVE_FS
6881 - (void)updateCollectionBehavior
6883 if (! [self isFullscreen])
6885 NSWindow *win = [self window];
6886 NSWindowCollectionBehavior b = [win collectionBehavior];
6887 if (ns_use_native_fullscreen)
6888 b |= NSWindowCollectionBehaviorFullScreenPrimary;
6890 b &= ~NSWindowCollectionBehaviorFullScreenPrimary;
6892 [win setCollectionBehavior: b];
6893 fs_is_native = ns_use_native_fullscreen;
6898 - (void)toggleFullScreen: (id)sender
6906 NSTRACE ("toggleFullScreen");
6910 #ifdef HAVE_NATIVE_FS
6911 [[self window] toggleFullScreen:sender];
6917 onFirstScreen = [[w screen] isEqual:[[NSScreen screens] objectAtIndex:0]];
6920 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6921 (FRAME_DEFAULT_FACE (f)),
6924 if (fs_state != FULLSCREEN_BOTH)
6926 NSScreen *screen = [w screen];
6928 #if defined (NS_IMPL_COCOA) && \
6929 MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
6930 /* Hide ghost menu bar on secondary monitor? */
6931 if (! onFirstScreen)
6932 onFirstScreen = [NSScreen screensHaveSeparateSpaces];
6934 /* Hide dock and menubar if we are on the primary screen. */
6937 #ifdef NS_IMPL_COCOA
6938 NSApplicationPresentationOptions options
6939 = NSApplicationPresentationAutoHideDock
6940 | NSApplicationPresentationAutoHideMenuBar;
6942 [NSApp setPresentationOptions: options];
6944 [NSMenu setMenuBarVisible:NO];
6948 fw = [[EmacsFSWindow alloc]
6949 initWithContentRect:[w contentRectForFrameRect:wr]
6950 styleMask:NSBorderlessWindowMask
6951 backing:NSBackingStoreBuffered
6955 [fw setContentView:[w contentView]];
6956 [fw setTitle:[w title]];
6957 [fw setDelegate:self];
6958 [fw setAcceptsMouseMovedEvents: YES];
6959 #if !defined (NS_IMPL_COCOA) || \
6960 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6961 [fw useOptimizedDrawing: YES];
6963 [fw setBackgroundColor: col];
6964 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6967 f->border_width = 0;
6968 FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
6969 tobar_height = FRAME_TOOLBAR_HEIGHT (f);
6970 FRAME_TOOLBAR_HEIGHT (f) = 0;
6974 [self windowWillEnterFullScreen:nil];
6975 [fw makeKeyAndOrderFront:NSApp];
6976 [fw makeFirstResponder:self];
6978 r = [fw frameRectForContentRect:[screen frame]];
6979 [fw setFrame: r display:YES animate:ns_use_fullscreen_animation];
6980 [self windowDidEnterFullScreen:nil];
6991 #ifdef NS_IMPL_COCOA
6992 [NSApp setPresentationOptions: NSApplicationPresentationDefault];
6994 [NSMenu setMenuBarVisible:YES];
6998 [w setContentView:[fw contentView]];
6999 [w setBackgroundColor: col];
7000 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
7003 f->border_width = bwidth;
7004 FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
7005 if (FRAME_EXTERNAL_TOOL_BAR (f))
7006 FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
7008 [self windowWillExitFullScreen:nil];
7009 [fw setFrame: [w frame] display:YES animate:ns_use_fullscreen_animation];
7011 [w makeKeyAndOrderFront:NSApp];
7012 [self windowDidExitFullScreen:nil];
7013 [self updateFrameSize:YES];
7019 NSTRACE ("handleFS");
7021 if (fs_state != emacsframe->want_fullscreen)
7023 if (fs_state == FULLSCREEN_BOTH)
7025 NSTRACE_MSG ("fs_state == FULLSCREEN_BOTH");
7026 [self toggleFullScreen:self];
7029 switch (emacsframe->want_fullscreen)
7031 case FULLSCREEN_BOTH:
7032 NSTRACE_MSG ("FULLSCREEN_BOTH");
7033 [self toggleFullScreen:self];
7035 case FULLSCREEN_WIDTH:
7036 NSTRACE_MSG ("FULLSCREEN_WIDTH");
7037 next_maximized = FULLSCREEN_WIDTH;
7038 if (fs_state != FULLSCREEN_BOTH)
7039 [[self window] performZoom:self];
7041 case FULLSCREEN_HEIGHT:
7042 NSTRACE_MSG ("FULLSCREEN_HEIGHT");
7043 next_maximized = FULLSCREEN_HEIGHT;
7044 if (fs_state != FULLSCREEN_BOTH)
7045 [[self window] performZoom:self];
7047 case FULLSCREEN_MAXIMIZED:
7048 NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
7049 next_maximized = FULLSCREEN_MAXIMIZED;
7050 if (fs_state != FULLSCREEN_BOTH)
7051 [[self window] performZoom:self];
7053 case FULLSCREEN_NONE:
7054 NSTRACE_MSG ("FULLSCREEN_NONE");
7055 if (fs_state != FULLSCREEN_BOTH)
7057 next_maximized = FULLSCREEN_NONE;
7058 [[self window] performZoom:self];
7063 emacsframe->want_fullscreen = FULLSCREEN_NONE;
7068 - (void) setFSValue: (int)value
7070 NSTRACE ("setFSValue");
7071 NSTRACE_FSTYPE ("value", value);
7073 Lisp_Object lval = Qnil;
7076 case FULLSCREEN_BOTH:
7079 case FULLSCREEN_WIDTH:
7082 case FULLSCREEN_HEIGHT:
7085 case FULLSCREEN_MAXIMIZED:
7089 store_frame_param (emacsframe, Qfullscreen, lval);
7093 - (void)mouseEntered: (NSEvent *)theEvent
7095 NSTRACE ("mouseEntered");
7097 FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7098 = EV_TIMESTAMP (theEvent);
7102 - (void)mouseExited: (NSEvent *)theEvent
7104 Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
7106 NSTRACE ("mouseExited");
7111 FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7112 = EV_TIMESTAMP (theEvent);
7114 if (emacsframe == hlinfo->mouse_face_mouse_frame)
7116 clear_mouse_face (hlinfo);
7117 hlinfo->mouse_face_mouse_frame = 0;
7124 NSTRACE ("menuDown");
7125 if (context_menu_value == -1)
7126 context_menu_value = [sender tag];
7129 NSInteger tag = [sender tag];
7130 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
7131 emacsframe->menu_bar_vector,
7135 ns_send_appdefined (-1);
7140 - (EmacsToolbar *)toolbar
7146 /* this gets called on toolbar button click */
7147 - toolbarClicked: (id)item
7150 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
7152 NSTRACE ("toolbarClicked");
7157 /* send first event (for some reason two needed) */
7158 theEvent = [[self window] currentEvent];
7159 emacs_event->kind = TOOL_BAR_EVENT;
7160 XSETFRAME (emacs_event->arg, emacsframe);
7161 EV_TRAILER (theEvent);
7163 emacs_event->kind = TOOL_BAR_EVENT;
7164 /* XSETINT (emacs_event->code, 0); */
7165 emacs_event->arg = AREF (emacsframe->tool_bar_items,
7166 idx + TOOL_BAR_ITEM_KEY);
7167 emacs_event->modifiers = EV_MODIFIERS (theEvent);
7168 EV_TRAILER (theEvent);
7173 - toggleToolbar: (id)sender
7178 emacs_event->kind = NS_NONKEY_EVENT;
7179 emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
7180 EV_TRAILER ((id)nil);
7185 - (void)drawRect: (NSRect)rect
7187 int x = NSMinX (rect), y = NSMinY (rect);
7188 int width = NSWidth (rect), height = NSHeight (rect);
7190 NSTRACE ("drawRect");
7191 NSTRACE_RECT ("input", rect);
7193 if (!emacsframe || !emacsframe->output_data.ns)
7196 ns_clear_frame_area (emacsframe, x, y, width, height);
7198 expose_frame (emacsframe, x, y, width, height);
7202 drawRect: may be called (at least in OS X 10.5) for invisible
7203 views as well for some reason. Thus, do not infer visibility
7206 emacsframe->async_visible = 1;
7207 emacsframe->async_iconified = 0;
7212 /* NSDraggingDestination protocol methods. Actually this is not really a
7213 protocol, but a category of Object. O well... */
7215 -(NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
7217 NSTRACE ("draggingEntered");
7218 return NSDragOperationGeneric;
7222 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
7228 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
7233 NSEvent *theEvent = [[self window] currentEvent];
7235 NSDragOperation op = [sender draggingSourceOperationMask];
7238 NSTRACE ("performDragOperation");
7243 position = [self convertPoint: [sender draggingLocation] fromView: nil];
7244 x = lrint (position.x); y = lrint (position.y);
7246 pb = [sender draggingPasteboard];
7247 type = [pb availableTypeFromArray: ns_drag_types];
7249 if (! (op & (NSDragOperationMove|NSDragOperationDelete)) &&
7250 // URL drags contain all operations (0xf), don't allow all to be set.
7253 if (op & NSDragOperationLink)
7254 modifiers |= NSControlKeyMask;
7255 if (op & NSDragOperationCopy)
7256 modifiers |= NSAlternateKeyMask;
7257 if (op & NSDragOperationGeneric)
7258 modifiers |= NSCommandKeyMask;
7261 modifiers = EV_MODIFIERS2 (modifiers);
7266 else if ([type isEqualToString: NSFilenamesPboardType])
7269 NSEnumerator *fenum;
7272 if (!(files = [pb propertyListForType: type]))
7275 fenum = [files objectEnumerator];
7276 while ( (file = [fenum nextObject]) )
7278 emacs_event->kind = DRAG_N_DROP_EVENT;
7279 XSETINT (emacs_event->x, x);
7280 XSETINT (emacs_event->y, y);
7281 ns_input_file = append2 (ns_input_file,
7282 build_string ([file UTF8String]));
7283 emacs_event->modifiers = modifiers;
7284 emacs_event->arg = list2 (Qfile, build_string ([file UTF8String]));
7285 EV_TRAILER (theEvent);
7289 else if ([type isEqualToString: NSURLPboardType])
7291 NSURL *url = [NSURL URLFromPasteboard: pb];
7292 if (url == nil) return NO;
7294 emacs_event->kind = DRAG_N_DROP_EVENT;
7295 XSETINT (emacs_event->x, x);
7296 XSETINT (emacs_event->y, y);
7297 emacs_event->modifiers = modifiers;
7298 emacs_event->arg = list2 (Qurl,
7299 build_string ([[url absoluteString]
7301 EV_TRAILER (theEvent);
7303 if ([url isFileURL] != NO)
7305 NSString *file = [url path];
7306 ns_input_file = append2 (ns_input_file,
7307 build_string ([file UTF8String]));
7311 else if ([type isEqualToString: NSStringPboardType]
7312 || [type isEqualToString: NSTabularTextPboardType])
7316 if (! (data = [pb stringForType: type]))
7319 emacs_event->kind = DRAG_N_DROP_EVENT;
7320 XSETINT (emacs_event->x, x);
7321 XSETINT (emacs_event->y, y);
7322 emacs_event->modifiers = modifiers;
7323 emacs_event->arg = list2 (Qnil, build_string ([data UTF8String]));
7324 EV_TRAILER (theEvent);
7329 fprintf (stderr, "Invalid data type in dragging pasteboard");
7335 - (id) validRequestorForSendType: (NSString *)typeSent
7336 returnType: (NSString *)typeReturned
7338 NSTRACE ("validRequestorForSendType");
7339 if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
7340 && typeReturned == nil)
7342 if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
7346 return [super validRequestorForSendType: typeSent
7347 returnType: typeReturned];
7351 /* The next two methods are part of NSServicesRequests informal protocol,
7352 supposedly called when a services menu item is chosen from this app.
7353 But this should not happen because we override the services menu with our
7354 own entries which call ns-perform-service.
7355 Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
7356 So let's at least stub them out until further investigation can be done. */
7358 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
7360 /* we could call ns_string_from_pasteboard(pboard) here but then it should
7361 be written into the buffer in place of the existing selection..
7362 ordinary service calls go through functions defined in ns-win.el */
7366 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
7368 NSArray *typesDeclared;
7371 /* We only support NSStringPboardType */
7372 if ([types containsObject:NSStringPboardType] == NO) {
7376 val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7377 if (CONSP (val) && SYMBOLP (XCAR (val)))
7380 if (CONSP (val) && NILP (XCDR (val)))
7383 if (! STRINGP (val))
7386 typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
7387 [pb declareTypes:typesDeclared owner:nil];
7388 ns_string_to_pasteboard (pb, val);
7393 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
7394 (gives a miniaturized version of the window); currently we use the latter for
7395 frames whose active buffer doesn't correspond to any file
7396 (e.g., '*scratch*') */
7397 - setMiniwindowImage: (BOOL) setMini
7399 id image = [[self window] miniwindowImage];
7400 NSTRACE ("setMiniwindowImage");
7402 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
7403 about "AppleDockIconEnabled" notwithstanding, however the set message
7404 below has its effect nonetheless. */
7405 if (image != emacsframe->output_data.ns->miniimage)
7407 if (image && [image isKindOfClass: [EmacsImage class]])
7409 [[self window] setMiniwindowImage:
7410 setMini ? emacsframe->output_data.ns->miniimage : nil];
7417 - (void) setRows: (int) r andColumns: (int) c
7419 NSTRACE ("[EmacsView setRows:%d andColumns:%d]", r, c);
7424 - (int) fullscreenState
7429 @end /* EmacsView */
7433 /* ==========================================================================
7435 EmacsWindow implementation
7437 ========================================================================== */
7439 @implementation EmacsWindow
7441 #ifdef NS_IMPL_COCOA
7442 - (id)accessibilityAttributeValue:(NSString *)attribute
7444 Lisp_Object str = Qnil;
7445 struct frame *f = SELECTED_FRAME ();
7446 struct buffer *curbuf = XBUFFER (XWINDOW (f->selected_window)->contents);
7448 if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
7449 return NSAccessibilityTextFieldRole;
7451 if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]
7452 && curbuf && ! NILP (BVAR (curbuf, mark_active)))
7454 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7456 else if (curbuf && [attribute isEqualToString:NSAccessibilityValueAttribute])
7458 if (! NILP (BVAR (curbuf, mark_active)))
7459 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7463 ptrdiff_t start_byte = BUF_BEGV_BYTE (curbuf);
7464 ptrdiff_t byte_range = BUF_ZV_BYTE (curbuf) - start_byte;
7465 ptrdiff_t range = BUF_ZV (curbuf) - BUF_BEGV (curbuf);
7467 if (! NILP (BVAR (curbuf, enable_multibyte_characters)))
7468 str = make_uninit_multibyte_string (range, byte_range);
7470 str = make_uninit_string (range);
7471 /* To check: This returns emacs-utf-8, which is a superset of utf-8.
7472 Is this a problem? */
7473 memcpy (SDATA (str), BYTE_POS_ADDR (start_byte), byte_range);
7480 if (CONSP (str) && SYMBOLP (XCAR (str)))
7483 if (CONSP (str) && NILP (XCDR (str)))
7488 const char *utfStr = SSDATA (str);
7489 NSString *nsStr = [NSString stringWithUTF8String: utfStr];
7494 return [super accessibilityAttributeValue:attribute];
7496 #endif /* NS_IMPL_COCOA */
7498 /* Constrain size and placement of a frame.
7500 By returning the original "frameRect", the frame is not
7501 contrained. This can lead to unwanted situations where, for
7502 example, the menu bar covers the frame.
7504 The default implementation (accessed using "super") constrains the
7505 frame to the visible area of SCREEN, minus the menu bar (if
7506 present) and the Dock. Note that default implementation also calls
7507 windowWillResize, with the frame it thinks should have. (This can
7508 make the frame exit maximized mode.)
7510 Note that this should work in situations where multiple monitors
7511 are present. Common configurations are side-by-side monitors and a
7512 monitor on top of another (e.g. when a laptop is placed under a
7514 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
7516 NSTRACE ("constrainFrameRect:" NSTRACE_FMT_RECT " toScreen:",
7517 NSTRACE_ARG_RECT (frameRect));
7519 #ifdef NS_IMPL_COCOA
7520 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7521 // If separate spaces is on, it is like each screen is independent. There is
7522 // no spanning of frames across screens.
7523 if ([NSScreen screensHaveSeparateSpaces])
7525 NSTRACE_MSG ("Screens have separate spaces");
7526 frameRect = [super constrainFrameRect:frameRect toScreen:screen];
7527 NSTRACE_RETURN_RECT (frameRect);
7533 return constrain_frame_rect(frameRect);
7537 - (void)performZoom:(id)sender
7539 NSTRACE ("performZoom");
7541 return [super performZoom:sender];
7544 - (void)zoom:(id)sender
7546 struct frame * f = SELECTED_FRAME ();
7550 ns_update_auto_hide_menu_bar();
7552 // Below are three zoom implementations. In the final commit, the
7553 // idea is that the last should be included.
7556 // Native zoom done using the standard zoom animation. Size of the
7557 // resulting frame reduced to accomodate the Dock and, if present,
7559 [super zoom:sender];
7562 // Native zoom done using the standard zoom animation, plus an
7563 // explicit resize to cover the full screen.
7564 [super zoom:sender];
7566 // After the native zoom, resize the resulting frame to fill the
7567 // entire screen, except the menu-bar.
7569 // This works for all practical purposes. (The only minor oddity is
7570 // when transiting from full-height frame to a maximized, the
7571 // animation reduces the height of the frame slighty (to the 4
7572 // pixels needed to accomodate the Doc) before it snaps back into
7573 // full height. The user would need a very trained eye to spot
7575 NSScreen * screen = [self screen];
7578 int fs_state = [(EmacsView *)[self delegate] fullscreenState];
7580 NSTRACE_FSTYPE ("fullscreenState", fs_state);
7582 NSRect sr = [screen frame];
7583 NSRect wr = [self frame];
7584 NSTRACE_RECT ("Rect after zoom", wr);
7588 if (fs_state == FULLSCREEN_MAXIMIZED
7589 || fs_state == FULLSCREEN_HEIGHT)
7592 newWr.size.height = sr.size.height - ns_menu_bar_height(screen);
7595 if (fs_state == FULLSCREEN_MAXIMIZED
7596 || fs_state == FULLSCREEN_WIDTH)
7599 newWr.size.width = sr.size.width;
7602 if (newWr.size.width != wr.size.width
7603 || newWr.size.height != wr.size.height
7604 || newWr.origin.x != wr.origin.x
7605 || newWr.origin.y != wr.origin.y)
7607 NSTRACE_RECT ("Corrected rect", newWr);
7608 [self setFrame: newWr display: NO];
7612 // Non-native zoom which is done instantaneous. The resulting frame
7613 // covert the entire scrren, except the menu-bar, if present.
7614 NSScreen * screen = [self screen];
7617 NSRect sr = [screen frame];
7618 sr.size.height -= ns_menu_bar_height (screen);
7620 sr = [[self delegate] windowWillUseStandardFrame:self
7622 [self setFrame: sr display: NO];
7627 @end /* EmacsWindow */
7630 @implementation EmacsFSWindow
7632 - (BOOL)canBecomeKeyWindow
7637 - (BOOL)canBecomeMainWindow
7644 /* ==========================================================================
7646 EmacsScroller implementation
7648 ========================================================================== */
7651 @implementation EmacsScroller
7653 /* for repeat button push */
7654 #define SCROLL_BAR_FIRST_DELAY 0.5
7655 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
7657 + (CGFloat) scrollerWidth
7659 /* TODO: if we want to allow variable widths, this is the place to do it,
7660 however neither GNUstep nor Cocoa support it very well */
7662 #if !defined (NS_IMPL_COCOA) || \
7663 MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
7664 r = [NSScroller scrollerWidth];
7666 r = [NSScroller scrollerWidthForControlSize: NSRegularControlSize
7667 scrollerStyle: NSScrollerStyleLegacy];
7673 - initFrame: (NSRect )r window: (Lisp_Object)nwin
7675 NSTRACE ("EmacsScroller_initFrame");
7677 r.size.width = [EmacsScroller scrollerWidth];
7678 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
7679 [self setContinuous: YES];
7680 [self setEnabled: YES];
7682 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
7683 locked against the top and bottom edges, and right edge on OS X, where
7684 scrollers are on right. */
7685 #ifdef NS_IMPL_GNUSTEP
7686 [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
7688 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
7691 window = XWINDOW (nwin);
7693 pixel_height = NSHeight (r);
7694 if (pixel_height == 0) pixel_height = 1;
7695 min_portion = 20 / pixel_height;
7697 frame = XFRAME (window->frame);
7698 if (FRAME_LIVE_P (frame))
7701 EmacsView *view = FRAME_NS_VIEW (frame);
7702 NSView *sview = [[view window] contentView];
7703 NSArray *subs = [sview subviews];
7705 /* disable optimization stopping redraw of other scrollbars */
7706 view->scrollbarsNeedingUpdate = 0;
7707 for (i =[subs count]-1; i >= 0; i--)
7708 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
7709 view->scrollbarsNeedingUpdate++;
7710 [sview addSubview: self];
7713 /* [self setFrame: r]; */
7719 - (void)setFrame: (NSRect)newRect
7721 NSTRACE ("EmacsScroller_setFrame");
7722 /* block_input (); */
7723 pixel_height = NSHeight (newRect);
7724 if (pixel_height == 0) pixel_height = 1;
7725 min_portion = 20 / pixel_height;
7726 [super setFrame: newRect];
7727 /* unblock_input (); */
7733 NSTRACE ("EmacsScroller_dealloc");
7735 wset_vertical_scroll_bar (window, Qnil);
7743 NSTRACE ("condemn");
7751 NSTRACE ("reprieve");
7760 bool ret = condemned;
7765 /* ensure other scrollbar updates after deletion */
7766 view = (EmacsView *)FRAME_NS_VIEW (frame);
7768 view->scrollbarsNeedingUpdate++;
7770 wset_vertical_scroll_bar (window, Qnil);
7772 [self removeFromSuperview];
7780 - (void)resetCursorRects
7782 NSRect visible = [self visibleRect];
7783 NSTRACE ("resetCursorRects");
7785 if (!NSIsEmptyRect (visible))
7786 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
7787 [[NSCursor arrowCursor] setOnMouseEntered: YES];
7791 - (int) checkSamePosition: (int) position portion: (int) portion
7794 return em_position ==position && em_portion ==portion && em_whole ==whole
7795 && portion != whole; /* needed for resize empty buf */
7799 - setPosition: (int)position portion: (int)portion whole: (int)whole
7801 NSTRACE ("setPosition");
7803 em_position = position;
7804 em_portion = portion;
7807 if (portion >= whole)
7809 #ifdef NS_IMPL_COCOA
7810 [self setKnobProportion: 1.0];
7811 [self setDoubleValue: 1.0];
7813 [self setFloatValue: 0.0 knobProportion: 1.0];
7820 portion = max ((float)whole*min_portion/pixel_height, portion);
7821 pos = (float)position / (whole - portion);
7822 por = (CGFloat)portion/whole;
7823 #ifdef NS_IMPL_COCOA
7824 [self setKnobProportion: por];
7825 [self setDoubleValue: pos];
7827 [self setFloatValue: pos knobProportion: por];
7834 /* set up emacs_event */
7835 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
7841 emacs_event->part = last_hit_part;
7842 emacs_event->code = 0;
7843 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
7844 XSETWINDOW (win, window);
7845 emacs_event->frame_or_window = win;
7846 emacs_event->timestamp = EV_TIMESTAMP (e);
7847 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
7848 emacs_event->arg = Qnil;
7849 XSETINT (emacs_event->x, loc * pixel_height);
7850 XSETINT (emacs_event->y, pixel_height-20);
7854 n_emacs_events_pending++;
7855 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
7858 hold_event (emacs_event);
7859 EVENT_INIT (*emacs_event);
7860 ns_send_appdefined (-1);
7864 /* called manually thru timer to implement repeated button action w/hold-down */
7865 - repeatScroll: (NSTimer *)scrollEntry
7867 NSEvent *e = [[self window] currentEvent];
7868 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
7869 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
7871 /* clear timer if need be */
7872 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
7874 [scroll_repeat_entry invalidate];
7875 [scroll_repeat_entry release];
7876 scroll_repeat_entry = nil;
7882 = [[NSTimer scheduledTimerWithTimeInterval:
7883 SCROLL_BAR_CONTINUOUS_DELAY
7885 selector: @selector (repeatScroll:)
7891 [self sendScrollEventAtLoc: 0 fromEvent: e];
7896 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
7897 mouseDragged events without going into a modal loop. */
7898 - (void)mouseDown: (NSEvent *)e
7901 /* hitPart is only updated AFTER event is passed on */
7902 NSScrollerPart part = [self testPart: [e locationInWindow]];
7903 CGFloat inc = 0.0, loc, kloc, pos;
7906 NSTRACE ("EmacsScroller_mouseDown");
7910 case NSScrollerDecrementPage:
7911 last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
7912 case NSScrollerIncrementPage:
7913 last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
7914 case NSScrollerDecrementLine:
7915 last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
7916 case NSScrollerIncrementLine:
7917 last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
7918 case NSScrollerKnob:
7919 last_hit_part = scroll_bar_handle; break;
7920 case NSScrollerKnobSlot: /* GNUstep-only */
7921 last_hit_part = scroll_bar_move_ratio; break;
7922 default: /* NSScrollerNoPart? */
7923 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
7930 pos = 0; /* ignored */
7932 /* set a timer to repeat, as we can't let superclass do this modally */
7934 = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
7936 selector: @selector (repeatScroll:)
7943 /* handle, or on GNUstep possibly slot */
7944 NSEvent *fake_event;
7946 /* compute float loc in slot and mouse offset on knob */
7947 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
7949 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
7955 else if (loc >= NSHeight (sr))
7957 loc = NSHeight (sr);
7965 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
7967 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
7969 last_mouse_offset = kloc;
7971 /* if knob, tell emacs a location offset by knob pos
7972 (to indicate top of handle) */
7973 if (part == NSScrollerKnob)
7974 pos = (loc - last_mouse_offset) / NSHeight (sr);
7976 /* else this is a slot click on GNUstep: go straight there */
7977 pos = loc / NSHeight (sr);
7979 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
7980 fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
7981 location: [e locationInWindow]
7982 modifierFlags: [e modifierFlags]
7983 timestamp: [e timestamp]
7984 windowNumber: [e windowNumber]
7985 context: [e context]
7986 eventNumber: [e eventNumber]
7987 clickCount: [e clickCount]
7988 pressure: [e pressure]];
7989 [super mouseUp: fake_event];
7992 if (part != NSScrollerKnob)
7993 [self sendScrollEventAtLoc: pos fromEvent: e];
7997 /* Called as we manually track scroller drags, rather than superclass. */
7998 - (void)mouseDragged: (NSEvent *)e
8003 NSTRACE ("EmacsScroller_mouseDragged");
8005 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
8007 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
8013 else if (loc >= NSHeight (sr) + last_mouse_offset)
8015 loc = NSHeight (sr) + last_mouse_offset;
8018 pos = (loc - last_mouse_offset) / NSHeight (sr);
8019 [self sendScrollEventAtLoc: pos fromEvent: e];
8023 - (void)mouseUp: (NSEvent *)e
8025 if (scroll_repeat_entry)
8027 [scroll_repeat_entry invalidate];
8028 [scroll_repeat_entry release];
8029 scroll_repeat_entry = nil;
8031 last_hit_part = scroll_bar_above_handle;
8035 /* treat scrollwheel events in the bar as though they were in the main window */
8036 - (void) scrollWheel: (NSEvent *)theEvent
8038 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
8039 [view mouseDown: theEvent];
8042 @end /* EmacsScroller */
8045 #ifdef NS_IMPL_GNUSTEP
8046 /* Dummy class to get rid of startup warnings. */
8047 @implementation EmacsDocument
8053 /* ==========================================================================
8055 Font-related functions; these used to be in nsfaces.m
8057 ========================================================================== */
8061 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
8063 struct font *font = XFONT_OBJECT (font_object);
8064 EmacsView *view = FRAME_NS_VIEW (f);
8065 int font_ascent, font_descent;
8068 fontset = fontset_from_font (font_object);
8069 FRAME_FONTSET (f) = fontset;
8071 if (FRAME_FONT (f) == font)
8072 /* This font is already set in frame F. There's nothing more to
8076 FRAME_FONT (f) = font;
8078 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
8079 FRAME_COLUMN_WIDTH (f) = font->average_width;
8080 get_font_ascent_descent (font, &font_ascent, &font_descent);
8081 FRAME_LINE_HEIGHT (f) = font_ascent + font_descent;
8083 /* Compute the scroll bar width in character columns. */
8084 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
8086 int wid = FRAME_COLUMN_WIDTH (f);
8087 FRAME_CONFIG_SCROLL_BAR_COLS (f)
8088 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
8092 int wid = FRAME_COLUMN_WIDTH (f);
8093 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
8096 /* Compute the scroll bar height in character lines. */
8097 if (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) > 0)
8099 int height = FRAME_LINE_HEIGHT (f);
8100 FRAME_CONFIG_SCROLL_BAR_LINES (f)
8101 = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + height - 1) / height;
8105 int height = FRAME_LINE_HEIGHT (f);
8106 FRAME_CONFIG_SCROLL_BAR_LINES (f) = (14 + height - 1) / height;
8109 /* Now make the frame display the given font. */
8110 if (FRAME_NS_WINDOW (f) != 0 && ! [view isFullscreen])
8111 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
8112 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 3,
8119 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
8120 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
8124 ns_xlfd_to_fontname (const char *xlfd)
8125 /* --------------------------------------------------------------------------
8126 Convert an X font name (XLFD) to an NS font name.
8127 Only family is used.
8128 The string returned is temporarily allocated.
8129 -------------------------------------------------------------------------- */
8131 char *name = xmalloc (180);
8135 if (!strncmp (xlfd, "--", 2))
8136 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
8138 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
8140 /* stopgap for malformed XLFD input */
8141 if (strlen (name) == 0)
8142 strcpy (name, "Monaco");
8144 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
8145 also uppercase after '-' or ' ' */
8146 name[0] = c_toupper (name[0]);
8147 for (len =strlen (name), i =0; i<len; i++)
8153 name[i+1] = c_toupper (name[i+1]);
8155 else if (name[i] == '_')
8159 name[i+1] = c_toupper (name[i+1]);
8162 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
8163 ret = [[NSString stringWithUTF8String: name] UTF8String];
8170 syms_of_nsterm (void)
8172 NSTRACE ("syms_of_nsterm");
8174 ns_antialias_threshold = 10.0;
8176 /* from 23+ we need to tell emacs what modifiers there are.. */
8177 DEFSYM (Qmodifier_value, "modifier-value");
8178 DEFSYM (Qalt, "alt");
8179 DEFSYM (Qhyper, "hyper");
8180 DEFSYM (Qmeta, "meta");
8181 DEFSYM (Qsuper, "super");
8182 DEFSYM (Qcontrol, "control");
8183 DEFSYM (QUTF8_STRING, "UTF8_STRING");
8185 DEFSYM (Qfile, "file");
8186 DEFSYM (Qurl, "url");
8188 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
8189 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
8190 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
8191 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
8192 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
8194 DEFVAR_LISP ("ns-input-file", ns_input_file,
8195 "The file specified in the last NS event.");
8196 ns_input_file =Qnil;
8198 DEFVAR_LISP ("ns-working-text", ns_working_text,
8199 "String for visualizing working composition sequence.");
8200 ns_working_text =Qnil;
8202 DEFVAR_LISP ("ns-input-font", ns_input_font,
8203 "The font specified in the last NS event.");
8204 ns_input_font =Qnil;
8206 DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
8207 "The fontsize specified in the last NS event.");
8208 ns_input_fontsize =Qnil;
8210 DEFVAR_LISP ("ns-input-line", ns_input_line,
8211 "The line specified in the last NS event.");
8212 ns_input_line =Qnil;
8214 DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
8215 "The service name specified in the last NS event.");
8216 ns_input_spi_name =Qnil;
8218 DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
8219 "The service argument specified in the last NS event.");
8220 ns_input_spi_arg =Qnil;
8222 DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
8223 "This variable describes the behavior of the alternate or option key.\n\
8224 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8225 Set to none means that the alternate / option key is not interpreted by Emacs\n\
8226 at all, allowing it to be used at a lower level for accented character entry.");
8227 ns_alternate_modifier = Qmeta;
8229 DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
8230 "This variable describes the behavior of the right alternate or option key.\n\
8231 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8232 Set to left means be the same key as `ns-alternate-modifier'.\n\
8233 Set to none means that the alternate / option key is not interpreted by Emacs\n\
8234 at all, allowing it to be used at a lower level for accented character entry.");
8235 ns_right_alternate_modifier = Qleft;
8237 DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
8238 "This variable describes the behavior of the command key.\n\
8239 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
8240 ns_command_modifier = Qsuper;
8242 DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
8243 "This variable describes the behavior of the right command key.\n\
8244 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8245 Set to left means be the same key as `ns-command-modifier'.\n\
8246 Set to none means that the command / option key is not interpreted by Emacs\n\
8247 at all, allowing it to be used at a lower level for accented character entry.");
8248 ns_right_command_modifier = Qleft;
8250 DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
8251 "This variable describes the behavior of the control key.\n\
8252 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
8253 ns_control_modifier = Qcontrol;
8255 DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
8256 "This variable describes the behavior of the right control key.\n\
8257 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8258 Set to left means be the same key as `ns-control-modifier'.\n\
8259 Set to none means that the control / option key is not interpreted by Emacs\n\
8260 at all, allowing it to be used at a lower level for accented character entry.");
8261 ns_right_control_modifier = Qleft;
8263 DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
8264 "This variable describes the behavior of the function key (on laptops).\n\
8265 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8266 Set to none means that the function key is not interpreted by Emacs at all,\n\
8267 allowing it to be used at a lower level for accented character entry.");
8268 ns_function_modifier = Qnone;
8270 DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
8271 "Non-nil (the default) means to render text antialiased.");
8272 ns_antialias_text = Qt;
8274 DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
8275 "Whether to confirm application quit using dialog.");
8276 ns_confirm_quit = Qnil;
8278 DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
8279 doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
8280 Only works on OSX 10.6 or later. */);
8281 ns_auto_hide_menu_bar = Qnil;
8283 DEFVAR_BOOL ("ns-use-native-fullscreen", ns_use_native_fullscreen,
8284 doc: /*Non-nil means to use native fullscreen on OSX >= 10.7.
8285 Nil means use fullscreen the old (< 10.7) way. The old way works better with
8286 multiple monitors, but lacks tool bar. This variable is ignored on OSX < 10.7.
8287 Default is t for OSX >= 10.7, nil otherwise. */);
8288 #ifdef HAVE_NATIVE_FS
8289 ns_use_native_fullscreen = YES;
8291 ns_use_native_fullscreen = NO;
8293 ns_last_use_native_fullscreen = ns_use_native_fullscreen;
8295 DEFVAR_BOOL ("ns-use-fullscreen-animation", ns_use_fullscreen_animation,
8296 doc: /*Non-nil means use animation on non-native fullscreen.
8297 For native fullscreen, this does nothing.
8298 Default is nil. */);
8299 ns_use_fullscreen_animation = NO;
8301 DEFVAR_BOOL ("ns-use-srgb-colorspace", ns_use_srgb_colorspace,
8302 doc: /*Non-nil means to use sRGB colorspace on OSX >= 10.7.
8303 Note that this does not apply to images.
8304 This variable is ignored on OSX < 10.7 and GNUstep. */);
8305 ns_use_srgb_colorspace = YES;
8307 /* TODO: move to common code */
8308 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
8309 doc: /* Which toolkit scroll bars Emacs uses, if any.
8310 A value of nil means Emacs doesn't use toolkit scroll bars.
8311 With the X Window system, the value is a symbol describing the
8312 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
8313 With MS Windows or Nextstep, the value is t. */);
8314 Vx_toolkit_scroll_bars = Qt;
8316 DEFVAR_BOOL ("x-use-underline-position-properties",
8317 x_use_underline_position_properties,
8318 doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
8319 A value of nil means ignore them. If you encounter fonts with bogus
8320 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
8321 to 4.1, set this to nil. */);
8322 x_use_underline_position_properties = 0;
8324 DEFVAR_BOOL ("x-underline-at-descent-line",
8325 x_underline_at_descent_line,
8326 doc: /* Non-nil means to draw the underline at the same place as the descent line.
8327 A value of nil means to draw the underline according to the value of the
8328 variable `x-use-underline-position-properties', which is usually at the
8329 baseline level. The default value is nil. */);
8330 x_underline_at_descent_line = 0;
8332 /* Tell Emacs about this window system. */
8333 Fprovide (Qns, Qnil);
8335 DEFSYM (Qcocoa, "cocoa");
8336 DEFSYM (Qgnustep, "gnustep");
8338 #ifdef NS_IMPL_COCOA
8339 Fprovide (Qcocoa, Qnil);
8342 Fprovide (Qgnustep, Qnil);