1 /* NeXT/Open/GNUstep / MacOSX communication module. -*- coding: utf-8 -*-
3 Copyright (C) 1989, 1993-1994, 2005-2006, 2008-2016 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 (at
11 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;
75 /* ==========================================================================
77 NSTRACE, Trace support.
79 ========================================================================== */
83 /* The following use "volatile" since they can be accessed from
85 volatile int nstrace_num = 0;
86 volatile int nstrace_depth = 0;
88 /* When 0, no trace is emitted. This is used by NSTRACE_WHEN and
89 NSTRACE_UNLESS to silence functions called.
91 TODO: This should really be a thread-local variable, to avoid that
92 a function with disabled trace thread silence trace output in
93 another. However, in practice this seldom is a problem. */
94 volatile int nstrace_enabled_global = 1;
96 /* Called when nstrace_enabled goes out of scope. */
97 void nstrace_leave(int * pointer_to_nstrace_enabled)
99 if (*pointer_to_nstrace_enabled)
106 /* Called when nstrace_saved_enabled_global goes out of scope. */
107 void nstrace_restore_global_trace_state(int * pointer_to_saved_enabled_global)
109 nstrace_enabled_global = *pointer_to_saved_enabled_global;
113 char const * nstrace_fullscreen_type_name (int fs_type)
117 case -1: return "-1";
118 case FULLSCREEN_NONE: return "FULLSCREEN_NONE";
119 case FULLSCREEN_WIDTH: return "FULLSCREEN_WIDTH";
120 case FULLSCREEN_HEIGHT: return "FULLSCREEN_HEIGHT";
121 case FULLSCREEN_BOTH: return "FULLSCREEN_BOTH";
122 case FULLSCREEN_MAXIMIZED: return "FULLSCREEN_MAXIMIZED";
123 default: return "FULLSCREEN_?????";
129 /* ==========================================================================
131 NSColor, EmacsColor category.
133 ========================================================================== */
134 @implementation NSColor (EmacsColor)
135 + (NSColor *)colorForEmacsRed:(CGFloat)red green:(CGFloat)green
136 blue:(CGFloat)blue alpha:(CGFloat)alpha
139 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
140 if (ns_use_srgb_colorspace)
141 return [NSColor colorWithSRGBRed: red
147 return [NSColor colorWithCalibratedRed: red
153 - (NSColor *)colorUsingDefaultColorSpace
156 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
157 if (ns_use_srgb_colorspace)
158 return [self colorUsingColorSpace: [NSColorSpace sRGBColorSpace]];
161 return [self colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
166 /* ==========================================================================
170 ========================================================================== */
172 /* Convert a symbol indexed with an NSxxx value to a value as defined
173 in keyboard.c (lispy_function_key). I hope this is a correct way
174 of doing things... */
175 static unsigned convert_ns_to_X_keysym[] =
177 NSHomeFunctionKey, 0x50,
178 NSLeftArrowFunctionKey, 0x51,
179 NSUpArrowFunctionKey, 0x52,
180 NSRightArrowFunctionKey, 0x53,
181 NSDownArrowFunctionKey, 0x54,
182 NSPageUpFunctionKey, 0x55,
183 NSPageDownFunctionKey, 0x56,
184 NSEndFunctionKey, 0x57,
185 NSBeginFunctionKey, 0x58,
186 NSSelectFunctionKey, 0x60,
187 NSPrintFunctionKey, 0x61,
188 NSClearLineFunctionKey, 0x0B,
189 NSExecuteFunctionKey, 0x62,
190 NSInsertFunctionKey, 0x63,
191 NSUndoFunctionKey, 0x65,
192 NSRedoFunctionKey, 0x66,
193 NSMenuFunctionKey, 0x67,
194 NSFindFunctionKey, 0x68,
195 NSHelpFunctionKey, 0x6A,
196 NSBreakFunctionKey, 0x6B,
198 NSF1FunctionKey, 0xBE,
199 NSF2FunctionKey, 0xBF,
200 NSF3FunctionKey, 0xC0,
201 NSF4FunctionKey, 0xC1,
202 NSF5FunctionKey, 0xC2,
203 NSF6FunctionKey, 0xC3,
204 NSF7FunctionKey, 0xC4,
205 NSF8FunctionKey, 0xC5,
206 NSF9FunctionKey, 0xC6,
207 NSF10FunctionKey, 0xC7,
208 NSF11FunctionKey, 0xC8,
209 NSF12FunctionKey, 0xC9,
210 NSF13FunctionKey, 0xCA,
211 NSF14FunctionKey, 0xCB,
212 NSF15FunctionKey, 0xCC,
213 NSF16FunctionKey, 0xCD,
214 NSF17FunctionKey, 0xCE,
215 NSF18FunctionKey, 0xCF,
216 NSF19FunctionKey, 0xD0,
217 NSF20FunctionKey, 0xD1,
218 NSF21FunctionKey, 0xD2,
219 NSF22FunctionKey, 0xD3,
220 NSF23FunctionKey, 0xD4,
221 NSF24FunctionKey, 0xD5,
223 NSBackspaceCharacter, 0x08, /* 8: Not on some KBs. */
224 NSDeleteCharacter, 0xFF, /* 127: Big 'delete' key upper right. */
225 NSDeleteFunctionKey, 0x9F, /* 63272: Del forw key off main array. */
227 NSTabCharacter, 0x09,
228 0x19, 0x09, /* left tab->regular since pass shift */
229 NSCarriageReturnCharacter, 0x0D,
230 NSNewlineCharacter, 0x0D,
231 NSEnterCharacter, 0x8D,
233 0x41|NSEventModifierFlagNumericPad, 0xAE, /* KP_Decimal */
234 0x43|NSEventModifierFlagNumericPad, 0xAA, /* KP_Multiply */
235 0x45|NSEventModifierFlagNumericPad, 0xAB, /* KP_Add */
236 0x4B|NSEventModifierFlagNumericPad, 0xAF, /* KP_Divide */
237 0x4E|NSEventModifierFlagNumericPad, 0xAD, /* KP_Subtract */
238 0x51|NSEventModifierFlagNumericPad, 0xBD, /* KP_Equal */
239 0x52|NSEventModifierFlagNumericPad, 0xB0, /* KP_0 */
240 0x53|NSEventModifierFlagNumericPad, 0xB1, /* KP_1 */
241 0x54|NSEventModifierFlagNumericPad, 0xB2, /* KP_2 */
242 0x55|NSEventModifierFlagNumericPad, 0xB3, /* KP_3 */
243 0x56|NSEventModifierFlagNumericPad, 0xB4, /* KP_4 */
244 0x57|NSEventModifierFlagNumericPad, 0xB5, /* KP_5 */
245 0x58|NSEventModifierFlagNumericPad, 0xB6, /* KP_6 */
246 0x59|NSEventModifierFlagNumericPad, 0xB7, /* KP_7 */
247 0x5B|NSEventModifierFlagNumericPad, 0xB8, /* KP_8 */
248 0x5C|NSEventModifierFlagNumericPad, 0xB9, /* KP_9 */
250 0x1B, 0x1B /* escape */
253 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
254 the maximum font size to NOT antialias. On GNUstep there is currently
255 no way to control this behavior. */
256 float ns_antialias_threshold;
258 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
259 NSString *ns_app_name = @"Emacs"; /* default changed later */
261 /* Display variables */
262 struct ns_display_info *x_display_list; /* Chain of existing displays */
263 long context_menu_value = 0;
266 static struct frame *ns_updating_frame;
267 static NSView *focus_view = NULL;
268 static int ns_window_num = 0;
269 #ifdef NS_IMPL_GNUSTEP
270 static NSRect uRect; // TODO: This is dead, remove it?
272 static BOOL gsaved = NO;
273 static BOOL ns_fake_keydown = NO;
275 static BOOL ns_menu_bar_is_hidden = NO;
277 /*static int debug_lock = 0; */
280 static BOOL send_appdefined = YES;
281 #define NO_APPDEFINED_DATA (-8)
282 static int last_appdefined_event_data = NO_APPDEFINED_DATA;
283 static NSTimer *timed_entry = 0;
284 static NSTimer *scroll_repeat_entry = nil;
285 static fd_set select_readfds, select_writefds;
286 enum { SELECT_HAVE_READ = 1, SELECT_HAVE_WRITE = 2, SELECT_HAVE_TMO = 4 };
287 static int select_nfds = 0, select_valid = 0;
288 static struct timespec select_timeout = { 0, 0 };
289 static int selfds[2] = { -1, -1 };
290 static pthread_mutex_t select_mutex;
291 static int apploopnr = 0;
292 static NSAutoreleasePool *outerpool;
293 static struct input_event *emacs_event = NULL;
294 static struct input_event *q_event_ptr = NULL;
295 static int n_emacs_events_pending = 0;
296 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
297 *ns_pending_service_args;
298 static BOOL ns_do_open_file = NO;
299 static BOOL ns_last_use_native_fullscreen;
301 /* Non-zero means that a HELP_EVENT has been generated since Emacs
304 static BOOL any_help_event_p = NO;
307 struct input_event *q;
313 static NSString *represented_filename = nil;
314 static struct frame *represented_frame = 0;
318 * State for pending menu activation:
319 * MENU_NONE Normal state
320 * MENU_PENDING A menu has been clicked on, but has been canceled so we can
321 * run lisp to update the menu.
322 * MENU_OPENING Menu is up to date, and the click event is redone so the menu
326 #define MENU_PENDING 1
327 #define MENU_OPENING 2
328 static int menu_will_open_state = MENU_NONE;
330 /* Saved position for menu click. */
331 static CGPoint menu_mouse_point;
334 /* Convert modifiers in a NeXTstep event to emacs style modifiers. */
335 #define NS_FUNCTION_KEY_MASK 0x800000
336 #define NSLeftControlKeyMask (0x000001 | NSEventModifierFlagControl)
337 #define NSRightControlKeyMask (0x002000 | NSEventModifierFlagControl)
338 #define NSLeftCommandKeyMask (0x000008 | NSEventModifierFlagCommand)
339 #define NSRightCommandKeyMask (0x000010 | NSEventModifierFlagCommand)
340 #define NSLeftAlternateKeyMask (0x000020 | NSEventModifierFlagOption)
341 #define NSRightAlternateKeyMask (0x000040 | NSEventModifierFlagOption)
342 #define EV_MODIFIERS2(flags) \
343 (((flags & NSEventModifierFlagHelp) ? \
344 hyper_modifier : 0) \
345 | (!EQ (ns_right_alternate_modifier, Qleft) && \
346 ((flags & NSRightAlternateKeyMask) \
347 == NSRightAlternateKeyMask) ? \
348 parse_solitary_modifier (ns_right_alternate_modifier) : 0) \
349 | ((flags & NSEventModifierFlagOption) ? \
350 parse_solitary_modifier (ns_alternate_modifier) : 0) \
351 | ((flags & NSEventModifierFlagShift) ? \
352 shift_modifier : 0) \
353 | (!EQ (ns_right_control_modifier, Qleft) && \
354 ((flags & NSRightControlKeyMask) \
355 == NSRightControlKeyMask) ? \
356 parse_solitary_modifier (ns_right_control_modifier) : 0) \
357 | ((flags & NSEventModifierFlagControl) ? \
358 parse_solitary_modifier (ns_control_modifier) : 0) \
359 | ((flags & NS_FUNCTION_KEY_MASK) ? \
360 parse_solitary_modifier (ns_function_modifier) : 0) \
361 | (!EQ (ns_right_command_modifier, Qleft) && \
362 ((flags & NSRightCommandKeyMask) \
363 == NSRightCommandKeyMask) ? \
364 parse_solitary_modifier (ns_right_command_modifier) : 0) \
365 | ((flags & NSEventModifierFlagCommand) ? \
366 parse_solitary_modifier (ns_command_modifier):0))
367 #define EV_MODIFIERS(e) EV_MODIFIERS2 ([e modifierFlags])
369 #define EV_UDMODIFIERS(e) \
370 ((([e type] == NSEventTypeLeftMouseDown) ? down_modifier : 0) \
371 | (([e type] == NSEventTypeRightMouseDown) ? down_modifier : 0) \
372 | (([e type] == NSEventTypeOtherMouseDown) ? down_modifier : 0) \
373 | (([e type] == NSEventTypeLeftMouseDragged) ? down_modifier : 0) \
374 | (([e type] == NSEventTypeRightMouseDragged) ? down_modifier : 0) \
375 | (([e type] == NSEventTypeOtherMouseDragged) ? down_modifier : 0) \
376 | (([e type] == NSEventTypeLeftMouseUp) ? up_modifier : 0) \
377 | (([e type] == NSEventTypeRightMouseUp) ? up_modifier : 0) \
378 | (([e type] == NSEventTypeOtherMouseUp) ? up_modifier : 0))
380 #define EV_BUTTON(e) \
381 ((([e type] == NSEventTypeLeftMouseDown) || ([e type] == NSEventTypeLeftMouseUp)) ? 0 : \
382 (([e type] == NSEventTypeRightMouseDown) || ([e type] == NSEventTypeRightMouseUp)) ? 2 : \
383 [e buttonNumber] - 1)
385 /* Convert the time field to a timestamp in milliseconds. */
386 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
388 /* This is a piece of code which is common to all the event handling
389 methods. Maybe it should even be a function. */
390 #define EV_TRAILER(e) \
392 XSETFRAME (emacs_event->frame_or_window, emacsframe); \
396 #define EV_TRAILER2(e) \
398 if (e) emacs_event->timestamp = EV_TIMESTAMP (e); \
401 Lisp_Object tem = Vinhibit_quit; \
402 Vinhibit_quit = Qt; \
403 n_emacs_events_pending++; \
404 kbd_buffer_store_event_hold (emacs_event, q_event_ptr); \
405 Vinhibit_quit = tem; \
408 hold_event (emacs_event); \
409 EVENT_INIT (*emacs_event); \
410 ns_send_appdefined (-1); \
413 /* TODO: get rid of need for these forward declarations */
414 static void ns_condemn_scroll_bars (struct frame *f);
415 static void ns_judge_scroll_bars (struct frame *f);
416 void x_set_frame_alpha (struct frame *f);
419 /* ==========================================================================
423 ========================================================================== */
426 ns_set_represented_filename (NSString* fstr, struct frame *f)
428 represented_filename = [fstr retain];
429 represented_frame = f;
433 ns_init_events (struct input_event* ev)
446 hold_event (struct input_event *event)
448 if (hold_event_q.nr == hold_event_q.cap)
450 if (hold_event_q.cap == 0) hold_event_q.cap = 10;
451 else hold_event_q.cap *= 2;
453 xrealloc (hold_event_q.q, hold_event_q.cap * sizeof *hold_event_q.q);
456 hold_event_q.q[hold_event_q.nr++] = *event;
457 /* Make sure ns_read_socket is called, i.e. we have input. */
459 send_appdefined = YES;
463 append2 (Lisp_Object list, Lisp_Object item)
464 /* --------------------------------------------------------------------------
465 Utility to append to a list
466 -------------------------------------------------------------------------- */
468 return CALLN (Fnconc, list, list1 (item));
473 ns_etc_directory (void)
474 /* If running as a self-contained app bundle, return as a string the
475 filename of the etc directory, if present; else nil. */
477 NSBundle *bundle = [NSBundle mainBundle];
478 NSString *resourceDir = [bundle resourcePath];
479 NSString *resourcePath;
480 NSFileManager *fileManager = [NSFileManager defaultManager];
483 resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
484 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
486 if (isDir) return [resourcePath UTF8String];
494 /* If running as a self-contained app bundle, return as a path string
495 the filenames of the libexec and bin directories, ie libexec:bin.
496 Otherwise, return nil.
497 Normally, Emacs does not add its own bin/ directory to the PATH.
498 However, a self-contained NS build has a different layout, with
499 bin/ and libexec/ subdirectories in the directory that contains
501 We put libexec first, because init_callproc_1 uses the first
502 element to initialize exec-directory. An alternative would be
503 for init_callproc to check for invocation-directory/libexec.
506 NSBundle *bundle = [NSBundle mainBundle];
507 NSString *resourceDir = [bundle resourcePath];
508 NSString *binDir = [bundle bundlePath];
509 NSString *resourcePath, *resourcePaths;
511 NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
512 NSFileManager *fileManager = [NSFileManager defaultManager];
514 NSEnumerator *pathEnum;
517 range = [resourceDir rangeOfString: @"Contents"];
518 if (range.location != NSNotFound)
520 binDir = [binDir stringByAppendingPathComponent: @"Contents"];
522 binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
526 paths = [binDir stringsByAppendingPaths:
527 [NSArray arrayWithObjects: @"libexec", @"bin", nil]];
528 pathEnum = [paths objectEnumerator];
531 while ((resourcePath = [pathEnum nextObject]))
533 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
536 if ([resourcePaths length] > 0)
538 = [resourcePaths stringByAppendingString: pathSeparator];
540 = [resourcePaths stringByAppendingString: resourcePath];
543 if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
551 /* If running as a self-contained app bundle, return as a path string
552 the filenames of the site-lisp and lisp directories.
553 Ie, site-lisp:lisp. Otherwise, return nil. */
555 NSBundle *bundle = [NSBundle mainBundle];
556 NSString *resourceDir = [bundle resourcePath];
557 NSString *resourcePath, *resourcePaths;
558 NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
559 NSFileManager *fileManager = [NSFileManager defaultManager];
561 NSArray *paths = [resourceDir stringsByAppendingPaths:
562 [NSArray arrayWithObjects:
563 @"site-lisp", @"lisp", nil]];
564 NSEnumerator *pathEnum = [paths objectEnumerator];
567 /* Hack to skip site-lisp. */
568 if (no_site_lisp) resourcePath = [pathEnum nextObject];
570 while ((resourcePath = [pathEnum nextObject]))
572 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
575 if ([resourcePaths length] > 0)
577 = [resourcePaths stringByAppendingString: pathSeparator];
579 = [resourcePaths stringByAppendingString: resourcePath];
582 if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
589 ns_init_locale (void)
590 /* OS X doesn't set any environment variables for the locale when run
591 from the GUI. Get the locale from the OS and set LANG. */
593 NSLocale *locale = [NSLocale currentLocale];
595 NSTRACE ("ns_init_locale");
599 /* It seems OS X should probably use UTF-8 everywhere.
600 'localeIdentifier' does not specify the encoding, and I can't
601 find any way to get the OS to tell us which encoding to use,
602 so hard-code '.UTF-8'. */
603 NSString *localeID = [NSString stringWithFormat:@"%@.UTF-8",
604 [locale localeIdentifier]];
606 /* Set LANG to locale, but not if LANG is already set. */
607 setenv("LANG", [localeID UTF8String], 0);
609 @catch (NSException *e)
611 NSLog (@"Locale detection failed: %@: %@", [e name], [e reason]);
617 ns_release_object (void *obj)
618 /* --------------------------------------------------------------------------
619 Release an object (callable from C)
620 -------------------------------------------------------------------------- */
627 ns_retain_object (void *obj)
628 /* --------------------------------------------------------------------------
629 Retain an object (callable from C)
630 -------------------------------------------------------------------------- */
637 ns_alloc_autorelease_pool (void)
638 /* --------------------------------------------------------------------------
639 Allocate a pool for temporary objects (callable from C)
640 -------------------------------------------------------------------------- */
642 return [[NSAutoreleasePool alloc] init];
647 ns_release_autorelease_pool (void *pool)
648 /* --------------------------------------------------------------------------
649 Free a pool and temporary objects it refers to (callable from C)
650 -------------------------------------------------------------------------- */
652 ns_release_object (pool);
657 ns_menu_bar_should_be_hidden (void)
658 /* True, if the menu bar should be hidden. */
660 return !NILP (ns_auto_hide_menu_bar)
661 && [NSApp respondsToSelector:@selector(setPresentationOptions:)];
674 static struct EmacsMargins
675 ns_screen_margins (NSScreen *screen)
676 /* The parts of SCREEN used by the operating system. */
678 NSTRACE ("ns_screen_margins");
680 struct EmacsMargins margins;
682 NSRect screenFrame = [screen frame];
683 NSRect screenVisibleFrame = [screen visibleFrame];
685 /* Sometimes, visibleFrame isn't up-to-date with respect to a hidden
686 menu bar, check this explicitly. */
687 if (ns_menu_bar_should_be_hidden())
693 CGFloat frameTop = screenFrame.origin.y + screenFrame.size.height;
694 CGFloat visibleFrameTop = (screenVisibleFrame.origin.y
695 + screenVisibleFrame.size.height);
697 margins.top = frameTop - visibleFrameTop;
701 CGFloat frameRight = screenFrame.origin.x + screenFrame.size.width;
702 CGFloat visibleFrameRight = (screenVisibleFrame.origin.x
703 + screenVisibleFrame.size.width);
704 margins.right = frameRight - visibleFrameRight;
707 margins.bottom = screenVisibleFrame.origin.y - screenFrame.origin.y;
708 margins.left = screenVisibleFrame.origin.x - screenFrame.origin.x;
710 NSTRACE_MSG ("left:%g right:%g top:%g bottom:%g",
720 /* A screen margin between 1 and DOCK_IGNORE_LIMIT (inclusive) is
721 assumed to contain a hidden dock. OS X currently use 4 pixels for
722 this, however, to be future compatible, a larger value is used. */
723 #define DOCK_IGNORE_LIMIT 6
725 static struct EmacsMargins
726 ns_screen_margins_ignoring_hidden_dock (NSScreen *screen)
727 /* The parts of SCREEN used by the operating system, excluding the parts
728 reserved for an hidden dock. */
730 NSTRACE ("ns_screen_margins_ignoring_hidden_dock");
732 struct EmacsMargins margins = ns_screen_margins(screen);
734 /* OS X (currently) reserved 4 pixels along the edge where a hidden
735 dock is located. Unfortunately, it's not possible to find the
736 location and information about if the dock is hidden. Instead,
737 it is assumed that if the margin of an edge is less than
738 DOCK_IGNORE_LIMIT, it contains a hidden dock. */
739 if (margins.left <= DOCK_IGNORE_LIMIT)
743 if (margins.right <= DOCK_IGNORE_LIMIT)
747 if (margins.top <= DOCK_IGNORE_LIMIT)
751 /* Note: This doesn't occur in current versions of OS X, but
752 included for completeness and future compatibility. */
753 if (margins.bottom <= DOCK_IGNORE_LIMIT)
758 NSTRACE_MSG ("left:%g right:%g top:%g bottom:%g",
769 ns_menu_bar_height (NSScreen *screen)
770 /* The height of the menu bar, if visible.
772 Note: Don't use this when fullscreen is enabled -- the screen
773 sometimes includes, sometimes excludes the menu bar area. */
775 struct EmacsMargins margins = ns_screen_margins(screen);
777 CGFloat res = margins.top;
779 NSTRACE ("ns_menu_bar_height " NSTRACE_FMT_RETURN " %.0f", res);
785 /* ==========================================================================
787 Focus (clipping) and screen update
789 ========================================================================== */
792 // Window constraining
793 // -------------------
795 // To ensure that the windows are not placed under the menu bar, they
796 // are typically moved by the call-back constrainFrameRect. However,
797 // by overriding it, it's possible to inhibit this, leaving the window
798 // in it's original position.
800 // It's possible to hide the menu bar. However, technically, it's only
801 // possible to hide it when the application is active. To ensure that
802 // this work properly, the menu bar and window constraining are
803 // deferred until the application becomes active.
805 // Even though it's not possible to manually move a window above the
806 // top of the screen, it is allowed if it's done programmatically,
807 // when the menu is hidden. This allows the editable area to cover the
808 // full screen height.
813 // Use the following extra files:
816 // ;; Hide menu and place frame slightly above the top of the screen.
817 // (setq ns-auto-hide-menu-bar t)
818 // (set-frame-position (selected-frame) 0 -20)
822 // emacs -Q -l init.el
824 // Result: No menu bar, and the title bar should be above the screen.
830 // Result: Menu bar visible, frame placed immediately below the menu.
833 static NSRect constrain_frame_rect(NSRect frameRect, bool isFullscreen)
835 NSTRACE ("constrain_frame_rect(" NSTRACE_FMT_RECT ")",
836 NSTRACE_ARG_RECT (frameRect));
838 // --------------------
839 // Collect information about the screen the frame is covering.
842 NSArray *screens = [NSScreen screens];
843 NSUInteger nr_screens = [screens count];
847 // The height of the menu bar, if present in any screen the frame is
849 int menu_bar_height = 0;
851 // A rectangle covering all the screen the frame is displayed in.
852 NSRect multiscreenRect = NSMakeRect(0, 0, 0, 0);
853 for (i = 0; i < nr_screens; ++i )
855 NSScreen *s = [screens objectAtIndex: i];
856 NSRect scrRect = [s frame];
858 NSTRACE_MSG ("Screen %d: " NSTRACE_FMT_RECT,
859 i, NSTRACE_ARG_RECT (scrRect));
861 if (NSIntersectionRect (frameRect, scrRect).size.height != 0)
863 multiscreenRect = NSUnionRect (multiscreenRect, scrRect);
867 CGFloat screen_menu_bar_height = ns_menu_bar_height (s);
868 menu_bar_height = max(menu_bar_height, screen_menu_bar_height);
873 NSTRACE_RECT ("multiscreenRect", multiscreenRect);
875 NSTRACE_MSG ("menu_bar_height: %d", menu_bar_height);
877 if (multiscreenRect.size.width == 0
878 || multiscreenRect.size.height == 0)
880 // Failed to find any monitor, give up.
881 NSTRACE_MSG ("multiscreenRect empty");
882 NSTRACE_RETURN_RECT (frameRect);
887 // --------------------
888 // Find a suitable placement.
891 if (ns_menu_bar_should_be_hidden())
893 // When the menu bar is hidden, the user may place part of the
894 // frame above the top of the screen, for example to hide the
897 // Hence, keep the original position.
901 // Ensure that the frame is below the menu bar, or below the top
904 // This assume that the menu bar is placed at the top in the
905 // rectangle that covers the monitors. (It doesn't have to be,
906 // but if it's not it's hard to do anything useful.)
907 CGFloat topOfWorkArea = (multiscreenRect.origin.y
908 + multiscreenRect.size.height
911 CGFloat topOfFrame = frameRect.origin.y + frameRect.size.height;
912 if (topOfFrame > topOfWorkArea)
914 frameRect.origin.y -= topOfFrame - topOfWorkArea;
915 NSTRACE_RECT ("After placement adjust", frameRect);
919 // Include the following section to restrict frame to the screens.
920 // (If so, update it to allow the frame to stretch down below the
923 // --------------------
924 // Ensure frame doesn't stretch below the screens.
927 CGFloat diff = multiscreenRect.origin.y - frameRect.origin.y;
931 frameRect.origin.y = multiscreenRect.origin.y;
932 frameRect.size.height -= diff;
936 NSTRACE_RETURN_RECT (frameRect);
942 ns_constrain_all_frames (void)
943 /* --------------------------------------------------------------------------
944 Ensure that the menu bar doesn't cover any frames.
945 -------------------------------------------------------------------------- */
947 Lisp_Object tail, frame;
949 NSTRACE ("ns_constrain_all_frames");
953 FOR_EACH_FRAME (tail, frame)
955 struct frame *f = XFRAME (frame);
958 EmacsView *view = FRAME_NS_VIEW (f);
960 if (![view isFullscreen])
963 setFrame:constrain_frame_rect([[view window] frame], false)
974 ns_update_auto_hide_menu_bar (void)
975 /* --------------------------------------------------------------------------
976 Show or hide the menu bar, based on user setting.
977 -------------------------------------------------------------------------- */
980 NSTRACE ("ns_update_auto_hide_menu_bar");
984 if (NSApp != nil && [NSApp isActive])
986 // Note, "setPresentationOptions" triggers an error unless the
987 // application is active.
988 BOOL menu_bar_should_be_hidden = ns_menu_bar_should_be_hidden ();
990 if (menu_bar_should_be_hidden != ns_menu_bar_is_hidden)
992 NSApplicationPresentationOptions options
993 = NSApplicationPresentationDefault;
995 if (menu_bar_should_be_hidden)
996 options |= NSApplicationPresentationAutoHideMenuBar
997 | NSApplicationPresentationAutoHideDock;
999 [NSApp setPresentationOptions: options];
1001 ns_menu_bar_is_hidden = menu_bar_should_be_hidden;
1003 if (!ns_menu_bar_is_hidden)
1005 ns_constrain_all_frames ();
1016 ns_update_begin (struct frame *f)
1017 /* --------------------------------------------------------------------------
1018 Prepare for a grouped sequence of drawing calls
1019 external (RIF) call; whole frame, called before update_window_begin
1020 -------------------------------------------------------------------------- */
1022 EmacsView *view = FRAME_NS_VIEW (f);
1023 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_begin");
1025 ns_update_auto_hide_menu_bar ();
1027 #ifdef NS_IMPL_COCOA
1028 if ([view isFullscreen] && [view fsIsNative])
1030 // Fix reappearing tool bar in fullscreen for OSX 10.7
1031 BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (f) ? YES : NO;
1032 NSToolbar *toolbar = [FRAME_NS_VIEW (f) toolbar];
1033 if (! tbar_visible != ! [toolbar isVisible])
1034 [toolbar setVisible: tbar_visible];
1038 ns_updating_frame = f;
1041 /* drawRect may have been called for say the minibuffer, and then clip path
1042 is for the minibuffer. But the display engine may draw more because
1043 we have set the frame as garbaged. So reset clip path to the whole
1045 #ifdef NS_IMPL_COCOA
1048 NSRect r = [view frame];
1049 NSRect cr = [[view window] frame];
1050 /* If a large frame size is set, r may be larger than the window frame
1051 before constrained. In that case don't change the clip path, as we
1052 will clear in to the tool bar and title bar. */
1054 + FRAME_NS_TITLEBAR_HEIGHT (f)
1055 + FRAME_TOOLBAR_HEIGHT (f) <= cr.size.height)
1057 bp = [[NSBezierPath bezierPathWithRect: r] retain];
1064 #ifdef NS_IMPL_GNUSTEP
1065 uRect = NSMakeRect (0, 0, 0, 0);
1071 ns_update_window_begin (struct window *w)
1072 /* --------------------------------------------------------------------------
1073 Prepare for a grouped sequence of drawing calls
1074 external (RIF) call; for one window, called after update_begin
1075 -------------------------------------------------------------------------- */
1077 struct frame *f = XFRAME (WINDOW_FRAME (w));
1078 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1080 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_window_begin");
1081 w->output_cursor = w->cursor;
1085 if (f == hlinfo->mouse_face_mouse_frame)
1087 /* Don't do highlighting for mouse motion during the update. */
1088 hlinfo->mouse_face_defer = 1;
1090 /* If the frame needs to be redrawn,
1091 simply forget about any prior mouse highlighting. */
1092 if (FRAME_GARBAGED_P (f))
1093 hlinfo->mouse_face_window = Qnil;
1095 /* (further code for mouse faces ifdef'd out in other terms elided) */
1103 ns_update_window_end (struct window *w, bool cursor_on_p,
1104 bool mouse_face_overwritten_p)
1105 /* --------------------------------------------------------------------------
1106 Finished a grouped sequence of drawing calls
1107 external (RIF) call; for one window called before update_end
1108 -------------------------------------------------------------------------- */
1110 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_window_end");
1112 /* note: this fn is nearly identical in all terms */
1113 if (!w->pseudo_window_p)
1118 display_and_set_cursor (w, 1,
1119 w->output_cursor.hpos, w->output_cursor.vpos,
1120 w->output_cursor.x, w->output_cursor.y);
1122 if (draw_window_fringes (w, 1))
1124 if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
1125 x_draw_right_divider (w);
1127 x_draw_vertical_border (w);
1133 /* If a row with mouse-face was overwritten, arrange for
1134 frame_up_to_date to redisplay the mouse highlight. */
1135 if (mouse_face_overwritten_p)
1136 reset_mouse_highlight (MOUSE_HL_INFO (XFRAME (w->frame)));
1141 ns_update_end (struct frame *f)
1142 /* --------------------------------------------------------------------------
1143 Finished a grouped sequence of drawing calls
1144 external (RIF) call; for whole frame, called after update_window_end
1145 -------------------------------------------------------------------------- */
1147 EmacsView *view = FRAME_NS_VIEW (f);
1149 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_end");
1151 /* if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
1152 MOUSE_HL_INFO (f)->mouse_face_defer = 0;
1157 [[view window] flushWindow];
1160 ns_updating_frame = NULL;
1164 ns_focus (struct frame *f, NSRect *r, int n)
1165 /* --------------------------------------------------------------------------
1166 Internal: Focus on given frame. During small local updates this is used to
1167 draw, however during large updates, ns_update_begin and ns_update_end are
1168 called to wrap the whole thing, in which case these calls are stubbed out.
1169 Except, on GNUstep, we accumulate the rectangle being drawn into, because
1170 the back end won't do this automatically, and will just end up flushing
1172 -------------------------------------------------------------------------- */
1174 NSTRACE_WHEN (NSTRACE_GROUP_FOCUS, "ns_focus");
1177 NSTRACE_RECT ("r", *r);
1180 if (f != ns_updating_frame)
1182 NSView *view = FRAME_NS_VIEW (f);
1183 if (view != focus_view)
1185 if (focus_view != NULL)
1187 [focus_view unlockFocus];
1188 [[focus_view window] flushWindow];
1195 /*if (view) debug_lock++; */
1202 [[NSGraphicsContext currentContext] saveGraphicsState];
1204 NSRectClipList (r, 2);
1213 ns_unfocus (struct frame *f)
1214 /* --------------------------------------------------------------------------
1215 Internal: Remove focus on given frame
1216 -------------------------------------------------------------------------- */
1218 NSTRACE_WHEN (NSTRACE_GROUP_FOCUS, "ns_unfocus");
1222 [[NSGraphicsContext currentContext] restoreGraphicsState];
1226 if (f != ns_updating_frame)
1228 if (focus_view != NULL)
1230 [focus_view unlockFocus];
1231 [[focus_view window] flushWindow];
1240 ns_clip_to_row (struct window *w, struct glyph_row *row,
1241 enum glyph_row_area area, BOOL gc)
1242 /* --------------------------------------------------------------------------
1243 Internal (but parallels other terms): Focus drawing on given row
1244 -------------------------------------------------------------------------- */
1246 struct frame *f = XFRAME (WINDOW_FRAME (w));
1248 int window_x, window_y, window_width;
1250 window_box (w, area, &window_x, &window_y, &window_width, 0);
1252 clip_rect.origin.x = window_x;
1253 clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
1254 clip_rect.origin.y = max (clip_rect.origin.y, window_y);
1255 clip_rect.size.width = window_width;
1256 clip_rect.size.height = row->visible_height;
1258 ns_focus (f, &clip_rect, 1);
1262 /* ==========================================================================
1264 Visible bell and beep.
1266 ========================================================================== */
1269 // This bell implementation shows the visual bell image asynchronously
1270 // from the rest of Emacs. This is done by adding a NSView to the
1271 // superview of the Emacs window and removing it using a timer.
1273 // Unfortunately, some Emacs operations, like scrolling, is done using
1274 // low-level primitives that copy the content of the window, including
1275 // the bell image. To some extent, this is handled by removing the
1276 // image prior to scrolling and marking that the window is in need for
1279 // To test this code, make sure that there is no artifacts of the bell
1280 // image in the following situations. Use a non-empty buffer (like the
1281 // tutorial) to ensure that a scroll is performed:
1283 // * Single-window: C-g C-v
1285 // * Side-by-windows: C-x 3 C-g C-v
1287 // * Windows above each other: C-x 2 C-g C-v
1289 @interface EmacsBell : NSImageView
1291 // Number of currently active bell:s.
1292 unsigned int nestCount;
1296 - (void)show:(NSView *)view;
1301 @implementation EmacsBell
1305 NSTRACE ("[EmacsBell init]");
1306 if ((self = [super init]))
1310 #ifdef NS_IMPL_GNUSTEP
1311 // GNUstep doesn't provide named images. This was reported in
1312 // 2011, see https://savannah.gnu.org/bugs/?33396
1314 // As a drop in replacement, a semitransparent gray square is used.
1315 self.image = [[NSImage alloc] initWithSize:NSMakeSize(32 * 5, 32 * 5)];
1316 [self.image lockFocus];
1317 [[NSColor colorForEmacsRed:0.5 green:0.5 blue:0.5 alpha:0.5] set];
1318 NSRectFill(NSMakeRect(0, 0, 32, 32));
1319 [self.image unlockFocus];
1321 self.image = [NSImage imageNamed:NSImageNameCaution];
1322 [self.image setSize:NSMakeSize(self.image.size.width * 5,
1323 self.image.size.height * 5)];
1329 - (void)show:(NSView *)view
1331 NSTRACE ("[EmacsBell show:]");
1332 NSTRACE_MSG ("nestCount: %u", nestCount);
1334 // Show the image, unless it's already shown.
1337 NSRect rect = [view bounds];
1339 pos.x = rect.origin.x + (rect.size.width - self.image.size.width )/2;
1340 pos.y = rect.origin.y + (rect.size.height - self.image.size.height)/2;
1342 [self setFrameOrigin:pos];
1343 [self setFrameSize:self.image.size];
1347 [[[view window] contentView] addSubview:self
1348 positioned:NSWindowAbove
1354 [self performSelector:@selector(hide) withObject:self afterDelay:0.5];
1360 // Note: Trace output from this method isn't shown, reason unknown.
1361 // NSTRACE ("[EmacsBell hide]");
1366 // Remove the image once the last bell became inactive.
1376 NSTRACE ("[EmacsBell remove]");
1379 NSTRACE_MSG ("removeFromSuperview");
1380 [self removeFromSuperview];
1381 mView.needsDisplay = YES;
1389 static EmacsBell * bell_view = nil;
1392 ns_ring_bell (struct frame *f)
1393 /* --------------------------------------------------------------------------
1395 -------------------------------------------------------------------------- */
1397 NSTRACE ("ns_ring_bell");
1400 struct frame *frame = SELECTED_FRAME ();
1403 if (bell_view == nil)
1405 bell_view = [[EmacsBell alloc] init];
1411 view = FRAME_NS_VIEW (frame);
1414 [bell_view show:view];
1426 static void hide_bell ()
1427 /* --------------------------------------------------------------------------
1428 Ensure the bell is hidden.
1429 -------------------------------------------------------------------------- */
1431 NSTRACE ("hide_bell");
1433 if (bell_view != nil)
1440 /* ==========================================================================
1442 Frame / window manager related functions
1444 ========================================================================== */
1448 ns_raise_frame (struct frame *f)
1449 /* --------------------------------------------------------------------------
1450 Bring window to foreground and make it active
1451 -------------------------------------------------------------------------- */
1455 check_window_system (f);
1456 view = FRAME_NS_VIEW (f);
1458 if (FRAME_VISIBLE_P (f))
1459 [[view window] makeKeyAndOrderFront: NSApp];
1465 ns_lower_frame (struct frame *f)
1466 /* --------------------------------------------------------------------------
1468 -------------------------------------------------------------------------- */
1472 check_window_system (f);
1473 view = FRAME_NS_VIEW (f);
1475 [[view window] orderBack: NSApp];
1481 ns_frame_raise_lower (struct frame *f, bool raise)
1482 /* --------------------------------------------------------------------------
1484 -------------------------------------------------------------------------- */
1486 NSTRACE ("ns_frame_raise_lower");
1496 ns_frame_rehighlight (struct frame *frame)
1497 /* --------------------------------------------------------------------------
1498 External (hook): called on things like window switching within frame
1499 -------------------------------------------------------------------------- */
1501 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
1502 struct frame *old_highlight = dpyinfo->x_highlight_frame;
1504 NSTRACE ("ns_frame_rehighlight");
1505 if (dpyinfo->x_focus_frame)
1507 dpyinfo->x_highlight_frame
1508 = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1509 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1510 : dpyinfo->x_focus_frame);
1511 if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
1513 fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
1514 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
1518 dpyinfo->x_highlight_frame = 0;
1520 if (dpyinfo->x_highlight_frame &&
1521 dpyinfo->x_highlight_frame != old_highlight)
1525 x_update_cursor (old_highlight, 1);
1526 x_set_frame_alpha (old_highlight);
1528 if (dpyinfo->x_highlight_frame)
1530 x_update_cursor (dpyinfo->x_highlight_frame, 1);
1531 x_set_frame_alpha (dpyinfo->x_highlight_frame);
1538 x_make_frame_visible (struct frame *f)
1539 /* --------------------------------------------------------------------------
1540 External: Show the window (X11 semantics)
1541 -------------------------------------------------------------------------- */
1543 NSTRACE ("x_make_frame_visible");
1544 /* XXX: at some points in past this was not needed, as the only place that
1545 called this (frame.c:Fraise_frame ()) also called raise_lower;
1546 if this ends up the case again, comment this out again. */
1547 if (!FRAME_VISIBLE_P (f))
1549 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1551 SET_FRAME_VISIBLE (f, 1);
1554 /* Making a new frame from a fullscreen frame will make the new frame
1555 fullscreen also. So skip handleFS as this will print an error. */
1556 if ([view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH
1557 && [view isFullscreen])
1560 if (f->want_fullscreen != FULLSCREEN_NONE)
1571 x_make_frame_invisible (struct frame *f)
1572 /* --------------------------------------------------------------------------
1573 External: Hide the window (X11 semantics)
1574 -------------------------------------------------------------------------- */
1577 NSTRACE ("x_make_frame_invisible");
1578 check_window_system (f);
1579 view = FRAME_NS_VIEW (f);
1580 [[view window] orderOut: NSApp];
1581 SET_FRAME_VISIBLE (f, 0);
1582 SET_FRAME_ICONIFIED (f, 0);
1587 x_iconify_frame (struct frame *f)
1588 /* --------------------------------------------------------------------------
1589 External: Iconify window
1590 -------------------------------------------------------------------------- */
1593 struct ns_display_info *dpyinfo;
1595 NSTRACE ("x_iconify_frame");
1596 check_window_system (f);
1597 view = FRAME_NS_VIEW (f);
1598 dpyinfo = FRAME_DISPLAY_INFO (f);
1600 if (dpyinfo->x_highlight_frame == f)
1601 dpyinfo->x_highlight_frame = 0;
1603 if ([[view window] windowNumber] <= 0)
1605 /* the window is still deferred. Make it very small, bring it
1606 on screen and order it out. */
1607 NSRect s = { { 100, 100}, {0, 0} };
1609 t = [[view window] frame];
1610 [[view window] setFrame: s display: NO];
1611 [[view window] orderBack: NSApp];
1612 [[view window] orderOut: NSApp];
1613 [[view window] setFrame: t display: NO];
1616 /* Processing input while Emacs is being minimized can cause a
1617 crash, so block it for the duration. */
1619 [[view window] miniaturize: NSApp];
1623 /* Free X resources of frame F. */
1626 x_free_frame_resources (struct frame *f)
1629 struct ns_display_info *dpyinfo;
1630 Mouse_HLInfo *hlinfo;
1632 NSTRACE ("x_free_frame_resources");
1633 check_window_system (f);
1634 view = FRAME_NS_VIEW (f);
1635 dpyinfo = FRAME_DISPLAY_INFO (f);
1636 hlinfo = MOUSE_HL_INFO (f);
1638 [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1642 free_frame_menubar (f);
1643 free_frame_faces (f);
1645 if (f == dpyinfo->x_focus_frame)
1646 dpyinfo->x_focus_frame = 0;
1647 if (f == dpyinfo->x_highlight_frame)
1648 dpyinfo->x_highlight_frame = 0;
1649 if (f == hlinfo->mouse_face_mouse_frame)
1650 reset_mouse_highlight (hlinfo);
1652 if (f->output_data.ns->miniimage != nil)
1653 [f->output_data.ns->miniimage release];
1655 [[view window] close];
1658 xfree (f->output_data.ns);
1664 x_destroy_window (struct frame *f)
1665 /* --------------------------------------------------------------------------
1666 External: Delete the window
1667 -------------------------------------------------------------------------- */
1669 NSTRACE ("x_destroy_window");
1670 check_window_system (f);
1671 x_free_frame_resources (f);
1677 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1678 /* --------------------------------------------------------------------------
1679 External: Position the window
1680 -------------------------------------------------------------------------- */
1682 NSView *view = FRAME_NS_VIEW (f);
1683 NSArray *screens = [NSScreen screens];
1684 NSScreen *fscreen = [screens objectAtIndex: 0];
1685 NSScreen *screen = [[view window] screen];
1687 NSTRACE ("x_set_offset");
1694 if (view != nil && screen && fscreen)
1696 f->left_pos = f->size_hint_flags & XNegative
1697 ? [screen visibleFrame].size.width + f->left_pos - FRAME_PIXEL_WIDTH (f)
1699 /* We use visibleFrame here to take menu bar into account.
1700 Ideally we should also adjust left/top with visibleFrame.origin. */
1702 f->top_pos = f->size_hint_flags & YNegative
1703 ? ([screen visibleFrame].size.height + f->top_pos
1704 - FRAME_PIXEL_HEIGHT (f) - FRAME_NS_TITLEBAR_HEIGHT (f)
1705 - FRAME_TOOLBAR_HEIGHT (f))
1707 #ifdef NS_IMPL_GNUSTEP
1708 if (f->left_pos < 100)
1709 f->left_pos = 100; /* don't overlap menu */
1711 /* Constrain the setFrameTopLeftPoint so we don't move behind the
1713 NSPoint pt = NSMakePoint (SCREENMAXBOUND (f->left_pos),
1714 SCREENMAXBOUND ([fscreen frame].size.height
1716 NSTRACE_POINT ("setFrameTopLeftPoint", pt);
1717 [[view window] setFrameTopLeftPoint: pt];
1718 f->size_hint_flags &= ~(XNegative|YNegative);
1726 x_set_window_size (struct frame *f,
1727 bool change_gravity,
1731 /* --------------------------------------------------------------------------
1732 Adjust window pixel size based on given character grid size
1733 Impl is a bit more complex than other terms, need to do some
1735 -------------------------------------------------------------------------- */
1737 EmacsView *view = FRAME_NS_VIEW (f);
1738 NSWindow *window = [view window];
1739 NSRect wr = [window frame];
1740 int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1741 int pixelwidth, pixelheight;
1742 int orig_height = wr.size.height;
1744 NSTRACE ("x_set_window_size");
1749 NSTRACE_RECT ("current", wr);
1750 NSTRACE_MSG ("Width:%d Height:%d Pixelwise:%d", width, height, pixelwise);
1751 NSTRACE_MSG ("Font %d x %d", FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f));
1757 pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
1758 pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
1762 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, width);
1763 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, height);
1766 /* If we have a toolbar, take its height into account. */
1767 if (tb && ! [view isFullscreen])
1769 /* NOTE: previously this would generate wrong result if toolbar not
1770 yet displayed and fixing toolbar_height=32 helped, but
1771 now (200903) seems no longer needed */
1772 FRAME_TOOLBAR_HEIGHT (f) =
1773 NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1774 - FRAME_NS_TITLEBAR_HEIGHT (f);
1776 /* Only breaks things here, removed by martin 2015-09-30. */
1777 #ifdef NS_IMPL_GNUSTEP
1778 FRAME_TOOLBAR_HEIGHT (f) -= 3;
1783 FRAME_TOOLBAR_HEIGHT (f) = 0;
1785 wr.size.width = pixelwidth + f->border_width;
1786 wr.size.height = pixelheight;
1787 if (! [view isFullscreen])
1788 wr.size.height += FRAME_NS_TITLEBAR_HEIGHT (f)
1789 + FRAME_TOOLBAR_HEIGHT (f);
1791 /* Do not try to constrain to this screen. We may have multiple
1792 screens, and want Emacs to span those. Constraining to screen
1793 prevents that, and that is not nice to the user. */
1794 if (f->output_data.ns->zooming)
1795 f->output_data.ns->zooming = 0;
1797 wr.origin.y += orig_height - wr.size.height;
1799 frame_size_history_add
1800 (f, Qx_set_window_size_1, width, height,
1801 list5 (Fcons (make_number (pixelwidth), make_number (pixelheight)),
1802 Fcons (make_number (wr.size.width), make_number (wr.size.height)),
1803 make_number (f->border_width),
1804 make_number (FRAME_NS_TITLEBAR_HEIGHT (f)),
1805 make_number (FRAME_TOOLBAR_HEIGHT (f))));
1807 [window setFrame: wr display: YES];
1809 [view updateFrameSize: NO];
1815 ns_fullscreen_hook (struct frame *f)
1817 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1819 NSTRACE ("ns_fullscreen_hook");
1821 if (!FRAME_VISIBLE_P (f))
1824 if (! [view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH)
1826 /* Old style fs don't initiate correctly if created from
1827 init/default-frame alist, so use a timer (not nice...).
1829 [NSTimer scheduledTimerWithTimeInterval: 0.5 target: view
1830 selector: @selector (handleFS)
1831 userInfo: nil repeats: NO];
1840 /* ==========================================================================
1844 ========================================================================== */
1848 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1850 struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1851 if (idx < 1 || idx >= color_table->avail)
1853 return color_table->colors[idx];
1858 ns_index_color (NSColor *color, struct frame *f)
1860 struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1864 if (!color_table->colors)
1866 color_table->size = NS_COLOR_CAPACITY;
1867 color_table->avail = 1; /* skip idx=0 as marker */
1868 color_table->colors = xmalloc (color_table->size * sizeof (NSColor *));
1869 color_table->colors[0] = nil;
1870 color_table->empty_indices = [[NSMutableSet alloc] init];
1873 /* Do we already have this color? */
1874 for (i = 1; i < color_table->avail; i++)
1875 if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1878 if ([color_table->empty_indices count] > 0)
1880 NSNumber *index = [color_table->empty_indices anyObject];
1881 [color_table->empty_indices removeObject: index];
1882 idx = [index unsignedLongValue];
1886 if (color_table->avail == color_table->size)
1887 color_table->colors =
1888 xpalloc (color_table->colors, &color_table->size, 1,
1889 min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1890 idx = color_table->avail++;
1893 color_table->colors[idx] = color;
1895 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1901 ns_free_indexed_color (unsigned long idx, struct frame *f)
1903 struct ns_color_table *color_table;
1910 color_table = FRAME_DISPLAY_INFO (f)->color_table;
1912 if (idx <= 0 || idx >= color_table->size) {
1913 message1 ("ns_free_indexed_color: Color index out of range.\n");
1917 index = [NSNumber numberWithUnsignedInt: idx];
1918 if ([color_table->empty_indices containsObject: index]) {
1919 message1 ("ns_free_indexed_color: attempt to free already freed color.\n");
1923 color = color_table->colors[idx];
1925 color_table->colors[idx] = nil;
1926 [color_table->empty_indices addObject: index];
1927 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1932 ns_get_color (const char *name, NSColor **col)
1933 /* --------------------------------------------------------------------------
1935 -------------------------------------------------------------------------- */
1936 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1937 X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1938 See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1941 static char hex[20];
1943 float r = -1.0, g, b;
1944 NSString *nsname = [NSString stringWithUTF8String: name];
1946 NSTRACE ("ns_get_color(%s, **)", name);
1950 if ([nsname isEqualToString: @"ns_selection_bg_color"])
1952 #ifdef NS_IMPL_COCOA
1953 NSString *defname = [[NSUserDefaults standardUserDefaults]
1954 stringForKey: @"AppleHighlightColor"];
1959 if ((new = [NSColor selectedTextBackgroundColor]) != nil)
1961 *col = [new colorUsingDefaultColorSpace];
1966 nsname = NS_SELECTION_BG_COLOR_DEFAULT;
1968 name = [nsname UTF8String];
1970 else if ([nsname isEqualToString: @"ns_selection_fg_color"])
1972 /* NOTE: OSX applications normally don't set foreground selection, but
1973 text may be unreadable if we don't.
1975 if ((new = [NSColor selectedTextColor]) != nil)
1977 *col = [new colorUsingDefaultColorSpace];
1982 nsname = NS_SELECTION_FG_COLOR_DEFAULT;
1983 name = [nsname UTF8String];
1986 /* First, check for some sort of numeric specification. */
1989 if (name[0] == '0' || name[0] == '1' || name[0] == '.') /* RGB decimal */
1991 NSScanner *scanner = [NSScanner scannerWithString: nsname];
1992 [scanner scanFloat: &r];
1993 [scanner scanFloat: &g];
1994 [scanner scanFloat: &b];
1996 else if (!strncmp(name, "rgb:", 4)) /* A newer X11 format -- rgb:r/g/b */
1997 scaling = (snprintf (hex, sizeof hex, "%s", name + 4) - 2) / 3;
1998 else if (name[0] == '#') /* An old X11 format; convert to newer */
2000 int len = (strlen(name) - 1);
2001 int start = (len % 3 == 0) ? 1 : len / 4 + 1;
2003 scaling = strlen(name+start) / 3;
2004 for (i = 0; i < 3; i++)
2005 sprintf (hex + i * (scaling + 1), "%.*s/", scaling,
2006 name + start + i * scaling);
2007 hex[3 * (scaling + 1) - 1] = '\0';
2013 float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
2014 if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
2024 *col = [NSColor colorForEmacsRed: r green: g blue: b alpha: 1.0];
2029 /* Otherwise, color is expected to be from a list */
2031 NSEnumerator *lenum, *cenum;
2035 #ifdef NS_IMPL_GNUSTEP
2036 /* XXX: who is wrong, the requestor or the implementation? */
2037 if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
2039 nsname = @"highlightColor";
2042 lenum = [[NSColorList availableColorLists] objectEnumerator];
2043 while ( (clist = [lenum nextObject]) && new == nil)
2045 cenum = [[clist allKeys] objectEnumerator];
2046 while ( (name = [cenum nextObject]) && new == nil )
2048 if ([name compare: nsname
2049 options: NSCaseInsensitiveSearch] == NSOrderedSame )
2050 new = [clist colorWithKey: name];
2056 *col = [new colorUsingDefaultColorSpace];
2063 ns_lisp_to_color (Lisp_Object color, NSColor **col)
2064 /* --------------------------------------------------------------------------
2065 Convert a Lisp string object to a NS color
2066 -------------------------------------------------------------------------- */
2068 NSTRACE ("ns_lisp_to_color");
2069 if (STRINGP (color))
2070 return ns_get_color (SSDATA (color), col);
2071 else if (SYMBOLP (color))
2072 return ns_get_color (SSDATA (SYMBOL_NAME (color)), col);
2078 ns_color_to_lisp (NSColor *col)
2079 /* --------------------------------------------------------------------------
2080 Convert a color to a lisp string with the RGB equivalent
2081 -------------------------------------------------------------------------- */
2083 EmacsCGFloat red, green, blue, alpha, gray;
2086 NSTRACE ("ns_color_to_lisp");
2089 if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
2091 if ((str =[[col colorNameComponent] UTF8String]))
2094 return build_string ((char *)str);
2097 [[col colorUsingDefaultColorSpace]
2098 getRed: &red green: &green blue: &blue alpha: &alpha];
2099 if (red == green && red == blue)
2101 [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
2102 getWhite: &gray alpha: &alpha];
2103 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
2104 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
2106 return build_string (buf);
2109 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
2110 lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
2113 return build_string (buf);
2118 ns_query_color(void *col, XColor *color_def, int setPixel)
2119 /* --------------------------------------------------------------------------
2120 Get ARGB values out of NSColor col and put them into color_def.
2121 If setPixel, set the pixel to a concatenated version.
2122 and set color_def pixel to the resulting index.
2123 -------------------------------------------------------------------------- */
2125 EmacsCGFloat r, g, b, a;
2127 [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
2128 color_def->red = r * 65535;
2129 color_def->green = g * 65535;
2130 color_def->blue = b * 65535;
2132 if (setPixel == YES)
2134 = ARGB_TO_ULONG((int)(a*255),
2135 (int)(r*255), (int)(g*255), (int)(b*255));
2140 ns_defined_color (struct frame *f,
2145 /* --------------------------------------------------------------------------
2146 Return true if named color found, and set color_def rgb accordingly.
2147 If makeIndex and alloc are nonzero put the color in the color_table,
2148 and set color_def pixel to the resulting index.
2149 If makeIndex is zero, set color_def pixel to ARGB.
2150 Return false if not found
2151 -------------------------------------------------------------------------- */
2154 NSTRACE_WHEN (NSTRACE_GROUP_COLOR, "ns_defined_color");
2157 if (ns_get_color (name, &col) != 0) /* Color not found */
2162 if (makeIndex && alloc)
2163 color_def->pixel = ns_index_color (col, f);
2164 ns_query_color (col, color_def, !makeIndex);
2171 x_set_frame_alpha (struct frame *f)
2172 /* --------------------------------------------------------------------------
2173 change the entire-frame transparency
2174 -------------------------------------------------------------------------- */
2176 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2178 double alpha_min = 1.0;
2180 NSTRACE ("x_set_frame_alpha");
2182 if (dpyinfo->x_highlight_frame == f)
2183 alpha = f->alpha[0];
2185 alpha = f->alpha[1];
2187 if (FLOATP (Vframe_alpha_lower_limit))
2188 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
2189 else if (INTEGERP (Vframe_alpha_lower_limit))
2190 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
2194 else if (1.0 < alpha)
2196 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
2199 #ifdef NS_IMPL_COCOA
2201 EmacsView *view = FRAME_NS_VIEW (f);
2202 [[view window] setAlphaValue: alpha];
2208 /* ==========================================================================
2212 ========================================================================== */
2216 frame_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
2217 /* --------------------------------------------------------------------------
2218 Programmatically reposition mouse pointer in pixel coordinates
2219 -------------------------------------------------------------------------- */
2221 NSTRACE ("frame_set_mouse_pixel_position");
2224 /* FIXME: this does not work, and what about GNUstep? */
2225 #ifdef NS_IMPL_COCOA
2226 [FRAME_NS_VIEW (f) lockFocus];
2227 PSsetmouse ((float)pix_x, (float)pix_y);
2228 [FRAME_NS_VIEW (f) unlockFocus];
2234 note_mouse_movement (struct frame *frame, CGFloat x, CGFloat y)
2235 /* ------------------------------------------------------------------------
2236 Called by EmacsView on mouseMovement events. Passes on
2237 to emacs mainstream code if we moved off of a rect of interest
2238 known as last_mouse_glyph.
2239 ------------------------------------------------------------------------ */
2241 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
2244 // NSTRACE ("note_mouse_movement");
2246 dpyinfo->last_mouse_motion_frame = frame;
2247 r = &dpyinfo->last_mouse_glyph;
2249 /* Note, this doesn't get called for enter/leave, since we don't have a
2250 position. Those are taken care of in the corresponding NSView methods. */
2252 /* has movement gone beyond last rect we were tracking? */
2253 if (x < r->origin.x || x >= r->origin.x + r->size.width
2254 || y < r->origin.y || y >= r->origin.y + r->size.height)
2256 ns_update_begin (frame);
2257 frame->mouse_moved = 1;
2258 note_mouse_highlight (frame, x, y);
2259 remember_mouse_glyph (frame, x, y, r);
2260 ns_update_end (frame);
2269 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
2270 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
2272 /* --------------------------------------------------------------------------
2273 External (hook): inform emacs about mouse position and hit parts.
2274 If a scrollbar is being dragged, set bar_window, part, x, y, time.
2275 x & y should be position in the scrollbar (the whole bar, not the handle)
2276 and length of scrollbar respectively
2277 -------------------------------------------------------------------------- */
2281 Lisp_Object frame, tail;
2283 struct ns_display_info *dpyinfo;
2285 NSTRACE ("ns_mouse_position");
2289 fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
2293 dpyinfo = FRAME_DISPLAY_INFO (*fp);
2297 /* Clear the mouse-moved flag for every frame on this display. */
2298 FOR_EACH_FRAME (tail, frame)
2299 if (FRAME_NS_P (XFRAME (frame))
2300 && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
2301 XFRAME (frame)->mouse_moved = 0;
2303 dpyinfo->last_mouse_scroll_bar = nil;
2304 if (dpyinfo->last_mouse_frame
2305 && FRAME_LIVE_P (dpyinfo->last_mouse_frame))
2306 f = dpyinfo->last_mouse_frame;
2308 f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame : SELECTED_FRAME ();
2310 if (f && FRAME_NS_P (f))
2312 view = FRAME_NS_VIEW (*fp);
2314 position = [[view window] mouseLocationOutsideOfEventStream];
2315 position = [view convertPoint: position fromView: nil];
2316 remember_mouse_glyph (f, position.x, position.y,
2317 &dpyinfo->last_mouse_glyph);
2318 NSTRACE_POINT ("position", position);
2320 if (bar_window) *bar_window = Qnil;
2321 if (part) *part = scroll_bar_above_handle;
2323 if (x) XSETINT (*x, lrint (position.x));
2324 if (y) XSETINT (*y, lrint (position.y));
2326 *time = dpyinfo->last_mouse_movement_time;
2335 ns_frame_up_to_date (struct frame *f)
2336 /* --------------------------------------------------------------------------
2337 External (hook): Fix up mouse highlighting right after a full update.
2338 Can't use FRAME_MOUSE_UPDATE due to ns_frame_begin and ns_frame_end calls.
2339 -------------------------------------------------------------------------- */
2341 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_frame_up_to_date");
2345 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
2346 if (f == hlinfo->mouse_face_mouse_frame)
2350 note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
2351 hlinfo->mouse_face_mouse_x,
2352 hlinfo->mouse_face_mouse_y);
2361 ns_define_frame_cursor (struct frame *f, Cursor cursor)
2362 /* --------------------------------------------------------------------------
2363 External (RIF): set frame mouse pointer type.
2364 -------------------------------------------------------------------------- */
2366 NSTRACE ("ns_define_frame_cursor");
2367 if (FRAME_POINTER_TYPE (f) != cursor)
2369 EmacsView *view = FRAME_NS_VIEW (f);
2370 FRAME_POINTER_TYPE (f) = cursor;
2371 [[view window] invalidateCursorRectsForView: view];
2372 /* Redisplay assumes this function also draws the changed frame
2373 cursor, but this function doesn't, so do it explicitly. */
2374 x_update_cursor (f, 1);
2380 /* ==========================================================================
2384 ========================================================================== */
2388 ns_convert_key (unsigned code)
2389 /* --------------------------------------------------------------------------
2390 Internal call used by NSView-keyDown.
2391 -------------------------------------------------------------------------- */
2393 const unsigned last_keysym = ARRAYELTS (convert_ns_to_X_keysym);
2395 /* An array would be faster, but less easy to read. */
2396 for (keysym = 0; keysym < last_keysym; keysym += 2)
2397 if (code == convert_ns_to_X_keysym[keysym])
2398 return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
2400 /* if decide to use keyCode and Carbon table, use this line:
2401 return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
2406 x_get_keysym_name (int keysym)
2407 /* --------------------------------------------------------------------------
2408 Called by keyboard.c. Not sure if the return val is important, except
2410 -------------------------------------------------------------------------- */
2412 static char value[16];
2413 NSTRACE ("x_get_keysym_name");
2414 sprintf (value, "%d", keysym);
2420 /* ==========================================================================
2422 Block drawing operations
2424 ========================================================================== */
2428 ns_redraw_scroll_bars (struct frame *f)
2432 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
2433 NSTRACE ("ns_redraw_scroll_bars");
2434 for (i =[subviews count]-1; i >= 0; i--)
2436 view = [subviews objectAtIndex: i];
2437 if (![view isKindOfClass: [EmacsScroller class]]) continue;
2444 ns_clear_frame (struct frame *f)
2445 /* --------------------------------------------------------------------------
2446 External (hook): Erase the entire frame
2447 -------------------------------------------------------------------------- */
2449 NSView *view = FRAME_NS_VIEW (f);
2452 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_clear_frame");
2454 /* comes on initial frame because we have
2455 after-make-frame-functions = select-frame */
2456 if (!FRAME_DEFAULT_FACE (f))
2459 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2464 ns_focus (f, &r, 1);
2465 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
2469 /* as of 2006/11 or so this is now needed */
2470 ns_redraw_scroll_bars (f);
2476 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2477 /* --------------------------------------------------------------------------
2478 External (RIF): Clear section of frame
2479 -------------------------------------------------------------------------- */
2481 NSRect r = NSMakeRect (x, y, width, height);
2482 NSView *view = FRAME_NS_VIEW (f);
2483 struct face *face = FRAME_DEFAULT_FACE (f);
2488 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_clear_frame_area");
2490 r = NSIntersectionRect (r, [view frame]);
2491 ns_focus (f, &r, 1);
2492 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2501 ns_copy_bits (struct frame *f, NSRect src, NSRect dest)
2503 NSTRACE ("ns_copy_bits");
2505 if (FRAME_NS_VIEW (f))
2507 hide_bell(); // Ensure the bell image isn't scrolled.
2509 ns_focus (f, &dest, 1);
2510 [FRAME_NS_VIEW (f) scrollRect: src
2511 by: NSMakeSize (dest.origin.x - src.origin.x,
2512 dest.origin.y - src.origin.y)];
2518 ns_scroll_run (struct window *w, struct run *run)
2519 /* --------------------------------------------------------------------------
2520 External (RIF): Insert or delete n lines at line vpos
2521 -------------------------------------------------------------------------- */
2523 struct frame *f = XFRAME (w->frame);
2524 int x, y, width, height, from_y, to_y, bottom_y;
2526 NSTRACE ("ns_scroll_run");
2528 /* begin copy from other terms */
2529 /* Get frame-relative bounding box of the text display area of W,
2530 without mode lines. Include in this box the left and right
2532 window_box (w, ANY_AREA, &x, &y, &width, &height);
2534 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2535 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2536 bottom_y = y + height;
2540 /* Scrolling up. Make sure we don't copy part of the mode
2541 line at the bottom. */
2542 if (from_y + run->height > bottom_y)
2543 height = bottom_y - from_y;
2545 height = run->height;
2549 /* Scrolling down. Make sure we don't copy over the mode line.
2551 if (to_y + run->height > bottom_y)
2552 height = bottom_y - to_y;
2554 height = run->height;
2556 /* end copy from other terms */
2566 NSRect srcRect = NSMakeRect (x, from_y, width, height);
2567 NSRect dstRect = NSMakeRect (x, to_y, width, height);
2569 ns_copy_bits (f, srcRect , dstRect);
2577 ns_after_update_window_line (struct window *w, struct glyph_row *desired_row)
2578 /* --------------------------------------------------------------------------
2579 External (RIF): preparatory to fringe update after text was updated
2580 -------------------------------------------------------------------------- */
2585 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_after_update_window_line");
2587 /* begin copy from other terms */
2590 if (!desired_row->mode_line_p && !w->pseudo_window_p)
2591 desired_row->redraw_fringe_bitmaps_p = 1;
2593 /* When a window has disappeared, make sure that no rest of
2594 full-width rows stays visible in the internal border. */
2595 if (windows_or_buffers_changed
2596 && desired_row->full_width_p
2597 && (f = XFRAME (w->frame),
2598 width = FRAME_INTERNAL_BORDER_WIDTH (f),
2600 && (height = desired_row->visible_height,
2603 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2606 ns_clear_frame_area (f, 0, y, width, height);
2607 ns_clear_frame_area (f,
2608 FRAME_PIXEL_WIDTH (f) - width,
2616 ns_shift_glyphs_for_insert (struct frame *f,
2617 int x, int y, int width, int height,
2619 /* --------------------------------------------------------------------------
2620 External (RIF): copy an area horizontally, don't worry about clearing src
2621 -------------------------------------------------------------------------- */
2623 NSRect srcRect = NSMakeRect (x, y, width, height);
2624 NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2626 NSTRACE ("ns_shift_glyphs_for_insert");
2628 ns_copy_bits (f, srcRect, dstRect);
2633 /* ==========================================================================
2635 Character encoding and metrics
2637 ========================================================================== */
2641 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2642 /* --------------------------------------------------------------------------
2643 External (RIF); compute left/right overhang of whole string and set in s
2644 -------------------------------------------------------------------------- */
2646 struct font *font = s->font;
2650 struct font_metrics metrics;
2651 unsigned int codes[2];
2652 codes[0] = *(s->char2b);
2653 codes[1] = *(s->char2b + s->nchars - 1);
2655 font->driver->text_extents (font, codes, 2, &metrics);
2656 s->left_overhang = -metrics.lbearing;
2658 = metrics.rbearing > metrics.width
2659 ? metrics.rbearing - metrics.width : 0;
2663 s->left_overhang = 0;
2664 if (EQ (font->driver->type, Qns))
2665 s->right_overhang = ((struct nsfont_info *)font)->ital ?
2666 FONT_HEIGHT (font) * 0.2 : 0;
2668 s->right_overhang = 0;
2674 /* ==========================================================================
2676 Fringe and cursor drawing
2678 ========================================================================== */
2681 extern int max_used_fringe_bitmap;
2683 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2684 struct draw_fringe_bitmap_params *p)
2685 /* --------------------------------------------------------------------------
2686 External (RIF); fringe-related
2687 -------------------------------------------------------------------------- */
2689 /* Fringe bitmaps comes in two variants, normal and periodic. A
2690 periodic bitmap is used to create a continuous pattern. Since a
2691 bitmap is rendered one text line at a time, the start offset (dh)
2692 of the bitmap varies. Concretely, this is used for the empty
2695 For a bitmap, "h + dh" is the full height and is always
2696 invariant. For a normal bitmap "dh" is zero.
2698 For example, when the period is three and the full height is 72
2699 the following combinations exists:
2705 struct frame *f = XFRAME (WINDOW_FRAME (w));
2706 struct face *face = p->face;
2707 static EmacsImage **bimgs = NULL;
2708 static int nBimgs = 0;
2710 NSTRACE_WHEN (NSTRACE_GROUP_FRINGE, "ns_draw_fringe_bitmap");
2711 NSTRACE_MSG ("which:%d cursor:%d overlay:%d width:%d height:%d period:%d",
2712 p->which, p->cursor_p, p->overlay_p, p->wd, p->h, p->dh);
2714 /* grow bimgs if needed */
2715 if (nBimgs < max_used_fringe_bitmap)
2717 bimgs = xrealloc (bimgs, max_used_fringe_bitmap * sizeof *bimgs);
2718 memset (bimgs + nBimgs, 0,
2719 (max_used_fringe_bitmap - nBimgs) * sizeof *bimgs);
2720 nBimgs = max_used_fringe_bitmap;
2723 /* Must clip because of partially visible lines. */
2724 ns_clip_to_row (w, row, ANY_AREA, YES);
2728 int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
2730 if (bx >= 0 && nx > 0)
2732 NSRect r = NSMakeRect (bx, by, nx, ny);
2734 [ns_lookup_indexed_color (face->background, f) set];
2741 NSRect r = NSMakeRect (p->x, p->y, p->wd, p->h);
2742 EmacsImage *img = bimgs[p->which - 1];
2746 // Note: For "periodic" images, allocate one EmacsImage for
2747 // the base image, and use it for all dh:s.
2748 unsigned short *bits = p->bits;
2749 int full_height = p->h + p->dh;
2751 unsigned char *cbits = xmalloc (full_height);
2753 for (i = 0; i < full_height; i++)
2755 img = [[EmacsImage alloc] initFromXBM: cbits width: 8
2758 bimgs[p->which - 1] = img;
2762 NSTRACE_RECT ("r", r);
2765 /* Since we composite the bitmap instead of just blitting it, we need
2766 to erase the whole background. */
2767 [ns_lookup_indexed_color(face->background, f) set];
2773 bm_color = ns_lookup_indexed_color(face->foreground, f);
2774 else if (p->overlay_p)
2775 bm_color = ns_lookup_indexed_color(face->background, f);
2777 bm_color = f->output_data.ns->cursor_color;
2778 [img setXBMColor: bm_color];
2781 #ifdef NS_IMPL_COCOA
2782 // Note: For periodic images, the full image height is "h + hd".
2783 // By using the height h, a suitable part of the image is used.
2784 NSRect fromRect = NSMakeRect(0, 0, p->wd, p->h);
2786 NSTRACE_RECT ("fromRect", fromRect);
2790 operation: NSCompositingOperationSourceOver
2796 NSPoint pt = r.origin;
2798 [img compositeToPoint: pt operation: NSCompositingOperationSourceOver];
2807 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2808 int x, int y, enum text_cursor_kinds cursor_type,
2809 int cursor_width, bool on_p, bool active_p)
2810 /* --------------------------------------------------------------------------
2811 External call (RIF): draw cursor.
2812 Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2813 -------------------------------------------------------------------------- */
2816 int fx, fy, h, cursor_height;
2817 struct frame *f = WINDOW_XFRAME (w);
2818 struct glyph *phys_cursor_glyph;
2819 struct glyph *cursor_glyph;
2821 NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2823 /* If cursor is out of bounds, don't draw garbage. This can happen
2824 in mini-buffer windows when switching between echo area glyphs
2827 NSTRACE ("ns_draw_window_cursor");
2832 w->phys_cursor_type = cursor_type;
2833 w->phys_cursor_on_p = on_p;
2835 if (cursor_type == NO_CURSOR)
2837 w->phys_cursor_width = 0;
2841 if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2843 if (glyph_row->exact_window_width_line_p
2844 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2846 glyph_row->cursor_in_fringe_p = 1;
2847 draw_fringe_bitmap (w, glyph_row, 0);
2852 /* We draw the cursor (with NSRectFill), then draw the glyph on top
2853 (other terminals do it the other way round). We must set
2854 w->phys_cursor_width to the cursor width. For bar cursors, that
2855 is CURSOR_WIDTH; for box cursors, it is the glyph width. */
2856 get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2858 /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2859 to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2860 if (cursor_type == BAR_CURSOR)
2862 if (cursor_width < 1)
2863 cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2865 /* The bar cursor should never be wider than the glyph. */
2866 if (cursor_width < w->phys_cursor_width)
2867 w->phys_cursor_width = cursor_width;
2869 /* If we have an HBAR, "cursor_width" MAY specify height. */
2870 else if (cursor_type == HBAR_CURSOR)
2872 cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2873 if (cursor_height > glyph_row->height)
2874 cursor_height = glyph_row->height;
2875 if (h > cursor_height) // Cursor smaller than line height, move down
2876 fy += h - cursor_height;
2880 r.origin.x = fx, r.origin.y = fy;
2882 r.size.width = w->phys_cursor_width;
2884 /* Prevent the cursor from being drawn outside the text area. */
2885 ns_clip_to_row (w, glyph_row, TEXT_AREA, NO); /* do ns_focus(f, &r, 1); if remove */
2888 face = FACE_FROM_ID_OR_NULL (f, phys_cursor_glyph->face_id);
2889 if (face && NS_FACE_BACKGROUND (face)
2890 == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2892 [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2893 hollow_color = FRAME_CURSOR_COLOR (f);
2896 [FRAME_CURSOR_COLOR (f) set];
2898 #ifdef NS_IMPL_COCOA
2899 /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2900 atomic. Cleaner ways of doing this should be investigated.
2901 One way would be to set a global variable DRAWING_CURSOR
2902 when making the call to draw_phys..(), don't focus in that
2903 case, then move the ns_unfocus() here after that call. */
2904 NSDisableScreenUpdates ();
2907 switch (cursor_type)
2909 case DEFAULT_CURSOR:
2912 case FILLED_BOX_CURSOR:
2915 case HOLLOW_BOX_CURSOR:
2918 NSRectFill (NSInsetRect (r, 1, 1));
2919 [FRAME_CURSOR_COLOR (f) set];
2926 /* If the character under cursor is R2L, draw the bar cursor
2927 on the right of its glyph, rather than on the left. */
2928 cursor_glyph = get_phys_cursor_glyph (w);
2929 if ((cursor_glyph->resolved_level & 1) != 0)
2930 s.origin.x += cursor_glyph->pixel_width - s.size.width;
2937 /* draw the character under the cursor */
2938 if (cursor_type != NO_CURSOR)
2939 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2941 #ifdef NS_IMPL_COCOA
2942 NSEnableScreenUpdates ();
2949 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2950 /* --------------------------------------------------------------------------
2951 External (RIF): Draw a vertical line.
2952 -------------------------------------------------------------------------- */
2954 struct frame *f = XFRAME (WINDOW_FRAME (w));
2956 NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2958 NSTRACE ("ns_draw_vertical_window_border");
2960 face = FACE_FROM_ID_OR_NULL (f, VERTICAL_BORDER_FACE_ID);
2962 ns_focus (f, &r, 1);
2964 [ns_lookup_indexed_color(face->foreground, f) set];
2972 ns_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
2973 /* --------------------------------------------------------------------------
2974 External (RIF): Draw a window divider.
2975 -------------------------------------------------------------------------- */
2977 struct frame *f = XFRAME (WINDOW_FRAME (w));
2979 NSRect r = NSMakeRect (x0, y0, x1-x0, y1-y0);
2981 NSTRACE ("ns_draw_window_divider");
2983 face = FACE_FROM_ID_OR_NULL (f, WINDOW_DIVIDER_FACE_ID);
2985 ns_focus (f, &r, 1);
2987 [ns_lookup_indexed_color(face->foreground, f) set];
2994 ns_show_hourglass (struct frame *f)
2996 /* TODO: add NSProgressIndicator to all frames. */
3000 ns_hide_hourglass (struct frame *f)
3002 /* TODO: remove NSProgressIndicator from all frames. */
3005 /* ==========================================================================
3007 Glyph drawing operations
3009 ========================================================================== */
3012 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
3013 /* --------------------------------------------------------------------------
3014 Wrapper utility to account for internal border width on full-width lines,
3015 and allow top full-width rows to hit the frame top. nr should be pointer
3016 to two successive NSRects. Number of rects actually used is returned.
3017 -------------------------------------------------------------------------- */
3019 int n = get_glyph_string_clip_rects (s, nr, 2);
3023 /* --------------------------------------------------------------------
3024 Draw a wavy line under glyph string s. The wave fills wave_height
3031 wave_height = 3 | * * * *
3032 --------------------------------------------------------------------- */
3035 ns_draw_underwave (struct glyph_string *s, EmacsCGFloat width, EmacsCGFloat x)
3037 int wave_height = 3, wave_length = 2;
3038 int y, dx, dy, odd, xmax;
3043 dy = wave_height - 1;
3044 y = s->ybase - wave_height + 3;
3047 /* Find and set clipping rectangle */
3048 waveClip = NSMakeRect (x, y, width, wave_height);
3049 [[NSGraphicsContext currentContext] saveGraphicsState];
3050 NSRectClip (waveClip);
3052 /* Draw the waves */
3053 a.x = x - ((int)(x) % dx) + (EmacsCGFloat) 0.5;
3055 odd = (int)(a.x/dx) % 2;
3056 a.y = b.y = y + 0.5;
3065 [NSBezierPath strokeLineFromPoint:a toPoint:b];
3066 a.x = b.x, a.y = b.y;
3067 b.x += dx, b.y = y + 0.5 + odd*dy;
3071 /* Restore previous clipping rectangle(s) */
3072 [[NSGraphicsContext currentContext] restoreGraphicsState];
3078 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
3079 NSColor *defaultCol, CGFloat width, CGFloat x)
3080 /* --------------------------------------------------------------------------
3081 Draw underline, overline, and strike-through on glyph string s.
3082 -------------------------------------------------------------------------- */
3084 if (s->for_overlaps)
3088 if (face->underline_p)
3090 if (s->face->underline_type == FACE_UNDER_WAVE)
3092 if (face->underline_defaulted_p)
3095 [ns_lookup_indexed_color (face->underline_color, s->f) set];
3097 ns_draw_underwave (s, width, x);
3099 else if (s->face->underline_type == FACE_UNDER_LINE)
3103 unsigned long thickness, position;
3105 /* If the prev was underlined, match its appearance. */
3106 if (s->prev && s->prev->face->underline_p
3107 && s->prev->face->underline_type == FACE_UNDER_LINE
3108 && s->prev->underline_thickness > 0)
3110 thickness = s->prev->underline_thickness;
3111 position = s->prev->underline_position;
3116 unsigned long descent;
3119 descent = s->y + s->height - s->ybase;
3121 /* Use underline thickness of font, defaulting to 1. */
3122 thickness = (font && font->underline_thickness > 0)
3123 ? font->underline_thickness : 1;
3125 /* Determine the offset of underlining from the baseline. */
3126 if (x_underline_at_descent_line)
3127 position = descent - thickness;
3128 else if (x_use_underline_position_properties
3129 && font && font->underline_position >= 0)
3130 position = font->underline_position;
3132 position = lround (font->descent / 2);
3134 position = underline_minimum_offset;
3136 position = max (position, underline_minimum_offset);
3138 /* Ensure underlining is not cropped. */
3139 if (descent <= position)
3141 position = descent - 1;
3144 else if (descent < position + thickness)
3148 s->underline_thickness = thickness;
3149 s->underline_position = position;
3151 r = NSMakeRect (x, s->ybase + position, width, thickness);
3153 if (face->underline_defaulted_p)
3156 [ns_lookup_indexed_color (face->underline_color, s->f) set];
3160 /* Do overline. We follow other terms in using a thickness of 1
3161 and ignoring overline_margin. */
3162 if (face->overline_p)
3165 r = NSMakeRect (x, s->y, width, 1);
3167 if (face->overline_color_defaulted_p)
3170 [ns_lookup_indexed_color (face->overline_color, s->f) set];
3174 /* Do strike-through. We follow other terms for thickness and
3175 vertical position.*/
3176 if (face->strike_through_p)
3181 dy = lrint ((s->height - 1) / 2);
3182 r = NSMakeRect (x, s->y + dy, width, 1);
3184 if (face->strike_through_color_defaulted_p)
3187 [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
3193 ns_draw_box (NSRect r, CGFloat thickness, NSColor *col,
3194 char left_p, char right_p)
3195 /* --------------------------------------------------------------------------
3196 Draw an unfilled rect inside r, optionally leaving left and/or right open.
3197 Note we can't just use an NSDrawRect command, because of the possibility
3198 of some sides not being drawn, and because the rect will be filled.
3199 -------------------------------------------------------------------------- */
3205 s.size.height = thickness;
3207 s.origin.y += r.size.height - thickness;
3210 s.size.height = r.size.height;
3211 s.origin.y = r.origin.y;
3213 /* left, right (optional) */
3214 s.size.width = thickness;
3219 s.origin.x += r.size.width - thickness;
3226 ns_draw_relief (NSRect r, int thickness, char raised_p,
3227 char top_p, char bottom_p, char left_p, char right_p,
3228 struct glyph_string *s)
3229 /* --------------------------------------------------------------------------
3230 Draw a relief rect inside r, optionally leaving some sides open.
3231 Note we can't just use an NSDrawBezel command, because of the possibility
3232 of some sides not being drawn, and because the rect will be filled.
3233 -------------------------------------------------------------------------- */
3235 static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
3236 NSColor *newBaseCol = nil;
3239 NSTRACE ("ns_draw_relief");
3243 if (s->face->use_box_color_for_shadows_p)
3245 newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
3247 /* else if (s->first_glyph->type == IMAGE_GLYPH
3249 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
3251 newBaseCol = IMAGE_BACKGROUND (s->img, s->f, 0);
3255 newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
3258 if (newBaseCol == nil)
3259 newBaseCol = [NSColor grayColor];
3261 if (newBaseCol != baseCol) /* TODO: better check */
3264 baseCol = [newBaseCol retain];
3266 lightCol = [[baseCol highlightWithLevel: 0.2] retain];
3268 darkCol = [[baseCol shadowWithLevel: 0.3] retain];
3271 [(raised_p ? lightCol : darkCol) set];
3273 /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
3276 sr.size.height = thickness;
3277 if (top_p) NSRectFill (sr);
3280 sr.size.height = r.size.height;
3281 sr.size.width = thickness;
3282 if (left_p) NSRectFill (sr);
3284 [(raised_p ? darkCol : lightCol) set];
3287 sr.size.width = r.size.width;
3288 sr.size.height = thickness;
3289 sr.origin.y += r.size.height - thickness;
3290 if (bottom_p) NSRectFill (sr);
3293 sr.size.height = r.size.height;
3294 sr.origin.y = r.origin.y;
3295 sr.size.width = thickness;
3296 sr.origin.x += r.size.width - thickness;
3297 if (right_p) NSRectFill (sr);
3302 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
3303 /* --------------------------------------------------------------------------
3304 Function modeled after x_draw_glyph_string_box ().
3305 Sets up parameters for drawing.
3306 -------------------------------------------------------------------------- */
3308 int right_x, last_x;
3309 char left_p, right_p;
3310 struct glyph *last_glyph;
3315 if (s->hl == DRAW_MOUSE_FACE)
3317 face = FACE_FROM_ID_OR_NULL (s->f,
3318 MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3320 face = FACE_FROM_ID_OR_NULL (s->f, MOUSE_FACE_ID);
3325 thickness = face->box_line_width;
3327 NSTRACE ("ns_dumpglyphs_box_or_relief");
3329 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
3330 ? WINDOW_RIGHT_EDGE_X (s->w)
3331 : window_box_right (s->w, s->area));
3332 last_glyph = (s->cmp || s->img
3333 ? s->first_glyph : s->first_glyph + s->nchars-1);
3335 right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
3336 ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
3338 left_p = (s->first_glyph->left_box_line_p
3339 || (s->hl == DRAW_MOUSE_FACE
3340 && (s->prev == NULL || s->prev->hl != s->hl)));
3341 right_p = (last_glyph->right_box_line_p
3342 || (s->hl == DRAW_MOUSE_FACE
3343 && (s->next == NULL || s->next->hl != s->hl)));
3345 r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
3347 /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
3348 if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
3350 ns_draw_box (r, abs (thickness),
3351 ns_lookup_indexed_color (face->box_color, s->f),
3356 ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
3357 1, 1, left_p, right_p, s);
3363 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
3364 /* --------------------------------------------------------------------------
3365 Modeled after x_draw_glyph_string_background, which draws BG in
3366 certain cases. Others are left to the text rendering routine.
3367 -------------------------------------------------------------------------- */
3369 NSTRACE ("ns_maybe_dumpglyphs_background");
3371 if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
3373 int box_line_width = max (s->face->box_line_width, 0);
3374 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
3375 /* When xdisp.c ignores FONT_HEIGHT, we cannot trust font
3376 dimensions, since the actual glyphs might be much
3377 smaller. So in that case we always clear the rectangle
3378 with background color. */
3379 || FONT_TOO_HIGH (s->font)
3380 || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
3383 if (s->hl == DRAW_MOUSE_FACE)
3386 = FACE_FROM_ID_OR_NULL (s->f,
3387 MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3389 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3392 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3394 [(NS_FACE_BACKGROUND (face) != 0
3395 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
3396 : FRAME_BACKGROUND_COLOR (s->f)) set];
3399 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (s->f);
3400 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
3403 if (s->hl != DRAW_CURSOR)
3405 NSRect r = NSMakeRect (s->x, s->y + box_line_width,
3406 s->background_width,
3407 s->height-2*box_line_width);
3411 s->background_filled_p = 1;
3418 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
3419 /* --------------------------------------------------------------------------
3420 Renders an image and associated borders.
3421 -------------------------------------------------------------------------- */
3423 EmacsImage *img = s->img->pixmap;
3424 int box_line_vwidth = max (s->face->box_line_width, 0);
3425 int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3426 int bg_x, bg_y, bg_height;
3433 NSTRACE ("ns_dumpglyphs_image");
3435 if (s->face->box != FACE_NO_BOX
3436 && s->first_glyph->left_box_line_p && s->slice.x == 0)
3437 x += abs (s->face->box_line_width);
3440 bg_y = s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
3441 bg_height = s->height;
3442 /* other terms have this, but was causing problems w/tabbar mode */
3443 /* - 2 * box_line_vwidth; */
3445 if (s->slice.x == 0) x += s->img->hmargin;
3446 if (s->slice.y == 0) y += s->img->vmargin;
3448 /* Draw BG: if we need larger area than image itself cleared, do that,
3449 otherwise, since we composite the image under NS (instead of mucking
3450 with its background color), we must clear just the image area. */
3451 if (s->hl == DRAW_MOUSE_FACE)
3453 face = FACE_FROM_ID_OR_NULL (s->f,
3454 MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3456 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3459 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3461 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
3463 if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
3464 || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
3466 br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
3467 s->background_filled_p = 1;
3471 br = NSMakeRect (x, y, s->slice.width, s->slice.height);
3476 /* Draw the image.. do we need to draw placeholder if img ==nil? */
3479 #ifdef NS_IMPL_COCOA
3480 NSRect dr = NSMakeRect (x, y, s->slice.width, s->slice.height);
3481 NSRect ir = NSMakeRect (s->slice.x,
3482 s->img->height - s->slice.y - s->slice.height,
3483 s->slice.width, s->slice.height);
3486 operation: NSCompositingOperationSourceOver
3491 [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3492 operation: NSCompositingOperationSourceOver];
3496 if (s->hl == DRAW_CURSOR)
3498 [FRAME_CURSOR_COLOR (s->f) set];
3499 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3500 tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3502 /* Currently on NS img->mask is always 0. Since
3503 get_window_cursor_type specifies a hollow box cursor when on
3504 a non-masked image we never reach this clause. But we put it
3505 in in anticipation of better support for image masks on
3507 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3511 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3514 /* Draw underline, overline, strike-through. */
3515 ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3517 /* Draw relief, if requested */
3518 if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3520 if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3522 th = tool_bar_button_relief >= 0 ?
3523 tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3524 raised_p = (s->hl == DRAW_IMAGE_RAISED);
3528 th = abs (s->img->relief);
3529 raised_p = (s->img->relief > 0);
3532 r.origin.x = x - th;
3533 r.origin.y = y - th;
3534 r.size.width = s->slice.width + 2*th-1;
3535 r.size.height = s->slice.height + 2*th-1;
3536 ns_draw_relief (r, th, raised_p,
3538 s->slice.y + s->slice.height == s->img->height,
3540 s->slice.x + s->slice.width == s->img->width, s);
3543 /* If there is no mask, the background won't be seen,
3544 so draw a rectangle on the image for the cursor.
3545 Do this for all images, getting transparency right is not reliable. */
3546 if (s->hl == DRAW_CURSOR)
3548 int thickness = abs (s->img->relief);
3549 if (thickness == 0) thickness = 1;
3550 ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3556 ns_dumpglyphs_stretch (struct glyph_string *s)
3561 NSColor *fgCol, *bgCol;
3563 if (!s->background_filled_p)
3565 n = ns_get_glyph_string_clip_rect (s, r);
3566 *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3568 ns_focus (s->f, r, n);
3570 if (s->hl == DRAW_MOUSE_FACE)
3572 face = FACE_FROM_ID_OR_NULL (s->f,
3573 MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3575 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3578 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3580 bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3581 fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3583 for (i = 0; i < n; ++i)
3585 if (!s->row->full_width_p)
3587 int overrun, leftoverrun;
3589 /* truncate to avoid overwriting fringe and/or scrollbar */
3590 overrun = max (0, (s->x + s->background_width)
3591 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3592 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3593 r[i].size.width -= overrun;
3595 /* truncate to avoid overwriting to left of the window box */
3596 leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3597 + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3599 if (leftoverrun > 0)
3601 r[i].origin.x += leftoverrun;
3602 r[i].size.width -= leftoverrun;
3605 /* XXX: Try to work between problem where a stretch glyph on
3606 a partially-visible bottom row will clear part of the
3607 modeline, and another where list-buffers headers and similar
3608 rows erroneously have visible_height set to 0. Not sure
3609 where this is coming from as other terms seem not to show. */
3610 r[i].size.height = min (s->height, s->row->visible_height);
3615 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3616 overwriting cursor (usually when cursor on a tab) */
3617 if (s->hl == DRAW_CURSOR)
3622 width = s->w->phys_cursor_width;
3623 r[i].size.width -= width;
3624 r[i].origin.x += width;
3628 /* Draw overlining, etc. on the cursor. */
3629 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3630 ns_draw_text_decoration (s, face, bgCol, width, x);
3632 ns_draw_text_decoration (s, face, fgCol, width, x);
3639 /* Draw overlining, etc. on the stretch glyph (or the part
3640 of the stretch glyph after the cursor). */
3641 ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3645 s->background_filled_p = 1;
3651 ns_draw_glyph_string_foreground (struct glyph_string *s)
3654 struct font *font = s->font;
3656 /* If first glyph of S has a left box line, start drawing the text
3657 of S to the right of that box line. */
3658 if (s->face && s->face->box != FACE_NO_BOX
3659 && s->first_glyph->left_box_line_p)
3660 x = s->x + eabs (s->face->box_line_width);
3664 flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3665 (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3666 (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3667 NS_DUMPGLYPH_NORMAL));
3670 (s, s->cmp_from, s->nchars, x, s->ybase,
3671 (flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3672 || flags == NS_DUMPGLYPH_MOUSEFACE);
3677 ns_draw_composite_glyph_string_foreground (struct glyph_string *s)
3680 struct font *font = s->font;
3682 /* If first glyph of S has a left box line, start drawing the text
3683 of S to the right of that box line. */
3684 if (s->face && s->face->box != FACE_NO_BOX
3685 && s->first_glyph->left_box_line_p)
3686 x = s->x + eabs (s->face->box_line_width);
3690 /* S is a glyph string for a composition. S->cmp_from is the index
3691 of the first character drawn for glyphs of this composition.
3692 S->cmp_from == 0 means we are drawing the very first character of
3693 this composition. */
3695 /* Draw a rectangle for the composition if the font for the very
3696 first character of the composition could not be loaded. */
3697 if (s->font_not_found_p)
3699 if (s->cmp_from == 0)
3701 NSRect r = NSMakeRect (s->x, s->y, s->width-1, s->height -1);
3702 ns_draw_box (r, 1, FRAME_CURSOR_COLOR (s->f), 1, 1);
3705 else if (! s->first_glyph->u.cmp.automatic)
3709 for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
3710 /* TAB in a composition means display glyphs with padding
3711 space on the left or right. */
3712 if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
3714 int xx = x + s->cmp->offsets[j * 2];
3715 int yy = y - s->cmp->offsets[j * 2 + 1];
3717 font->driver->draw (s, j, j + 1, xx, yy, false);
3718 if (s->face->overstrike)
3719 font->driver->draw (s, j, j + 1, xx + 1, yy, false);
3724 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
3729 for (i = j = s->cmp_from; i < s->cmp_to; i++)
3731 glyph = LGSTRING_GLYPH (gstring, i);
3732 if (NILP (LGLYPH_ADJUSTMENT (glyph)))
3733 width += LGLYPH_WIDTH (glyph);
3736 int xoff, yoff, wadjust;
3740 font->driver->draw (s, j, i, x, y, false);
3741 if (s->face->overstrike)
3742 font->driver->draw (s, j, i, x + 1, y, false);
3745 xoff = LGLYPH_XOFF (glyph);
3746 yoff = LGLYPH_YOFF (glyph);
3747 wadjust = LGLYPH_WADJUST (glyph);
3748 font->driver->draw (s, i, i + 1, x + xoff, y + yoff, false);
3749 if (s->face->overstrike)
3750 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff,
3759 font->driver->draw (s, j, i, x, y, false);
3760 if (s->face->overstrike)
3761 font->driver->draw (s, j, i, x + 1, y, false);
3767 ns_draw_glyph_string (struct glyph_string *s)
3768 /* --------------------------------------------------------------------------
3769 External (RIF): Main draw-text call.
3770 -------------------------------------------------------------------------- */
3772 /* TODO (optimize): focus for box and contents draw */
3775 char box_drawn_p = 0;
3776 struct font *font = s->face->font;
3777 if (! font) font = FRAME_FONT (s->f);
3779 NSTRACE_WHEN (NSTRACE_GROUP_GLYPHS, "ns_draw_glyph_string");
3781 if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3784 struct glyph_string *next;
3786 for (width = 0, next = s->next;
3787 next && width < s->right_overhang;
3788 width += next->width, next = next->next)
3789 if (next->first_glyph->type != IMAGE_GLYPH)
3791 if (next->first_glyph->type != STRETCH_GLYPH)
3793 n = ns_get_glyph_string_clip_rect (s->next, r);
3794 ns_focus (s->f, r, n);
3795 ns_maybe_dumpglyphs_background (s->next, 1);
3800 ns_dumpglyphs_stretch (s->next);
3802 next->num_clips = 0;
3806 if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3807 && (s->first_glyph->type == CHAR_GLYPH
3808 || s->first_glyph->type == COMPOSITE_GLYPH))
3810 n = ns_get_glyph_string_clip_rect (s, r);
3811 ns_focus (s->f, r, n);
3812 ns_maybe_dumpglyphs_background (s, 1);
3813 ns_dumpglyphs_box_or_relief (s);
3818 switch (s->first_glyph->type)
3822 n = ns_get_glyph_string_clip_rect (s, r);
3823 ns_focus (s->f, r, n);
3824 ns_dumpglyphs_image (s, r[0]);
3829 ns_dumpglyphs_stretch (s);
3833 case COMPOSITE_GLYPH:
3834 n = ns_get_glyph_string_clip_rect (s, r);
3835 ns_focus (s->f, r, n);
3837 if (s->for_overlaps || (s->cmp_from > 0
3838 && ! s->first_glyph->u.cmp.automatic))
3839 s->background_filled_p = 1;
3841 ns_maybe_dumpglyphs_background
3842 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3844 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3846 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3847 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3848 NS_FACE_FOREGROUND (s->face) = tmp;
3852 BOOL isComposite = s->first_glyph->type == COMPOSITE_GLYPH;
3855 ns_draw_composite_glyph_string_foreground (s);
3857 ns_draw_glyph_string_foreground (s);
3861 NSColor *col = (NS_FACE_FOREGROUND (s->face) != 0
3862 ? ns_lookup_indexed_color (NS_FACE_FOREGROUND (s->face),
3864 : FRAME_FOREGROUND_COLOR (s->f));
3867 /* Draw underline, overline, strike-through. */
3868 ns_draw_text_decoration (s, s->face, col, s->width, s->x);
3871 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3873 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3874 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3875 NS_FACE_FOREGROUND (s->face) = tmp;
3881 case GLYPHLESS_GLYPH:
3882 n = ns_get_glyph_string_clip_rect (s, r);
3883 ns_focus (s->f, r, n);
3885 if (s->for_overlaps || (s->cmp_from > 0
3886 && ! s->first_glyph->u.cmp.automatic))
3887 s->background_filled_p = 1;
3889 ns_maybe_dumpglyphs_background
3890 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3892 /* Not yet implemented. */
3901 /* Draw box if not done already. */
3902 if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3904 n = ns_get_glyph_string_clip_rect (s, r);
3905 ns_focus (s->f, r, n);
3906 ns_dumpglyphs_box_or_relief (s);
3915 /* ==========================================================================
3919 ========================================================================== */
3923 ns_send_appdefined (int value)
3924 /* --------------------------------------------------------------------------
3925 Internal: post an appdefined event which EmacsApp-sendEvent will
3926 recognize and take as a command to halt the event loop.
3927 -------------------------------------------------------------------------- */
3929 NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_send_appdefined(%d)", value);
3931 // GNUstep needs postEvent to happen on the main thread.
3932 // Cocoa needs nextEventMatchingMask to happen on the main thread too.
3933 if (! [[NSThread currentThread] isMainThread])
3935 EmacsApp *app = (EmacsApp *)NSApp;
3936 app->nextappdefined = value;
3937 [app performSelectorOnMainThread:@selector (sendFromMainThread:)
3943 /* Only post this event if we haven't already posted one. This will end
3944 the [NXApp run] main loop after having processed all events queued at
3947 #ifdef NS_IMPL_COCOA
3948 if (! send_appdefined)
3950 /* OSX 10.10.1 swallows the AppDefined event we are sending ourselves
3951 in certain situations (rapid incoming events).
3952 So check if we have one, if not add one. */
3953 NSEvent *appev = [NSApp nextEventMatchingMask:NSEventMaskApplicationDefined
3954 untilDate:[NSDate distantPast]
3955 inMode:NSDefaultRunLoopMode
3957 if (! appev) send_appdefined = YES;
3961 if (send_appdefined)
3965 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
3966 send_appdefined = NO;
3968 /* Don't need wakeup timer any more */
3971 [timed_entry invalidate];
3972 [timed_entry release];
3976 nxev = [NSEvent otherEventWithType: NSEventTypeApplicationDefined
3977 location: NSMakePoint (0, 0)
3980 windowNumber: [[NSApp mainWindow] windowNumber]
3981 context: [NSApp context]
3986 /* Post an application defined event on the event queue. When this is
3987 received the [NXApp run] will return, thus having processed all
3988 events which are currently queued. */
3989 [NSApp postEvent: nxev atStart: NO];
3993 #ifdef HAVE_NATIVE_FS
3997 Lisp_Object frame, tail;
3999 if (ns_last_use_native_fullscreen == ns_use_native_fullscreen)
4002 ns_last_use_native_fullscreen = ns_use_native_fullscreen;
4004 FOR_EACH_FRAME (tail, frame)
4006 struct frame *f = XFRAME (frame);
4009 EmacsView *view = FRAME_NS_VIEW (f);
4010 [view updateCollectionBehavior];
4016 /* GNUstep does not have cancelTracking. */
4017 #ifdef NS_IMPL_COCOA
4018 /* Check if menu open should be canceled or continued as normal. */
4020 ns_check_menu_open (NSMenu *menu)
4022 /* Click in menu bar? */
4023 NSArray *a = [[NSApp mainMenu] itemArray];
4027 if (menu == nil) // Menu tracking ended.
4029 if (menu_will_open_state == MENU_OPENING)
4030 menu_will_open_state = MENU_NONE;
4034 for (i = 0; ! found && i < [a count]; i++)
4035 found = menu == [[a objectAtIndex:i] submenu];
4038 if (menu_will_open_state == MENU_NONE && emacs_event)
4040 NSEvent *theEvent = [NSApp currentEvent];
4041 struct frame *emacsframe = SELECTED_FRAME ();
4043 [menu cancelTracking];
4044 menu_will_open_state = MENU_PENDING;
4045 emacs_event->kind = MENU_BAR_ACTIVATE_EVENT;
4046 EV_TRAILER (theEvent);
4048 CGEventRef ourEvent = CGEventCreate (NULL);
4049 menu_mouse_point = CGEventGetLocation (ourEvent);
4050 CFRelease (ourEvent);
4052 else if (menu_will_open_state == MENU_OPENING)
4054 menu_will_open_state = MENU_NONE;
4059 /* Redo saved menu click if state is MENU_PENDING. */
4061 ns_check_pending_open_menu ()
4063 if (menu_will_open_state == MENU_PENDING)
4065 CGEventSourceRef source
4066 = CGEventSourceCreate (kCGEventSourceStateHIDSystemState);
4068 CGEventRef event = CGEventCreateMouseEvent (source,
4069 kCGEventLeftMouseDown,
4071 kCGMouseButtonLeft);
4072 CGEventSetType (event, kCGEventLeftMouseDown);
4073 CGEventPost (kCGHIDEventTap, event);
4077 menu_will_open_state = MENU_OPENING;
4080 #endif /* NS_IMPL_COCOA */
4083 unwind_apploopnr (Lisp_Object not_used)
4086 n_emacs_events_pending = 0;
4087 ns_finish_events ();
4092 ns_read_socket (struct terminal *terminal, struct input_event *hold_quit)
4093 /* --------------------------------------------------------------------------
4094 External (hook): Post an event to ourself and keep reading events until
4095 we read it back again. In effect process all events which were waiting.
4096 From 21+ we have to manage the event buffer ourselves.
4097 -------------------------------------------------------------------------- */
4099 struct input_event ev;
4102 NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_read_socket");
4105 return -1; /* Already within event loop. */
4107 #ifdef HAVE_NATIVE_FS
4111 if ([NSApp modalWindow] != nil)
4114 if (hold_event_q.nr > 0)
4117 for (i = 0; i < hold_event_q.nr; ++i)
4118 kbd_buffer_store_event_hold (&hold_event_q.q[i], hold_quit);
4119 hold_event_q.nr = 0;
4124 n_emacs_events_pending = 0;
4125 ns_init_events (&ev);
4126 q_event_ptr = hold_quit;
4128 /* we manage autorelease pools by allocate/reallocate each time around
4129 the loop; strict nesting is occasionally violated but seems not to
4130 matter.. earlier methods using full nesting caused major memory leaks */
4131 [outerpool release];
4132 outerpool = [[NSAutoreleasePool alloc] init];
4134 /* If have pending open-file requests, attend to the next one of those. */
4135 if (ns_pending_files && [ns_pending_files count] != 0
4136 && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
4138 [ns_pending_files removeObjectAtIndex: 0];
4140 /* Deal with pending service requests. */
4141 else if (ns_pending_service_names && [ns_pending_service_names count] != 0
4143 NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
4144 withArg: [ns_pending_service_args objectAtIndex: 0]])
4146 [ns_pending_service_names removeObjectAtIndex: 0];
4147 [ns_pending_service_args removeObjectAtIndex: 0];
4151 ptrdiff_t specpdl_count = SPECPDL_INDEX ();
4152 /* Run and wait for events. We must always send one NX_APPDEFINED event
4153 to ourself, otherwise [NXApp run] will never exit. */
4154 send_appdefined = YES;
4155 ns_send_appdefined (-1);
4157 if (++apploopnr != 1)
4161 record_unwind_protect (unwind_apploopnr, Qt);
4163 unbind_to (specpdl_count, Qnil); /* calls unwind_apploopnr */
4166 nevents = n_emacs_events_pending;
4167 n_emacs_events_pending = 0;
4168 ns_finish_events ();
4177 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
4178 fd_set *exceptfds, struct timespec const *timeout,
4179 sigset_t const *sigmask)
4180 /* --------------------------------------------------------------------------
4181 Replacement for select, checking for events
4182 -------------------------------------------------------------------------- */
4186 struct input_event event;
4189 NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_select");
4192 return -1; /* Already within event loop. */
4194 #ifdef HAVE_NATIVE_FS
4198 if (hold_event_q.nr > 0)
4200 /* We already have events pending. */
4206 for (k = 0; k < nfds+1; k++)
4208 if (readfds && FD_ISSET(k, readfds)) ++nr;
4209 if (writefds && FD_ISSET(k, writefds)) ++nr;
4213 || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0))
4214 return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
4216 [outerpool release];
4217 outerpool = [[NSAutoreleasePool alloc] init];
4220 send_appdefined = YES;
4223 pthread_mutex_lock (&select_mutex);
4228 select_readfds = *readfds;
4229 select_valid += SELECT_HAVE_READ;
4233 select_writefds = *writefds;
4234 select_valid += SELECT_HAVE_WRITE;
4239 select_timeout = *timeout;
4240 select_valid += SELECT_HAVE_TMO;
4243 pthread_mutex_unlock (&select_mutex);
4245 /* Inform fd_handler that select should be called */
4247 emacs_write_sig (selfds[1], &c, 1);
4249 else if (nr == 0 && timeout)
4251 /* No file descriptor, just a timeout, no need to wake fd_handler */
4252 double time = timespectod (*timeout);
4253 timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
4256 @selector (timeout_handler:)
4261 else /* No timeout and no file descriptors, can this happen? */
4263 /* Send appdefined so we exit from the loop */
4264 ns_send_appdefined (-1);
4268 ns_init_events (&event);
4269 if (++apploopnr != 1)
4275 ptrdiff_t specpdl_count = SPECPDL_INDEX ();
4276 record_unwind_protect (unwind_apploopnr, Qt);
4278 unbind_to (specpdl_count, Qnil); /* calls unwind_apploopnr */
4281 ns_finish_events ();
4282 if (nr > 0 && readfds)
4285 emacs_write_sig (selfds[1], &c, 1);
4289 t = last_appdefined_event_data;
4291 if (t != NO_APPDEFINED_DATA)
4293 last_appdefined_event_data = NO_APPDEFINED_DATA;
4297 /* The NX_APPDEFINED event we received was a timeout. */
4302 /* The NX_APPDEFINED event we received was the result of
4303 at least one real input event arriving. */
4309 /* Received back from select () in fd_handler; copy the results */
4310 pthread_mutex_lock (&select_mutex);
4311 if (readfds) *readfds = select_readfds;
4312 if (writefds) *writefds = select_writefds;
4313 pthread_mutex_unlock (&select_mutex);
4328 /* ==========================================================================
4332 ========================================================================== */
4336 ns_set_vertical_scroll_bar (struct window *window,
4337 int portion, int whole, int position)
4338 /* --------------------------------------------------------------------------
4339 External (hook): Update or add scrollbar
4340 -------------------------------------------------------------------------- */
4344 struct frame *f = XFRAME (WINDOW_FRAME (window));
4345 EmacsView *view = FRAME_NS_VIEW (f);
4347 int window_y, window_height;
4348 int top, left, height, width;
4349 BOOL update_p = YES;
4351 /* optimization; display engine sends WAY too many of these.. */
4352 if (!NILP (window->vertical_scroll_bar))
4354 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4355 if ([bar checkSamePosition: position portion: portion whole: whole])
4357 if (view->scrollbarsNeedingUpdate == 0)
4359 if (!windows_or_buffers_changed)
4363 view->scrollbarsNeedingUpdate--;
4368 NSTRACE ("ns_set_vertical_scroll_bar");
4370 /* Get dimensions. */
4371 window_box (window, ANY_AREA, 0, &window_y, 0, &window_height);
4373 height = window_height;
4374 width = NS_SCROLL_BAR_WIDTH (f);
4375 left = WINDOW_SCROLL_BAR_AREA_X (window);
4377 r = NSMakeRect (left, top, width, height);
4378 /* the parent view is flipped, so we need to flip y value */
4380 r.origin.y = (v.size.height - r.size.height - r.origin.y);
4382 XSETWINDOW (win, window);
4385 /* we want at least 5 lines to display a scrollbar */
4386 if (WINDOW_TOTAL_LINES (window) < 5)
4388 if (!NILP (window->vertical_scroll_bar))
4390 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4391 [bar removeFromSuperview];
4392 wset_vertical_scroll_bar (window, Qnil);
4395 ns_clear_frame_area (f, left, top, width, height);
4400 if (NILP (window->vertical_scroll_bar))
4402 if (width > 0 && height > 0)
4403 ns_clear_frame_area (f, left, top, width, height);
4405 bar = [[EmacsScroller alloc] initFrame: r window: win];
4406 wset_vertical_scroll_bar (window, make_save_ptr (bar));
4412 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4413 oldRect = [bar frame];
4414 r.size.width = oldRect.size.width;
4415 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4417 if (oldRect.origin.x != r.origin.x)
4418 ns_clear_frame_area (f, left, top, width, height);
4424 [bar setPosition: position portion: portion whole: whole];
4430 ns_set_horizontal_scroll_bar (struct window *window,
4431 int portion, int whole, int position)
4432 /* --------------------------------------------------------------------------
4433 External (hook): Update or add scrollbar
4434 -------------------------------------------------------------------------- */
4438 struct frame *f = XFRAME (WINDOW_FRAME (window));
4439 EmacsView *view = FRAME_NS_VIEW (f);
4441 int top, height, left, width;
4442 int window_x, window_width;
4443 BOOL update_p = YES;
4445 /* optimization; display engine sends WAY too many of these.. */
4446 if (!NILP (window->horizontal_scroll_bar))
4448 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4449 if ([bar checkSamePosition: position portion: portion whole: whole])
4451 if (view->scrollbarsNeedingUpdate == 0)
4453 if (!windows_or_buffers_changed)
4457 view->scrollbarsNeedingUpdate--;
4462 NSTRACE ("ns_set_horizontal_scroll_bar");
4464 /* Get dimensions. */
4465 window_box (window, ANY_AREA, &window_x, 0, &window_width, 0);
4467 width = window_width;
4468 height = NS_SCROLL_BAR_HEIGHT (f);
4469 top = WINDOW_SCROLL_BAR_AREA_Y (window);
4471 r = NSMakeRect (left, top, width, height);
4472 /* the parent view is flipped, so we need to flip y value */
4474 r.origin.y = (v.size.height - r.size.height - r.origin.y);
4476 XSETWINDOW (win, window);
4479 if (NILP (window->horizontal_scroll_bar))
4481 if (width > 0 && height > 0)
4482 ns_clear_frame_area (f, left, top, width, height);
4484 bar = [[EmacsScroller alloc] initFrame: r window: win];
4485 wset_horizontal_scroll_bar (window, make_save_ptr (bar));
4491 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4492 oldRect = [bar frame];
4493 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4495 if (oldRect.origin.y != r.origin.y)
4496 ns_clear_frame_area (f, left, top, width, height);
4502 /* If there are both horizontal and vertical scroll-bars they leave
4503 a square that belongs to neither. We need to clear it otherwise
4504 it fills with junk. */
4505 if (!NILP (window->vertical_scroll_bar))
4506 ns_clear_frame_area (f, WINDOW_SCROLL_BAR_AREA_X (window), top,
4507 NS_SCROLL_BAR_HEIGHT (f), height);
4510 [bar setPosition: position portion: portion whole: whole];
4516 ns_condemn_scroll_bars (struct frame *f)
4517 /* --------------------------------------------------------------------------
4518 External (hook): arrange for all frame's scrollbars to be removed
4519 at next call to judge_scroll_bars, except for those redeemed.
4520 -------------------------------------------------------------------------- */
4524 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
4526 NSTRACE ("ns_condemn_scroll_bars");
4528 for (i =[subviews count]-1; i >= 0; i--)
4530 view = [subviews objectAtIndex: i];
4531 if ([view isKindOfClass: [EmacsScroller class]])
4538 ns_redeem_scroll_bar (struct window *window)
4539 /* --------------------------------------------------------------------------
4540 External (hook): arrange to spare this window's scrollbar
4541 at next call to judge_scroll_bars.
4542 -------------------------------------------------------------------------- */
4545 NSTRACE ("ns_redeem_scroll_bar");
4546 if (!NILP (window->vertical_scroll_bar)
4547 && WINDOW_HAS_VERTICAL_SCROLL_BAR (window))
4549 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4553 if (!NILP (window->horizontal_scroll_bar)
4554 && WINDOW_HAS_HORIZONTAL_SCROLL_BAR (window))
4556 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4563 ns_judge_scroll_bars (struct frame *f)
4564 /* --------------------------------------------------------------------------
4565 External (hook): destroy all scrollbars on frame that weren't
4566 redeemed after call to condemn_scroll_bars.
4567 -------------------------------------------------------------------------- */
4571 EmacsView *eview = FRAME_NS_VIEW (f);
4572 NSArray *subviews = [[eview superview] subviews];
4575 NSTRACE ("ns_judge_scroll_bars");
4576 for (i = [subviews count]-1; i >= 0; --i)
4578 view = [subviews objectAtIndex: i];
4579 if (![view isKindOfClass: [EmacsScroller class]]) continue;
4585 [eview updateFrameSize: NO];
4588 /* ==========================================================================
4592 ========================================================================== */
4595 x_display_pixel_height (struct ns_display_info *dpyinfo)
4597 NSArray *screens = [NSScreen screens];
4598 NSEnumerator *enumerator = [screens objectEnumerator];
4603 while ((screen = [enumerator nextObject]) != nil)
4604 frame = NSUnionRect (frame, [screen frame]);
4606 return NSHeight (frame);
4610 x_display_pixel_width (struct ns_display_info *dpyinfo)
4612 NSArray *screens = [NSScreen screens];
4613 NSEnumerator *enumerator = [screens objectEnumerator];
4618 while ((screen = [enumerator nextObject]) != nil)
4619 frame = NSUnionRect (frame, [screen frame]);
4621 return NSWidth (frame);
4625 static Lisp_Object ns_string_to_lispmod (const char *s)
4626 /* --------------------------------------------------------------------------
4627 Convert modifier name to lisp symbol
4628 -------------------------------------------------------------------------- */
4630 if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
4632 else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
4634 else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
4636 else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
4638 else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
4640 else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
4648 ns_default (const char *parameter, Lisp_Object *result,
4649 Lisp_Object yesval, Lisp_Object noval,
4650 BOOL is_float, BOOL is_modstring)
4651 /* --------------------------------------------------------------------------
4652 Check a parameter value in user's preferences
4653 -------------------------------------------------------------------------- */
4655 const char *value = ns_get_defaults_value (parameter);
4661 if (c_strcasecmp (value, "YES") == 0)
4663 else if (c_strcasecmp (value, "NO") == 0)
4665 else if (is_float && (f = strtod (value, &pos), pos != value))
4666 *result = make_float (f);
4667 else if (is_modstring && value)
4668 *result = ns_string_to_lispmod (value);
4669 else fprintf (stderr,
4670 "Bad value for default \"%s\": \"%s\"\n", parameter, value);
4676 ns_initialize_display_info (struct ns_display_info *dpyinfo)
4677 /* --------------------------------------------------------------------------
4678 Initialize global info and storage for display.
4679 -------------------------------------------------------------------------- */
4681 NSScreen *screen = [NSScreen mainScreen];
4682 NSWindowDepth depth = [screen depth];
4684 dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
4685 dpyinfo->resy = 72.27;
4686 dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
4687 NSColorSpaceFromDepth (depth)]
4688 && ![NSCalibratedWhiteColorSpace isEqualToString:
4689 NSColorSpaceFromDepth (depth)];
4690 dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
4691 dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
4692 dpyinfo->color_table->colors = NULL;
4693 dpyinfo->root_window = 42; /* a placeholder.. */
4694 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
4695 dpyinfo->n_fonts = 0;
4696 dpyinfo->smallest_font_height = 1;
4697 dpyinfo->smallest_char_width = 1;
4699 reset_mouse_highlight (&dpyinfo->mouse_highlight);
4703 /* This and next define (many of the) public functions in this file. */
4704 /* x_... are generic versions in xdisp.c that we, and other terms, get away
4705 with using despite presence in the "system dependent" redisplay
4706 interface. In addition, many of the ns_ methods have code that is
4707 shared with all terms, indicating need for further refactoring. */
4708 extern frame_parm_handler ns_frame_parm_handlers[];
4709 static struct redisplay_interface ns_redisplay_interface =
4711 ns_frame_parm_handlers,
4715 x_clear_end_of_line,
4717 ns_after_update_window_line,
4718 ns_update_window_begin,
4719 ns_update_window_end,
4720 0, /* flush_display */
4721 x_clear_window_mouse_face,
4722 x_get_glyph_overhangs,
4723 x_fix_overlapping_area,
4724 ns_draw_fringe_bitmap,
4725 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
4726 0, /* destroy_fringe_bitmap */
4727 ns_compute_glyph_string_overhangs,
4728 ns_draw_glyph_string,
4729 ns_define_frame_cursor,
4730 ns_clear_frame_area,
4731 ns_draw_window_cursor,
4732 ns_draw_vertical_window_border,
4733 ns_draw_window_divider,
4734 ns_shift_glyphs_for_insert,
4741 ns_delete_display (struct ns_display_info *dpyinfo)
4747 /* This function is called when the last frame on a display is deleted. */
4749 ns_delete_terminal (struct terminal *terminal)
4751 struct ns_display_info *dpyinfo = terminal->display_info.ns;
4753 NSTRACE ("ns_delete_terminal");
4755 /* Protect against recursive calls. delete_frame in
4756 delete_terminal calls us back when it deletes our last frame. */
4757 if (!terminal->name)
4762 x_destroy_all_bitmaps (dpyinfo);
4763 ns_delete_display (dpyinfo);
4768 static struct terminal *
4769 ns_create_terminal (struct ns_display_info *dpyinfo)
4770 /* --------------------------------------------------------------------------
4771 Set up use of NS before we make the first connection.
4772 -------------------------------------------------------------------------- */
4774 struct terminal *terminal;
4776 NSTRACE ("ns_create_terminal");
4778 terminal = create_terminal (output_ns, &ns_redisplay_interface);
4780 terminal->display_info.ns = dpyinfo;
4781 dpyinfo->terminal = terminal;
4783 terminal->clear_frame_hook = ns_clear_frame;
4784 terminal->ring_bell_hook = ns_ring_bell;
4785 terminal->update_begin_hook = ns_update_begin;
4786 terminal->update_end_hook = ns_update_end;
4787 terminal->read_socket_hook = ns_read_socket;
4788 terminal->frame_up_to_date_hook = ns_frame_up_to_date;
4789 terminal->mouse_position_hook = ns_mouse_position;
4790 terminal->frame_rehighlight_hook = ns_frame_rehighlight;
4791 terminal->frame_raise_lower_hook = ns_frame_raise_lower;
4792 terminal->fullscreen_hook = ns_fullscreen_hook;
4793 terminal->menu_show_hook = ns_menu_show;
4794 terminal->popup_dialog_hook = ns_popup_dialog;
4795 terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
4796 terminal->set_horizontal_scroll_bar_hook = ns_set_horizontal_scroll_bar;
4797 terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
4798 terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
4799 terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
4800 terminal->delete_frame_hook = x_destroy_window;
4801 terminal->delete_terminal_hook = ns_delete_terminal;
4802 /* Other hooks are NULL by default. */
4808 struct ns_display_info *
4809 ns_term_init (Lisp_Object display_name)
4810 /* --------------------------------------------------------------------------
4811 Start the Application and get things rolling.
4812 -------------------------------------------------------------------------- */
4814 struct terminal *terminal;
4815 struct ns_display_info *dpyinfo;
4816 static int ns_initialized = 0;
4819 if (ns_initialized) return x_display_list;
4824 NSTRACE ("ns_term_init");
4826 [outerpool release];
4827 outerpool = [[NSAutoreleasePool alloc] init];
4829 /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4830 /*GSDebugAllocationActive (YES); */
4834 Fset_input_interrupt_mode (Qnil);
4836 if (selfds[0] == -1)
4838 if (emacs_pipe (selfds) != 0)
4840 fprintf (stderr, "Failed to create pipe: %s\n",
4841 emacs_strerror (errno));
4845 fcntl (selfds[0], F_SETFL, O_NONBLOCK|fcntl (selfds[0], F_GETFL));
4846 FD_ZERO (&select_readfds);
4847 FD_ZERO (&select_writefds);
4848 pthread_mutex_init (&select_mutex, NULL);
4851 ns_pending_files = [[NSMutableArray alloc] init];
4852 ns_pending_service_names = [[NSMutableArray alloc] init];
4853 ns_pending_service_args = [[NSMutableArray alloc] init];
4855 /* Start app and create the main menu, window, view.
4856 Needs to be here because ns_initialize_display_info () uses AppKit classes.
4857 The view will then ask the NSApp to stop and return to Emacs. */
4858 [EmacsApp sharedApplication];
4861 [NSApp setDelegate: NSApp];
4863 /* Start the select thread. */
4864 [NSThread detachNewThreadSelector:@selector (fd_handler:)
4868 /* debugging: log all notifications */
4869 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
4870 selector: @selector (logNotification:)
4871 name: nil object: nil]; */
4873 dpyinfo = xzalloc (sizeof *dpyinfo);
4875 ns_initialize_display_info (dpyinfo);
4876 terminal = ns_create_terminal (dpyinfo);
4878 terminal->kboard = allocate_kboard (Qns);
4879 /* Don't let the initial kboard remain current longer than necessary.
4880 That would cause problems if a file loaded on startup tries to
4881 prompt in the mini-buffer. */
4882 if (current_kboard == initial_kboard)
4883 current_kboard = terminal->kboard;
4884 terminal->kboard->reference_count++;
4886 dpyinfo->next = x_display_list;
4887 x_display_list = dpyinfo;
4889 dpyinfo->name_list_element = Fcons (display_name, Qnil);
4891 terminal->name = xlispstrdup (display_name);
4895 if (!inhibit_x_resources)
4897 ns_default ("GSFontAntiAlias", &ns_antialias_text,
4900 /* this is a standard variable */
4901 ns_default ("AppleAntiAliasingThreshold", &tmp,
4902 make_float (10.0), make_float (6.0), YES, NO);
4903 ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4906 NSTRACE_MSG ("Colors");
4909 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4913 Lisp_Object color_file, color_map, color;
4917 color_file = Fexpand_file_name (build_string ("rgb.txt"),
4918 Fsymbol_value (intern ("data-directory")));
4920 color_map = Fx_load_color_file (color_file);
4921 if (NILP (color_map))
4922 fatal ("Could not read %s.\n", SDATA (color_file));
4924 cl = [[NSColorList alloc] initWithName: @"Emacs"];
4925 for ( ; CONSP (color_map); color_map = XCDR (color_map))
4927 color = XCAR (color_map);
4928 name = SSDATA (XCAR (color));
4929 c = XINT (XCDR (color));
4931 [NSColor colorForEmacsRed: RED_FROM_ULONG (c) / 255.0
4932 green: GREEN_FROM_ULONG (c) / 255.0
4933 blue: BLUE_FROM_ULONG (c) / 255.0
4935 forKey: [NSString stringWithUTF8String: name]];
4937 [cl writeToFile: nil];
4941 NSTRACE_MSG ("Versions");
4944 #ifdef NS_IMPL_GNUSTEP
4945 Vwindow_system_version = build_string (gnustep_base_version);
4947 /*PSnextrelease (128, c); */
4948 char c[DBL_BUFSIZE_BOUND];
4949 int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4950 Vwindow_system_version = make_unibyte_string (c, len);
4954 delete_keyboard_wait_descriptor (0);
4956 ns_app_name = [[NSProcessInfo processInfo] processName];
4958 /* Set up OS X app menu */
4960 NSTRACE_MSG ("Menu init");
4962 #ifdef NS_IMPL_COCOA
4966 /* set up the application menu */
4967 svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4968 [svcsMenu setAutoenablesItems: NO];
4969 appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4970 [appMenu setAutoenablesItems: NO];
4971 mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4972 dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4974 [appMenu insertItemWithTitle: @"About Emacs"
4975 action: @selector (orderFrontStandardAboutPanel:)
4978 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4979 [appMenu insertItemWithTitle: @"Preferences..."
4980 action: @selector (showPreferencesWindow:)
4983 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4984 item = [appMenu insertItemWithTitle: @"Services"
4985 action: @selector (menuDown:)
4988 [appMenu setSubmenu: svcsMenu forItem: item];
4989 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4990 [appMenu insertItemWithTitle: @"Hide Emacs"
4991 action: @selector (hide:)
4994 item = [appMenu insertItemWithTitle: @"Hide Others"
4995 action: @selector (hideOtherApplications:)
4998 [item setKeyEquivalentModifierMask: NSEventModifierFlagCommand | NSEventModifierFlagOption];
4999 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
5000 [appMenu insertItemWithTitle: @"Quit Emacs"
5001 action: @selector (terminate:)
5005 item = [mainMenu insertItemWithTitle: ns_app_name
5006 action: @selector (menuDown:)
5009 [mainMenu setSubmenu: appMenu forItem: item];
5010 [dockMenu insertItemWithTitle: @"New Frame"
5011 action: @selector (newFrame:)
5015 [NSApp setMainMenu: mainMenu];
5016 [NSApp setAppleMenu: appMenu];
5017 [NSApp setServicesMenu: svcsMenu];
5018 /* Needed at least on Cocoa, to get dock menu to show windows */
5019 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
5021 [[NSNotificationCenter defaultCenter]
5022 addObserver: mainMenu
5023 selector: @selector (trackingNotification:)
5024 name: NSMenuDidBeginTrackingNotification object: mainMenu];
5025 [[NSNotificationCenter defaultCenter]
5026 addObserver: mainMenu
5027 selector: @selector (trackingNotification:)
5028 name: NSMenuDidEndTrackingNotification object: mainMenu];
5030 #endif /* MAC OS X menu setup */
5032 /* Register our external input/output types, used for determining
5033 applicable services and also drag/drop eligibility. */
5035 NSTRACE_MSG ("Input/output types");
5037 ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
5038 ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
5040 ns_drag_types = [[NSArray arrayWithObjects:
5042 NSTabularTextPboardType,
5043 NSFilenamesPboardType,
5044 NSURLPboardType, nil] retain];
5046 /* If fullscreen is in init/default-frame-alist, focus isn't set
5047 right for fullscreen windows, so set this. */
5048 [NSApp activateIgnoringOtherApps:YES];
5050 NSTRACE_MSG ("Call NSApp run");
5053 ns_do_open_file = YES;
5055 #ifdef NS_IMPL_GNUSTEP
5056 /* GNUstep steals SIGCHLD for use in NSTask, but we don't use NSTask.
5057 We must re-catch it so subprocess works. */
5058 catch_child_signal ();
5061 NSTRACE_MSG ("ns_term_init done");
5070 ns_term_shutdown (int sig)
5072 [[NSUserDefaults standardUserDefaults] synchronize];
5074 /* code not reached in emacs.c after this is called by shut_down_emacs: */
5075 if (STRINGP (Vauto_save_list_file_name))
5076 unlink (SSDATA (Vauto_save_list_file_name));
5078 if (sig == 0 || sig == SIGTERM)
5080 [NSApp terminate: NSApp];
5082 else // force a stack trace to happen
5089 /* ==========================================================================
5091 EmacsApp implementation
5093 ========================================================================== */
5096 @implementation EmacsApp
5100 NSTRACE ("[EmacsApp init]");
5102 if ((self = [super init]))
5104 #ifdef NS_IMPL_COCOA
5105 self->isFirst = YES;
5107 #ifdef NS_IMPL_GNUSTEP
5108 self->applicationDidFinishLaunchingCalled = NO;
5115 #ifdef NS_IMPL_COCOA
5118 NSTRACE ("[EmacsApp run]");
5120 #ifndef NSAppKitVersionNumber10_9
5121 #define NSAppKitVersionNumber10_9 1265
5124 if ((int)NSAppKitVersionNumber != NSAppKitVersionNumber10_9)
5130 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
5132 if (isFirst) [self finishLaunching];
5135 shouldKeepRunning = YES;
5139 pool = [[NSAutoreleasePool alloc] init];
5142 [self nextEventMatchingMask:NSEventMaskAny
5143 untilDate:[NSDate distantFuture]
5144 inMode:NSDefaultRunLoopMode
5147 [self sendEvent:event];
5148 [self updateWindows];
5149 } while (shouldKeepRunning);
5154 - (void)stop: (id)sender
5156 NSTRACE ("[EmacsApp stop:]");
5158 shouldKeepRunning = NO;
5159 // Stop possible dialog also. Noop if no dialog present.
5160 // The file dialog still leaks 7k - 10k on 10.9 though.
5161 [super stop:sender];
5163 #endif /* NS_IMPL_COCOA */
5165 - (void)logNotification: (NSNotification *)notification
5167 NSTRACE ("[EmacsApp logNotification:]");
5169 const char *name = [[notification name] UTF8String];
5170 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
5171 && !strstr (name, "WindowNumber"))
5172 NSLog (@"notification: '%@'", [notification name]);
5176 - (void)sendEvent: (NSEvent *)theEvent
5177 /* --------------------------------------------------------------------------
5178 Called when NSApp is running for each event received. Used to stop
5179 the loop when we choose, since there's no way to just run one iteration.
5180 -------------------------------------------------------------------------- */
5182 int type = [theEvent type];
5183 NSWindow *window = [theEvent window];
5185 NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "[EmacsApp sendEvent:]");
5186 NSTRACE_MSG ("Type: %d", type);
5188 #ifdef NS_IMPL_GNUSTEP
5189 // Keyboard events aren't propagated to file dialogs for some reason.
5190 if ([NSApp modalWindow] != nil &&
5191 (type == NSEventTypeKeyDown || type == NSEventTypeKeyUp || type == NSEventTypeFlagsChanged))
5193 [[NSApp modalWindow] sendEvent: theEvent];
5198 if (represented_filename != nil && represented_frame)
5200 NSString *fstr = represented_filename;
5201 NSView *view = FRAME_NS_VIEW (represented_frame);
5202 #ifdef NS_IMPL_COCOA
5203 /* work around a bug observed on 10.3 and later where
5204 setTitleWithRepresentedFilename does not clear out previous state
5205 if given filename does not exist */
5206 if (! [[NSFileManager defaultManager] fileExistsAtPath: fstr])
5207 [[view window] setRepresentedFilename: @""];
5209 [[view window] setRepresentedFilename: fstr];
5210 [represented_filename release];
5211 represented_filename = nil;
5212 represented_frame = NULL;
5215 if (type == NSEventTypeApplicationDefined)
5217 switch ([theEvent data2])
5219 #ifdef NS_IMPL_COCOA
5220 case NSAPP_DATA2_RUNASSCRIPT:
5225 case NSAPP_DATA2_RUNFILEDIALOG:
5226 ns_run_file_dialog ();
5232 if (type == NSEventTypeCursorUpdate && window == nil)
5234 fprintf (stderr, "Dropping external cursor update event.\n");
5238 if (type == NSEventTypeApplicationDefined)
5240 /* Events posted by ns_send_appdefined interrupt the run loop here.
5241 But, if a modal window is up, an appdefined can still come through,
5242 (e.g., from a makeKeyWindow event) but stopping self also stops the
5243 modal loop. Just defer it until later. */
5244 if ([NSApp modalWindow] == nil)
5246 last_appdefined_event_data = [theEvent data1];
5251 send_appdefined = YES;
5256 #ifdef NS_IMPL_COCOA
5257 /* If no dialog and none of our frames have focus and it is a move, skip it.
5258 It is a mouse move in an auxiliary menu, i.e. on the top right on OSX,
5259 such as Wifi, sound, date or similar.
5260 This prevents "spooky" highlighting in the frame under the menu. */
5261 if (type == NSEventTypeMouseMoved && [NSApp modalWindow] == nil)
5263 struct ns_display_info *di;
5264 BOOL has_focus = NO;
5265 for (di = x_display_list; ! has_focus && di; di = di->next)
5266 has_focus = di->x_focus_frame != 0;
5272 NSTRACE_UNSILENCE();
5274 [super sendEvent: theEvent];
5278 - (void)showPreferencesWindow: (id)sender
5280 struct frame *emacsframe = SELECTED_FRAME ();
5281 NSEvent *theEvent = [NSApp currentEvent];
5285 emacs_event->kind = NS_NONKEY_EVENT;
5286 emacs_event->code = KEY_NS_SHOW_PREFS;
5287 emacs_event->modifiers = 0;
5288 EV_TRAILER (theEvent);
5292 - (void)newFrame: (id)sender
5294 NSTRACE ("[EmacsApp newFrame:]");
5296 struct frame *emacsframe = SELECTED_FRAME ();
5297 NSEvent *theEvent = [NSApp currentEvent];
5301 emacs_event->kind = NS_NONKEY_EVENT;
5302 emacs_event->code = KEY_NS_NEW_FRAME;
5303 emacs_event->modifiers = 0;
5304 EV_TRAILER (theEvent);
5308 /* Open a file (used by below, after going into queue read by ns_read_socket) */
5309 - (BOOL) openFile: (NSString *)fileName
5311 NSTRACE ("[EmacsApp openFile:]");
5313 struct frame *emacsframe = SELECTED_FRAME ();
5314 NSEvent *theEvent = [NSApp currentEvent];
5319 emacs_event->kind = NS_NONKEY_EVENT;
5320 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
5321 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
5322 ns_input_line = Qnil; /* can be start or cons start,end */
5323 emacs_event->modifiers =0;
5324 EV_TRAILER (theEvent);
5330 /* **************************************************************************
5332 EmacsApp delegate implementation
5334 ************************************************************************** */
5336 - (void)applicationDidFinishLaunching: (NSNotification *)notification
5337 /* --------------------------------------------------------------------------
5338 When application is loaded, terminate event loop in ns_term_init
5339 -------------------------------------------------------------------------- */
5341 NSTRACE ("[EmacsApp applicationDidFinishLaunching:]");
5343 #ifdef NS_IMPL_GNUSTEP
5344 ((EmacsApp *)self)->applicationDidFinishLaunchingCalled = YES;
5346 [NSApp setServicesProvider: NSApp];
5348 [self antialiasThresholdDidChange:nil];
5349 #ifdef NS_IMPL_COCOA
5350 [[NSNotificationCenter defaultCenter]
5352 selector:@selector(antialiasThresholdDidChange:)
5353 name:NSAntialiasThresholdChangedNotification
5357 ns_send_appdefined (-2);
5360 - (void)antialiasThresholdDidChange:(NSNotification *)notification
5362 #ifdef NS_IMPL_COCOA
5363 macfont_update_antialias_threshold ();
5368 /* Termination sequences:
5371 MenuBar | File | Exit:
5372 Select Quit from App menubar:
5374 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5377 Select Quit from Dock menu:
5380 Cancel -> Nothing else
5384 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5389 - (void) terminate: (id)sender
5391 NSTRACE ("[EmacsApp terminate:]");
5393 struct frame *emacsframe = SELECTED_FRAME ();
5398 emacs_event->kind = NS_NONKEY_EVENT;
5399 emacs_event->code = KEY_NS_POWER_OFF;
5400 emacs_event->arg = Qt; /* mark as non-key event */
5401 EV_TRAILER ((id)nil);
5405 runAlertPanel(NSString *title,
5406 NSString *msgFormat,
5407 NSString *defaultButton,
5408 NSString *alternateButton)
5410 #if !defined (NS_IMPL_COCOA) || \
5411 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
5412 return NSRunAlertPanel(title, msgFormat, defaultButton, alternateButton, nil)
5413 == NSAlertDefaultReturn;
5415 NSAlert *alert = [[NSAlert alloc] init];
5416 [alert setAlertStyle: NSAlertStyleCritical];
5417 [alert setMessageText: msgFormat];
5418 [alert addButtonWithTitle: defaultButton];
5419 [alert addButtonWithTitle: alternateButton];
5420 NSInteger ret = [alert runModal];
5422 return ret == NSAlertFirstButtonReturn;
5427 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
5429 NSTRACE ("[EmacsApp applicationShouldTerminate:]");
5433 if (NILP (ns_confirm_quit)) // || ns_shutdown_properly --> TO DO
5434 return NSTerminateNow;
5436 ret = runAlertPanel(ns_app_name,
5437 @"Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?",
5438 @"Save Buffers and Exit", @"Cancel");
5441 return NSTerminateNow;
5443 return NSTerminateCancel;
5444 return NSTerminateNow; /* just in case */
5448 not_in_argv (NSString *arg)
5451 const char *a = [arg UTF8String];
5452 for (k = 1; k < initial_argc; ++k)
5453 if (strcmp (a, initial_argv[k]) == 0) return 0;
5457 /* Notification from the Workspace to open a file */
5458 - (BOOL)application: sender openFile: (NSString *)file
5460 if (ns_do_open_file || not_in_argv (file))
5461 [ns_pending_files addObject: file];
5466 /* Open a file as a temporary file */
5467 - (BOOL)application: sender openTempFile: (NSString *)file
5469 if (ns_do_open_file || not_in_argv (file))
5470 [ns_pending_files addObject: file];
5475 /* Notification from the Workspace to open a file noninteractively (?) */
5476 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
5478 if (ns_do_open_file || not_in_argv (file))
5479 [ns_pending_files addObject: file];
5483 /* Notification from the Workspace to open multiple files */
5484 - (void)application: sender openFiles: (NSArray *)fileList
5486 NSEnumerator *files = [fileList objectEnumerator];
5488 /* Don't open files from the command line unconditionally,
5489 Cocoa parses the command line wrong, --option value tries to open value
5490 if --option is the last option. */
5491 while ((file = [files nextObject]) != nil)
5492 if (ns_do_open_file || not_in_argv (file))
5493 [ns_pending_files addObject: file];
5495 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
5500 /* Handle dock menu requests. */
5501 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
5507 /* TODO: these may help w/IO switching btwn terminal and NSApp */
5508 - (void)applicationWillBecomeActive: (NSNotification *)notification
5510 NSTRACE ("[EmacsApp applicationWillBecomeActive:]");
5511 //ns_app_active=YES;
5514 - (void)applicationDidBecomeActive: (NSNotification *)notification
5516 NSTRACE ("[EmacsApp applicationDidBecomeActive:]");
5518 #ifdef NS_IMPL_GNUSTEP
5519 if (! applicationDidFinishLaunchingCalled)
5520 [self applicationDidFinishLaunching:notification];
5522 //ns_app_active=YES;
5524 ns_update_auto_hide_menu_bar ();
5525 // No constraining takes place when the application is not active.
5526 ns_constrain_all_frames ();
5528 - (void)applicationDidResignActive: (NSNotification *)notification
5530 NSTRACE ("[EmacsApp applicationDidResignActive:]");
5533 ns_send_appdefined (-1);
5538 /* ==========================================================================
5540 EmacsApp aux handlers for managing event loop
5542 ========================================================================== */
5545 - (void)timeout_handler: (NSTimer *)timedEntry
5546 /* --------------------------------------------------------------------------
5547 The timeout specified to ns_select has passed.
5548 -------------------------------------------------------------------------- */
5550 /*NSTRACE ("timeout_handler"); */
5551 ns_send_appdefined (-2);
5554 - (void)sendFromMainThread:(id)unused
5556 ns_send_appdefined (nextappdefined);
5559 - (void)fd_handler:(id)unused
5560 /* --------------------------------------------------------------------------
5561 Check data waiting on file descriptors and terminate if so
5562 -------------------------------------------------------------------------- */
5565 int waiting = 1, nfds;
5568 fd_set readfds, writefds, *wfds;
5569 struct timespec timeout, *tmo;
5570 NSAutoreleasePool *pool = nil;
5572 /* NSTRACE ("fd_handler"); */
5577 pool = [[NSAutoreleasePool alloc] init];
5583 FD_SET (selfds[0], &fds);
5584 result = select (selfds[0]+1, &fds, NULL, NULL, NULL);
5585 if (result > 0 && read (selfds[0], &c, 1) == 1 && c == 'g')
5590 pthread_mutex_lock (&select_mutex);
5593 if (select_valid & SELECT_HAVE_READ)
5594 readfds = select_readfds;
5598 if (select_valid & SELECT_HAVE_WRITE)
5600 writefds = select_writefds;
5605 if (select_valid & SELECT_HAVE_TMO)
5607 timeout = select_timeout;
5613 pthread_mutex_unlock (&select_mutex);
5615 FD_SET (selfds[0], &readfds);
5616 if (selfds[0] >= nfds) nfds = selfds[0]+1;
5618 result = pselect (nfds, &readfds, wfds, NULL, tmo, NULL);
5621 ns_send_appdefined (-2);
5622 else if (result > 0)
5624 if (FD_ISSET (selfds[0], &readfds))
5626 if (read (selfds[0], &c, 1) == 1 && c == 's')
5631 pthread_mutex_lock (&select_mutex);
5632 if (select_valid & SELECT_HAVE_READ)
5633 select_readfds = readfds;
5634 if (select_valid & SELECT_HAVE_WRITE)
5635 select_writefds = writefds;
5636 if (select_valid & SELECT_HAVE_TMO)
5637 select_timeout = timeout;
5638 pthread_mutex_unlock (&select_mutex);
5640 ns_send_appdefined (result);
5650 /* ==========================================================================
5654 ========================================================================== */
5656 /* called from system: queue for next pass through event loop */
5657 - (void)requestService: (NSPasteboard *)pboard
5658 userData: (NSString *)userData
5659 error: (NSString **)error
5661 [ns_pending_service_names addObject: userData];
5662 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
5663 SSDATA (ns_string_from_pasteboard (pboard))]];
5667 /* called from ns_read_socket to clear queue */
5668 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
5670 struct frame *emacsframe = SELECTED_FRAME ();
5671 NSEvent *theEvent = [NSApp currentEvent];
5673 NSTRACE ("[EmacsApp fulfillService:withArg:]");
5678 emacs_event->kind = NS_NONKEY_EVENT;
5679 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
5680 ns_input_spi_name = build_string ([name UTF8String]);
5681 ns_input_spi_arg = build_string ([arg UTF8String]);
5682 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5683 EV_TRAILER (theEvent);
5693 /* ==========================================================================
5695 EmacsView implementation
5697 ========================================================================== */
5700 @implementation EmacsView
5702 /* needed to inform when window closed from LISP */
5703 - (void) setWindowClosing: (BOOL)closing
5705 NSTRACE ("[EmacsView setWindowClosing:%d]", closing);
5707 windowClosing = closing;
5713 NSTRACE ("[EmacsView dealloc]");
5715 if (fs_state == FULLSCREEN_BOTH)
5716 [nonfs_window release];
5721 /* called on font panel selection */
5722 - (void)changeFont: (id)sender
5724 NSEvent *e = [[self window] currentEvent];
5725 struct face *face = FRAME_DEFAULT_FACE (emacsframe);
5726 struct font *font = face->font;
5731 NSTRACE ("[EmacsView changeFont:]");
5736 #ifdef NS_IMPL_GNUSTEP
5737 nsfont = ((struct nsfont_info *)font)->nsfont;
5739 #ifdef NS_IMPL_COCOA
5740 nsfont = (NSFont *) macfont_get_nsctfont (font);
5743 if ((newFont = [sender convertFont: nsfont]))
5745 SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
5747 emacs_event->kind = NS_NONKEY_EVENT;
5748 emacs_event->modifiers = 0;
5749 emacs_event->code = KEY_NS_CHANGE_FONT;
5751 size = [newFont pointSize];
5752 ns_input_fontsize = make_number (lrint (size));
5753 ns_input_font = build_string ([[newFont familyName] UTF8String]);
5759 - (BOOL)acceptsFirstResponder
5761 NSTRACE ("[EmacsView acceptsFirstResponder]");
5766 - (void)resetCursorRects
5768 NSRect visible = [self visibleRect];
5769 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
5770 NSTRACE ("[EmacsView resetCursorRects]");
5772 if (currentCursor == nil)
5773 currentCursor = [NSCursor arrowCursor];
5775 if (!NSIsEmptyRect (visible))
5776 [self addCursorRect: visible cursor: currentCursor];
5777 [currentCursor setOnMouseEntered: YES];
5782 /*****************************************************************************/
5783 /* Keyboard handling. */
5786 - (void)keyDown: (NSEvent *)theEvent
5788 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5790 unsigned fnKeysym = 0;
5791 static NSMutableArray *nsEvArray;
5793 unsigned int flags = [theEvent modifierFlags];
5795 NSTRACE ("[EmacsView keyDown:]");
5797 /* Rhapsody and OS X give up and down events for the arrow keys */
5798 if (ns_fake_keydown == YES)
5799 ns_fake_keydown = NO;
5800 else if ([theEvent type] != NSEventTypeKeyDown)
5806 if (![[self window] isKeyWindow]
5807 && [[theEvent window] isKindOfClass: [EmacsWindow class]]
5808 /* we must avoid an infinite loop here. */
5809 && (EmacsView *)[[theEvent window] delegate] != self)
5811 /* XXX: There is an occasional condition in which, when Emacs display
5812 updates a different frame from the current one, and temporarily
5813 selects it, then processes some interrupt-driven input
5814 (dispnew.c:3878), OS will send the event to the correct NSWindow, but
5815 for some reason that window has its first responder set to the NSView
5816 most recently updated (I guess), which is not the correct one. */
5817 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
5821 if (nsEvArray == nil)
5822 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
5824 [NSCursor setHiddenUntilMouseMoves: YES];
5826 if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
5828 clear_mouse_face (hlinfo);
5829 hlinfo->mouse_face_hidden = 1;
5832 if (!processingCompose)
5834 /* When using screen sharing, no left or right information is sent,
5835 so use Left key in those cases. */
5836 int is_left_key, is_right_key;
5838 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
5839 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
5841 /* (Carbon way: [theEvent keyCode]) */
5843 /* is it a "function key"? */
5844 /* Note: Sometimes a plain key will have the NSEventModifierFlagNumericPad
5845 flag set (this is probably a bug in the OS).
5847 if (code < 0x00ff && (flags&NSEventModifierFlagNumericPad))
5849 fnKeysym = ns_convert_key ([theEvent keyCode] | NSEventModifierFlagNumericPad);
5853 fnKeysym = ns_convert_key (code);
5858 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
5859 because Emacs treats Delete and KP-Delete same (in simple.el). */
5860 if ((fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
5861 #ifdef NS_IMPL_GNUSTEP
5862 /* GNUstep uses incompatible keycodes, even for those that are
5863 supposed to be hardware independent. Just check for delete.
5864 Keypad delete does not have keysym 0xFFFF.
5865 See http://savannah.gnu.org/bugs/?25395
5867 || (fnKeysym == 0xFFFF && code == 127)
5870 code = 0xFF08; /* backspace */
5875 /* are there modifiers? */
5876 emacs_event->modifiers = 0;
5878 if (flags & NSEventModifierFlagHelp)
5879 emacs_event->modifiers |= hyper_modifier;
5881 if (flags & NSEventModifierFlagShift)
5882 emacs_event->modifiers |= shift_modifier;
5884 is_right_key = (flags & NSRightCommandKeyMask) == NSRightCommandKeyMask;
5885 is_left_key = (flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask
5886 || (! is_right_key && (flags & NSEventModifierFlagCommand) == NSEventModifierFlagCommand);
5889 emacs_event->modifiers |= parse_solitary_modifier
5890 (EQ (ns_right_command_modifier, Qleft)
5891 ? ns_command_modifier
5892 : ns_right_command_modifier);
5896 emacs_event->modifiers |= parse_solitary_modifier
5897 (ns_command_modifier);
5899 /* if super (default), take input manager's word so things like
5900 dvorak / qwerty layout work */
5901 if (EQ (ns_command_modifier, Qsuper)
5903 && [[theEvent characters] length] != 0)
5905 /* XXX: the code we get will be unshifted, so if we have
5906 a shift modifier, must convert ourselves */
5907 if (!(flags & NSEventModifierFlagShift))
5908 code = [[theEvent characters] characterAtIndex: 0];
5910 /* this is ugly and also requires linking w/Carbon framework
5911 (for LMGetKbdType) so for now leave this rare (?) case
5912 undealt with.. in future look into CGEvent methods */
5915 long smv = GetScriptManagerVariable (smKeyScript);
5916 Handle uchrHandle = GetResource
5917 ('uchr', GetScriptVariable (smv, smScriptKeys));
5919 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
5920 [[theEvent characters] characterAtIndex: 0],
5921 kUCKeyActionDisplay,
5922 (flags & ~NSEventModifierFlagCommand) >> 8,
5923 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
5924 &dummy, 1, &dummy, &code);
5931 is_right_key = (flags & NSRightControlKeyMask) == NSRightControlKeyMask;
5932 is_left_key = (flags & NSLeftControlKeyMask) == NSLeftControlKeyMask
5933 || (! is_right_key && (flags & NSEventModifierFlagControl) == NSEventModifierFlagControl);
5936 emacs_event->modifiers |= parse_solitary_modifier
5937 (EQ (ns_right_control_modifier, Qleft)
5938 ? ns_control_modifier
5939 : ns_right_control_modifier);
5942 emacs_event->modifiers |= parse_solitary_modifier
5943 (ns_control_modifier);
5945 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
5946 emacs_event->modifiers |=
5947 parse_solitary_modifier (ns_function_modifier);
5949 left_is_none = NILP (ns_alternate_modifier)
5950 || EQ (ns_alternate_modifier, Qnone);
5952 is_right_key = (flags & NSRightAlternateKeyMask)
5953 == NSRightAlternateKeyMask;
5954 is_left_key = (flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask
5956 && (flags & NSEventModifierFlagOption) == NSEventModifierFlagOption);
5960 if ((NILP (ns_right_alternate_modifier)
5961 || EQ (ns_right_alternate_modifier, Qnone)
5962 || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
5964 { /* accept pre-interp alt comb */
5965 if ([[theEvent characters] length] > 0)
5966 code = [[theEvent characters] characterAtIndex: 0];
5967 /*HACK: clear lone shift modifier to stop next if from firing */
5968 if (emacs_event->modifiers == shift_modifier)
5969 emacs_event->modifiers = 0;
5972 emacs_event->modifiers |= parse_solitary_modifier
5973 (EQ (ns_right_alternate_modifier, Qleft)
5974 ? ns_alternate_modifier
5975 : ns_right_alternate_modifier);
5978 if (is_left_key) /* default = meta */
5980 if (left_is_none && !fnKeysym)
5981 { /* accept pre-interp alt comb */
5982 if ([[theEvent characters] length] > 0)
5983 code = [[theEvent characters] characterAtIndex: 0];
5984 /*HACK: clear lone shift modifier to stop next if from firing */
5985 if (emacs_event->modifiers == shift_modifier)
5986 emacs_event->modifiers = 0;
5989 emacs_event->modifiers |=
5990 parse_solitary_modifier (ns_alternate_modifier);
5994 fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
5995 code, fnKeysym, flags, emacs_event->modifiers);
5997 /* if it was a function key or had modifiers, pass it directly to emacs */
5998 if (fnKeysym || (emacs_event->modifiers
5999 && (emacs_event->modifiers != shift_modifier)
6000 && [[theEvent charactersIgnoringModifiers] length] > 0))
6001 /*[[theEvent characters] length] */
6003 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
6005 code |= (1<<28)|(3<<16);
6006 else if (code == 0x7f)
6007 code |= (1<<28)|(3<<16);
6009 emacs_event->kind = code > 0xFF
6010 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
6012 emacs_event->code = code;
6013 EV_TRAILER (theEvent);
6014 processingCompose = NO;
6020 if (NS_KEYLOG && !processingCompose)
6021 fprintf (stderr, "keyDown: Begin compose sequence.\n");
6023 processingCompose = YES;
6024 [nsEvArray addObject: theEvent];
6025 [self interpretKeyEvents: nsEvArray];
6026 [nsEvArray removeObject: theEvent];
6030 #ifdef NS_IMPL_COCOA
6031 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
6032 decided not to send key-down for.
6033 See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
6034 This only applies on Tiger and earlier.
6035 If it matches one of these, send it on to keyDown. */
6036 -(void)keyUp: (NSEvent *)theEvent
6038 int flags = [theEvent modifierFlags];
6039 int code = [theEvent keyCode];
6041 NSTRACE ("[EmacsView keyUp:]");
6043 if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
6044 code == 0x30 && (flags & NSEventModifierFlagControl) && !(flags & NSEventModifierFlagCommand))
6047 fprintf (stderr, "keyUp: passed test");
6048 ns_fake_keydown = YES;
6049 [self keyDown: theEvent];
6055 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
6058 /* <NSTextInput>: called when done composing;
6059 NOTE: also called when we delete over working text, followed immed.
6060 by doCommandBySelector: deleteBackward: */
6061 - (void)insertText: (id)aString
6064 int len = [(NSString *)aString length];
6067 NSTRACE ("[EmacsView insertText:]");
6070 NSLog (@"insertText '%@'\tlen = %d", aString, len);
6071 processingCompose = NO;
6076 /* first, clear any working text */
6077 if (workingText != nil)
6078 [self deleteWorkingText];
6080 /* now insert the string as keystrokes */
6081 for (i =0; i<len; i++)
6083 code = [aString characterAtIndex: i];
6084 /* TODO: still need this? */
6086 code = '~'; /* 0x7E */
6087 if (code != 32) /* Space */
6088 emacs_event->modifiers = 0;
6090 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
6091 emacs_event->code = code;
6092 EV_TRAILER ((id)nil);
6097 /* <NSTextInput>: inserts display of composing characters */
6098 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
6100 NSString *str = [aString respondsToSelector: @selector (string)] ?
6101 [aString string] : aString;
6103 NSTRACE ("[EmacsView setMarkedText:selectedRange:]");
6106 NSLog (@"setMarkedText '%@' len =%lu range %lu from %lu",
6107 str, (unsigned long)[str length],
6108 (unsigned long)selRange.length,
6109 (unsigned long)selRange.location);
6111 if (workingText != nil)
6112 [self deleteWorkingText];
6113 if ([str length] == 0)
6119 processingCompose = YES;
6120 workingText = [str copy];
6121 ns_working_text = build_string ([workingText UTF8String]);
6123 emacs_event->kind = NS_TEXT_EVENT;
6124 emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
6125 EV_TRAILER ((id)nil);
6129 /* delete display of composing characters [not in <NSTextInput>] */
6130 - (void)deleteWorkingText
6132 NSTRACE ("[EmacsView deleteWorkingText]");
6134 if (workingText == nil)
6137 NSLog(@"deleteWorkingText len =%lu\n", (unsigned long)[workingText length]);
6138 [workingText release];
6140 processingCompose = NO;
6145 emacs_event->kind = NS_TEXT_EVENT;
6146 emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
6147 EV_TRAILER ((id)nil);
6151 - (BOOL)hasMarkedText
6153 NSTRACE ("[EmacsView hasMarkedText]");
6155 return workingText != nil;
6159 - (NSRange)markedRange
6161 NSTRACE ("[EmacsView markedRange]");
6163 NSRange rng = workingText != nil
6164 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
6166 NSLog (@"markedRange request");
6173 NSTRACE ("[EmacsView unmarkText]");
6176 NSLog (@"unmark (accept) text");
6177 [self deleteWorkingText];
6178 processingCompose = NO;
6182 /* used to position char selection windows, etc. */
6183 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
6187 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
6189 NSTRACE ("[EmacsView firstRectForCharacterRange:]");
6192 NSLog (@"firstRectForCharRange request");
6194 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
6195 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
6196 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
6197 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
6198 +FRAME_LINE_HEIGHT (emacsframe));
6200 pt = [self convertPoint: pt toView: nil];
6201 #if !defined (NS_IMPL_COCOA) || \
6202 MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
6203 pt = [[self window] convertBaseToScreen: pt];
6207 rect = [[self window] convertRectToScreen: rect];
6213 - (NSInteger)conversationIdentifier
6215 return (NSInteger)self;
6219 - (void)doCommandBySelector: (SEL)aSelector
6221 NSTRACE ("[EmacsView doCommandBySelector:]");
6224 NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
6226 processingCompose = NO;
6227 if (aSelector == @selector (deleteBackward:))
6229 /* happens when user backspaces over an ongoing composition:
6230 throw a 'delete' into the event queue */
6233 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
6234 emacs_event->code = 0xFF08;
6235 EV_TRAILER ((id)nil);
6239 - (NSArray *)validAttributesForMarkedText
6241 static NSArray *arr = nil;
6242 if (arr == nil) arr = [NSArray new];
6243 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
6247 - (NSRange)selectedRange
6250 NSLog (@"selectedRange request");
6251 return NSMakeRange (NSNotFound, 0);
6254 #if defined (NS_IMPL_COCOA) || GNUSTEP_GUI_MAJOR_VERSION > 0 || \
6255 GNUSTEP_GUI_MINOR_VERSION > 22
6256 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
6258 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
6262 NSLog (@"characterIndexForPoint request");
6266 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
6268 static NSAttributedString *str = nil;
6269 if (str == nil) str = [NSAttributedString new];
6271 NSLog (@"attributedSubstringFromRange request");
6275 /* End <NSTextInput> impl. */
6276 /*****************************************************************************/
6279 /* This is what happens when the user presses a mouse button. */
6280 - (void)mouseDown: (NSEvent *)theEvent
6282 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6283 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
6285 NSTRACE ("[EmacsView mouseDown:]");
6287 [self deleteWorkingText];
6292 dpyinfo->last_mouse_frame = emacsframe;
6293 /* appears to be needed to prevent spurious movement events generated on
6295 emacsframe->mouse_moved = 0;
6297 if ([theEvent type] == NSEventTypeScrollWheel)
6299 CGFloat delta = [theEvent deltaY];
6300 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
6303 delta = [theEvent deltaX];
6306 NSTRACE_MSG ("deltaIsZero");
6309 emacs_event->kind = HORIZ_WHEEL_EVENT;
6312 emacs_event->kind = WHEEL_EVENT;
6314 emacs_event->code = 0;
6315 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
6316 ((delta > 0) ? up_modifier : down_modifier);
6320 emacs_event->kind = MOUSE_CLICK_EVENT;
6321 emacs_event->code = EV_BUTTON (theEvent);
6322 emacs_event->modifiers = EV_MODIFIERS (theEvent)
6323 | EV_UDMODIFIERS (theEvent);
6325 XSETINT (emacs_event->x, lrint (p.x));
6326 XSETINT (emacs_event->y, lrint (p.y));
6327 EV_TRAILER (theEvent);
6331 - (void)rightMouseDown: (NSEvent *)theEvent
6333 NSTRACE ("[EmacsView rightMouseDown:]");
6334 [self mouseDown: theEvent];
6338 - (void)otherMouseDown: (NSEvent *)theEvent
6340 NSTRACE ("[EmacsView otherMouseDown:]");
6341 [self mouseDown: theEvent];
6345 - (void)mouseUp: (NSEvent *)theEvent
6347 NSTRACE ("[EmacsView mouseUp:]");
6348 [self mouseDown: theEvent];
6352 - (void)rightMouseUp: (NSEvent *)theEvent
6354 NSTRACE ("[EmacsView rightMouseUp:]");
6355 [self mouseDown: theEvent];
6359 - (void)otherMouseUp: (NSEvent *)theEvent
6361 NSTRACE ("[EmacsView otherMouseUp:]");
6362 [self mouseDown: theEvent];
6366 - (void) scrollWheel: (NSEvent *)theEvent
6368 NSTRACE ("[EmacsView scrollWheel:]");
6369 [self mouseDown: theEvent];
6373 /* Tell emacs the mouse has moved. */
6374 - (void)mouseMoved: (NSEvent *)e
6376 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
6377 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6381 NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "[EmacsView mouseMoved:]");
6383 dpyinfo->last_mouse_movement_time = EV_TIMESTAMP (e);
6384 pt = [self convertPoint: [e locationInWindow] fromView: nil];
6385 dpyinfo->last_mouse_motion_x = pt.x;
6386 dpyinfo->last_mouse_motion_y = pt.y;
6388 /* update any mouse face */
6389 if (hlinfo->mouse_face_hidden)
6391 hlinfo->mouse_face_hidden = 0;
6392 clear_mouse_face (hlinfo);
6395 /* tooltip handling */
6396 previous_help_echo_string = help_echo_string;
6397 help_echo_string = Qnil;
6399 if (!NILP (Vmouse_autoselect_window))
6401 NSTRACE_MSG ("mouse_autoselect_window");
6402 static Lisp_Object last_mouse_window;
6404 = window_from_coordinates (emacsframe, pt.x, pt.y, 0, 0);
6406 if (WINDOWP (window)
6407 && !EQ (window, last_mouse_window)
6408 && !EQ (window, selected_window)
6409 && (focus_follows_mouse
6410 || (EQ (XWINDOW (window)->frame,
6411 XWINDOW (selected_window)->frame))))
6413 NSTRACE_MSG ("in_window");
6414 emacs_event->kind = SELECT_WINDOW_EVENT;
6415 emacs_event->frame_or_window = window;
6418 /* Remember the last window where we saw the mouse. */
6419 last_mouse_window = window;
6422 if (!note_mouse_movement (emacsframe, pt.x, pt.y))
6423 help_echo_string = previous_help_echo_string;
6425 XSETFRAME (frame, emacsframe);
6426 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
6428 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
6429 (note_mouse_highlight), which is called through the
6430 note_mouse_movement () call above */
6431 any_help_event_p = YES;
6432 gen_help_event (help_echo_string, frame, help_echo_window,
6433 help_echo_object, help_echo_pos);
6436 if (emacsframe->mouse_moved && send_appdefined)
6437 ns_send_appdefined (-1);
6441 - (void)mouseDragged: (NSEvent *)e
6443 NSTRACE ("[EmacsView mouseDragged:]");
6444 [self mouseMoved: e];
6448 - (void)rightMouseDragged: (NSEvent *)e
6450 NSTRACE ("[EmacsView rightMouseDragged:]");
6451 [self mouseMoved: e];
6455 - (void)otherMouseDragged: (NSEvent *)e
6457 NSTRACE ("[EmacsView otherMouseDragged:]");
6458 [self mouseMoved: e];
6462 - (BOOL)windowShouldClose: (id)sender
6464 NSEvent *e =[[self window] currentEvent];
6466 NSTRACE ("[EmacsView windowShouldClose:]");
6467 windowClosing = YES;
6470 emacs_event->kind = DELETE_WINDOW_EVENT;
6471 emacs_event->modifiers = 0;
6472 emacs_event->code = 0;
6474 /* Don't close this window, let this be done from lisp code. */
6478 - (void) updateFrameSize: (BOOL) delay;
6480 NSWindow *window = [self window];
6481 NSRect wr = [window frame];
6483 int oldc = cols, oldr = rows;
6484 int oldw = FRAME_PIXEL_WIDTH (emacsframe);
6485 int oldh = FRAME_PIXEL_HEIGHT (emacsframe);
6488 NSTRACE ("[EmacsView updateFrameSize:]");
6489 NSTRACE_SIZE ("Original size", NSMakeSize (oldw, oldh));
6490 NSTRACE_RECT ("Original frame", wr);
6491 NSTRACE_MSG ("Original columns: %d", cols);
6492 NSTRACE_MSG ("Original rows: %d", rows);
6494 if (! [self isFullscreen])
6496 #ifdef NS_IMPL_GNUSTEP
6497 // GNUstep does not always update the tool bar height. Force it.
6498 if (toolbar && [toolbar isVisible])
6499 update_frame_tool_bar (emacsframe);
6502 extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6503 + FRAME_TOOLBAR_HEIGHT (emacsframe);
6506 if (wait_for_tool_bar)
6508 if (FRAME_TOOLBAR_HEIGHT (emacsframe) == 0)
6510 NSTRACE_MSG ("Waiting for toolbar");
6513 wait_for_tool_bar = NO;
6516 neww = (int)wr.size.width - emacsframe->border_width;
6517 newh = (int)wr.size.height - extra;
6519 NSTRACE_SIZE ("New size", NSMakeSize (neww, newh));
6520 NSTRACE_MSG ("tool_bar_height: %d", emacsframe->tool_bar_height);
6522 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, neww);
6523 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, newh);
6525 if (cols < MINWIDTH)
6528 if (rows < MINHEIGHT)
6531 NSTRACE_MSG ("New columns: %d", cols);
6532 NSTRACE_MSG ("New rows: %d", rows);
6534 if (oldr != rows || oldc != cols || neww != oldw || newh != oldh)
6536 NSView *view = FRAME_NS_VIEW (emacsframe);
6538 change_frame_size (emacsframe,
6539 FRAME_PIXEL_TO_TEXT_WIDTH (emacsframe, neww),
6540 FRAME_PIXEL_TO_TEXT_HEIGHT (emacsframe, newh),
6542 SET_FRAME_GARBAGED (emacsframe);
6543 cancel_mouse_face (emacsframe);
6545 wr = NSMakeRect (0, 0, neww, newh);
6547 [view setFrame: wr];
6549 // to do: consider using [NSNotificationCenter postNotificationName:].
6550 [self windowDidMove: // Update top/left.
6551 [NSNotification notificationWithName:NSWindowDidMoveNotification
6552 object:[view window]]];
6556 NSTRACE_MSG ("No change");
6560 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
6561 /* normalize frame to gridded text size */
6565 NSTRACE ("[EmacsView windowWillResize:toSize: " NSTRACE_FMT_SIZE "]",
6566 NSTRACE_ARG_SIZE (frameSize));
6567 NSTRACE_RECT ("[sender frame]", [sender frame]);
6568 NSTRACE_FSTYPE ("fs_state", fs_state);
6570 if (fs_state == FULLSCREEN_MAXIMIZED
6571 && (maximized_width != (int)frameSize.width
6572 || maximized_height != (int)frameSize.height))
6573 [self setFSValue: FULLSCREEN_NONE];
6574 else if (fs_state == FULLSCREEN_WIDTH
6575 && maximized_width != (int)frameSize.width)
6576 [self setFSValue: FULLSCREEN_NONE];
6577 else if (fs_state == FULLSCREEN_HEIGHT
6578 && maximized_height != (int)frameSize.height)
6579 [self setFSValue: FULLSCREEN_NONE];
6581 if (fs_state == FULLSCREEN_NONE)
6582 maximized_width = maximized_height = -1;
6584 if (! [self isFullscreen])
6586 extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6587 + FRAME_TOOLBAR_HEIGHT (emacsframe);
6590 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, frameSize.width);
6591 if (cols < MINWIDTH)
6594 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe,
6595 frameSize.height - extra);
6596 if (rows < MINHEIGHT)
6598 #ifdef NS_IMPL_COCOA
6600 /* this sets window title to have size in it; the wm does this under GS */
6601 NSRect r = [[self window] frame];
6602 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
6610 else if (fs_state == FULLSCREEN_NONE && ! maximizing_resize)
6613 NSWindow *window = [self window];
6616 char *t = strdup ([[[self window] title] UTF8String]);
6617 char *pos = strstr (t, " — ");
6622 size_title = xmalloc (strlen (old_title) + 40);
6623 esprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
6624 [window setTitle: [NSString stringWithUTF8String: size_title]];
6629 #endif /* NS_IMPL_COCOA */
6631 NSTRACE_MSG ("cols: %d rows: %d", cols, rows);
6633 /* Restrict the new size to the text gird.
6635 Don't restrict the width if the user only adjusted the height, and
6636 vice versa. (Without this, the frame would shrink, and move
6637 slightly, if the window was resized by dragging one of its
6639 if (!frame_resize_pixelwise)
6641 NSRect r = [[self window] frame];
6643 if (r.size.width != frameSize.width)
6646 FRAME_TEXT_COLS_TO_PIXEL_WIDTH (emacsframe, cols);
6649 if (r.size.height != frameSize.height)
6652 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows) + extra;
6656 NSTRACE_RETURN_SIZE (frameSize);
6662 - (void)windowDidResize: (NSNotification *)notification
6664 NSTRACE ("[EmacsView windowDidResize:]");
6665 if (!FRAME_LIVE_P (emacsframe))
6667 NSTRACE_MSG ("Ignored (frame dead)");
6670 if (emacsframe->output_data.ns->in_animation)
6672 NSTRACE_MSG ("Ignored (in animation)");
6676 if (! [self fsIsNative])
6678 NSWindow *theWindow = [notification object];
6679 /* We can get notification on the non-FS window when in
6681 if ([self window] != theWindow) return;
6684 NSTRACE_RECT ("frame", [[notification object] frame]);
6686 #ifdef NS_IMPL_GNUSTEP
6687 NSWindow *theWindow = [notification object];
6689 /* In GNUstep, at least currently, it's possible to get a didResize
6690 without getting a willResize.. therefore we need to act as if we got
6691 the willResize now */
6692 NSSize sz = [theWindow frame].size;
6693 sz = [self windowWillResize: theWindow toSize: sz];
6694 #endif /* NS_IMPL_GNUSTEP */
6696 if (cols > 0 && rows > 0)
6698 [self updateFrameSize: YES];
6701 ns_send_appdefined (-1);
6704 #ifdef NS_IMPL_COCOA
6705 - (void)viewDidEndLiveResize
6707 NSTRACE ("[EmacsView viewDidEndLiveResize]");
6709 [super viewDidEndLiveResize];
6712 [[self window] setTitle: [NSString stringWithUTF8String: old_title]];
6716 maximizing_resize = NO;
6718 #endif /* NS_IMPL_COCOA */
6721 - (void)windowDidBecomeKey: (NSNotification *)notification
6722 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6724 [self windowDidBecomeKey];
6728 - (void)windowDidBecomeKey /* for direct calls */
6730 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6731 struct frame *old_focus = dpyinfo->x_focus_frame;
6733 NSTRACE ("[EmacsView windowDidBecomeKey]");
6735 if (emacsframe != old_focus)
6736 dpyinfo->x_focus_frame = emacsframe;
6738 ns_frame_rehighlight (emacsframe);
6742 emacs_event->kind = FOCUS_IN_EVENT;
6743 EV_TRAILER ((id)nil);
6748 - (void)windowDidResignKey: (NSNotification *)notification
6749 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6751 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6752 BOOL is_focus_frame = dpyinfo->x_focus_frame == emacsframe;
6753 NSTRACE ("[EmacsView windowDidResignKey:]");
6756 dpyinfo->x_focus_frame = 0;
6758 emacsframe->mouse_moved = 0;
6759 ns_frame_rehighlight (emacsframe);
6761 /* FIXME: for some reason needed on second and subsequent clicks away
6762 from sole-frame Emacs to get hollow box to show */
6763 if (!windowClosing && [[self window] isVisible] == YES)
6765 x_update_cursor (emacsframe, 1);
6766 x_set_frame_alpha (emacsframe);
6769 if (any_help_event_p)
6772 XSETFRAME (frame, emacsframe);
6773 help_echo_string = Qnil;
6774 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
6777 if (emacs_event && is_focus_frame)
6779 [self deleteWorkingText];
6780 emacs_event->kind = FOCUS_OUT_EVENT;
6781 EV_TRAILER ((id)nil);
6786 - (void)windowWillMiniaturize: sender
6788 NSTRACE ("[EmacsView windowWillMiniaturize:]");
6792 - (void)setFrame:(NSRect)frameRect;
6794 NSTRACE ("[EmacsView setFrame:" NSTRACE_FMT_RECT "]",
6795 NSTRACE_ARG_RECT (frameRect));
6797 [super setFrame:(NSRect)frameRect];
6813 - initFrameFromEmacs: (struct frame *)f
6821 NSTRACE ("[EmacsView initFrameFromEmacs:]");
6822 NSTRACE_MSG ("cols:%d lines:%d", f->text_cols, f->text_lines);
6825 processingCompose = NO;
6826 scrollbarsNeedingUpdate = 0;
6827 fs_state = FULLSCREEN_NONE;
6828 fs_before_fs = next_maximized = -1;
6829 #ifdef HAVE_NATIVE_FS
6830 fs_is_native = ns_use_native_fullscreen;
6834 maximized_width = maximized_height = -1;
6837 ns_userRect = NSMakeRect (0, 0, 0, 0);
6838 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
6839 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
6840 [self initWithFrame: r];
6841 [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
6843 FRAME_NS_VIEW (f) = self;
6845 #ifdef NS_IMPL_COCOA
6847 maximizing_resize = NO;
6850 win = [[EmacsWindow alloc]
6851 initWithContentRect: r
6852 styleMask: (NSWindowStyleMaskResizable |
6853 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6854 NSWindowStyleMaskTitled |
6856 NSWindowStyleMaskMiniaturizable |
6857 NSWindowStyleMaskClosable)
6858 backing: NSBackingStoreBuffered
6861 #ifdef HAVE_NATIVE_FS
6862 [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
6866 bwidth = f->border_width = wr.size.width - r.size.width;
6867 tibar_height = FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
6869 [win setAcceptsMouseMovedEvents: YES];
6870 [win setDelegate: self];
6871 #if !defined (NS_IMPL_COCOA) || \
6872 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6873 [win useOptimizedDrawing: YES];
6876 [[win contentView] addSubview: self];
6879 [self registerForDraggedTypes: ns_drag_types];
6882 name = [NSString stringWithUTF8String:
6883 NILP (tem) ? "Emacs" : SSDATA (tem)];
6884 [win setTitle: name];
6886 /* toolbar support */
6887 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
6888 [NSString stringWithFormat: @"Emacs Frame %d",
6890 [win setToolbar: toolbar];
6891 [toolbar setVisible: NO];
6893 /* Don't set frame garbaged until tool bar is up to date?
6894 This avoids an extra clear and redraw (flicker) at frame creation. */
6895 if (FRAME_EXTERNAL_TOOL_BAR (f)) wait_for_tool_bar = YES;
6896 else wait_for_tool_bar = NO;
6899 #ifdef NS_IMPL_COCOA
6901 NSButton *toggleButton;
6902 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
6903 [toggleButton setTarget: self];
6904 [toggleButton setAction: @selector (toggleToolbar: )];
6907 FRAME_TOOLBAR_HEIGHT (f) = 0;
6911 [win setMiniwindowTitle:
6912 [NSString stringWithUTF8String: SSDATA (tem)]];
6915 NSScreen *screen = [win screen];
6919 NSPoint pt = NSMakePoint
6920 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
6921 IN_BOUND (-SCREENMAX,
6922 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX));
6924 [win setFrameTopLeftPoint: pt];
6926 NSTRACE_RECT ("new frame", [win frame]);
6930 [win makeFirstResponder: self];
6932 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6933 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
6934 [win setBackgroundColor: col];
6935 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6936 [win setOpaque: NO];
6938 #if !defined (NS_IMPL_COCOA) || \
6939 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6940 [self allocateGState];
6942 [NSApp registerServicesMenuSendTypes: ns_send_types
6950 - (void)windowDidMove: sender
6952 NSWindow *win = [self window];
6953 NSRect r = [win frame];
6954 NSArray *screens = [NSScreen screens];
6955 NSScreen *screen = [screens objectAtIndex: 0];
6957 NSTRACE ("[EmacsView windowDidMove:]");
6959 if (!emacsframe->output_data.ns)
6963 emacsframe->left_pos = r.origin.x;
6964 emacsframe->top_pos =
6965 [screen frame].size.height - (r.origin.y + r.size.height);
6970 /* Called AFTER method below, but before our windowWillResize call there leads
6971 to windowDidResize -> x_set_window_size. Update emacs' notion of frame
6972 location so set_window_size moves the frame. */
6973 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
6975 NSTRACE (("[EmacsView windowShouldZoom:toFrame:" NSTRACE_FMT_RECT "]"
6976 NSTRACE_FMT_RETURN "YES"),
6977 NSTRACE_ARG_RECT (newFrame));
6979 emacsframe->output_data.ns->zooming = 1;
6984 /* Override to do something slightly nonstandard, but nice. First click on
6985 zoom button will zoom vertically. Second will zoom completely. Third
6986 returns to original. */
6987 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
6988 defaultFrame:(NSRect)defaultFrame
6990 // TODO: Rename to "currentFrame" and assign "result" properly in
6992 NSRect result = [sender frame];
6994 NSTRACE (("[EmacsView windowWillUseStandardFrame:defaultFrame:"
6995 NSTRACE_FMT_RECT "]"),
6996 NSTRACE_ARG_RECT (defaultFrame));
6997 NSTRACE_FSTYPE ("fs_state", fs_state);
6998 NSTRACE_FSTYPE ("fs_before_fs", fs_before_fs);
6999 NSTRACE_FSTYPE ("next_maximized", next_maximized);
7000 NSTRACE_RECT ("ns_userRect", ns_userRect);
7001 NSTRACE_RECT ("[sender frame]", [sender frame]);
7003 if (fs_before_fs != -1) /* Entering fullscreen */
7005 NSTRACE_MSG ("Entering fullscreen");
7006 result = defaultFrame;
7010 // Save the window size and position (frame) before the resize.
7011 if (fs_state != FULLSCREEN_MAXIMIZED
7012 && fs_state != FULLSCREEN_WIDTH)
7014 ns_userRect.size.width = result.size.width;
7015 ns_userRect.origin.x = result.origin.x;
7018 if (fs_state != FULLSCREEN_MAXIMIZED
7019 && fs_state != FULLSCREEN_HEIGHT)
7021 ns_userRect.size.height = result.size.height;
7022 ns_userRect.origin.y = result.origin.y;
7025 NSTRACE_RECT ("ns_userRect (2)", ns_userRect);
7027 if (next_maximized == FULLSCREEN_HEIGHT
7028 || (next_maximized == -1
7029 && abs ((int)(defaultFrame.size.height - result.size.height))
7030 > FRAME_LINE_HEIGHT (emacsframe)))
7033 NSTRACE_MSG ("FULLSCREEN_HEIGHT");
7034 maximized_height = result.size.height = defaultFrame.size.height;
7035 maximized_width = -1;
7036 result.origin.y = defaultFrame.origin.y;
7037 if (ns_userRect.size.height != 0)
7039 result.origin.x = ns_userRect.origin.x;
7040 result.size.width = ns_userRect.size.width;
7042 [self setFSValue: FULLSCREEN_HEIGHT];
7043 #ifdef NS_IMPL_COCOA
7044 maximizing_resize = YES;
7047 else if (next_maximized == FULLSCREEN_WIDTH)
7049 NSTRACE_MSG ("FULLSCREEN_WIDTH");
7050 maximized_width = result.size.width = defaultFrame.size.width;
7051 maximized_height = -1;
7052 result.origin.x = defaultFrame.origin.x;
7053 if (ns_userRect.size.width != 0)
7055 result.origin.y = ns_userRect.origin.y;
7056 result.size.height = ns_userRect.size.height;
7058 [self setFSValue: FULLSCREEN_WIDTH];
7060 else if (next_maximized == FULLSCREEN_MAXIMIZED
7061 || (next_maximized == -1
7062 && abs ((int)(defaultFrame.size.width - result.size.width))
7063 > FRAME_COLUMN_WIDTH (emacsframe)))
7065 NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
7067 result = defaultFrame; /* second click */
7068 maximized_width = result.size.width;
7069 maximized_height = result.size.height;
7070 [self setFSValue: FULLSCREEN_MAXIMIZED];
7071 #ifdef NS_IMPL_COCOA
7072 maximizing_resize = YES;
7078 NSTRACE_MSG ("Restore");
7079 result = ns_userRect.size.height ? ns_userRect : result;
7080 NSTRACE_RECT ("restore (2)", result);
7081 ns_userRect = NSMakeRect (0, 0, 0, 0);
7082 #ifdef NS_IMPL_COCOA
7083 maximizing_resize = fs_state != FULLSCREEN_NONE;
7085 [self setFSValue: FULLSCREEN_NONE];
7086 maximized_width = maximized_height = -1;
7090 if (fs_before_fs == -1) next_maximized = -1;
7092 NSTRACE_RECT ("Final ns_userRect", ns_userRect);
7093 NSTRACE_MSG ("Final maximized_width: %d", maximized_width);
7094 NSTRACE_MSG ("Final maximized_height: %d", maximized_height);
7095 NSTRACE_FSTYPE ("Final next_maximized", next_maximized);
7097 [self windowWillResize: sender toSize: result.size];
7099 NSTRACE_RETURN_RECT (result);
7105 - (void)windowDidDeminiaturize: sender
7107 NSTRACE ("[EmacsView windowDidDeminiaturize:]");
7108 if (!emacsframe->output_data.ns)
7111 SET_FRAME_ICONIFIED (emacsframe, 0);
7112 SET_FRAME_VISIBLE (emacsframe, 1);
7113 windows_or_buffers_changed = 63;
7117 emacs_event->kind = DEICONIFY_EVENT;
7118 EV_TRAILER ((id)nil);
7123 - (void)windowDidExpose: sender
7125 NSTRACE ("[EmacsView windowDidExpose:]");
7126 if (!emacsframe->output_data.ns)
7129 SET_FRAME_VISIBLE (emacsframe, 1);
7130 SET_FRAME_GARBAGED (emacsframe);
7132 if (send_appdefined)
7133 ns_send_appdefined (-1);
7137 - (void)windowDidMiniaturize: sender
7139 NSTRACE ("[EmacsView windowDidMiniaturize:]");
7140 if (!emacsframe->output_data.ns)
7143 SET_FRAME_ICONIFIED (emacsframe, 1);
7144 SET_FRAME_VISIBLE (emacsframe, 0);
7148 emacs_event->kind = ICONIFY_EVENT;
7149 EV_TRAILER ((id)nil);
7153 #ifdef HAVE_NATIVE_FS
7154 - (NSApplicationPresentationOptions)window:(NSWindow *)window
7155 willUseFullScreenPresentationOptions:
7156 (NSApplicationPresentationOptions)proposedOptions
7158 return proposedOptions|NSApplicationPresentationAutoHideToolbar;
7162 - (void)windowWillEnterFullScreen:(NSNotification *)notification
7164 NSTRACE ("[EmacsView windowWillEnterFullScreen:]");
7165 [self windowWillEnterFullScreen];
7167 - (void)windowWillEnterFullScreen /* provided for direct calls */
7169 NSTRACE ("[EmacsView windowWillEnterFullScreen]");
7170 fs_before_fs = fs_state;
7173 - (void)windowDidEnterFullScreen:(NSNotification *)notification
7175 NSTRACE ("[EmacsView windowDidEnterFullScreen:]");
7176 [self windowDidEnterFullScreen];
7179 - (void)windowDidEnterFullScreen /* provided for direct calls */
7181 NSTRACE ("[EmacsView windowDidEnterFullScreen]");
7182 [self setFSValue: FULLSCREEN_BOTH];
7183 if (! [self fsIsNative])
7185 [self windowDidBecomeKey];
7186 [nonfs_window orderOut:self];
7190 BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (emacsframe) ? YES : NO;
7191 #ifdef NS_IMPL_COCOA
7192 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
7193 unsigned val = (unsigned)[NSApp presentationOptions];
7195 // OSX 10.7 bug fix, the menu won't appear without this.
7196 // val is non-zero on other OSX versions.
7199 NSApplicationPresentationOptions options
7200 = NSApplicationPresentationAutoHideDock
7201 | NSApplicationPresentationAutoHideMenuBar
7202 | NSApplicationPresentationFullScreen
7203 | NSApplicationPresentationAutoHideToolbar;
7205 [NSApp setPresentationOptions: options];
7209 [toolbar setVisible:tbar_visible];
7213 - (void)windowWillExitFullScreen:(NSNotification *)notification
7215 NSTRACE ("[EmacsView windowWillExitFullScreen:]");
7216 [self windowWillExitFullScreen];
7219 - (void)windowWillExitFullScreen /* provided for direct calls */
7221 NSTRACE ("[EmacsView windowWillExitFullScreen]");
7222 if (!FRAME_LIVE_P (emacsframe))
7224 NSTRACE_MSG ("Ignored (frame dead)");
7227 if (next_maximized != -1)
7228 fs_before_fs = next_maximized;
7231 - (void)windowDidExitFullScreen:(NSNotification *)notification
7233 NSTRACE ("[EmacsView windowDidExitFullScreen:]");
7234 [self windowDidExitFullScreen];
7237 - (void)windowDidExitFullScreen /* provided for direct calls */
7239 NSTRACE ("[EmacsView windowDidExitFullScreen]");
7240 if (!FRAME_LIVE_P (emacsframe))
7242 NSTRACE_MSG ("Ignored (frame dead)");
7245 [self setFSValue: fs_before_fs];
7247 #ifdef HAVE_NATIVE_FS
7248 [self updateCollectionBehavior];
7250 if (FRAME_EXTERNAL_TOOL_BAR (emacsframe))
7252 [toolbar setVisible:YES];
7253 update_frame_tool_bar (emacsframe);
7254 [self updateFrameSize:YES];
7255 [[self window] display];
7258 [toolbar setVisible:NO];
7260 if (next_maximized != -1)
7261 [[self window] performZoom:self];
7266 return fs_is_native;
7269 - (BOOL)isFullscreen
7275 res = (nonfs_window != nil);
7279 #ifdef HAVE_NATIVE_FS
7280 res = (([[self window] styleMask] & NSWindowStyleMaskFullScreen) != 0);
7286 NSTRACE ("[EmacsView isFullscreen] " NSTRACE_FMT_RETURN " %d",
7292 #ifdef HAVE_NATIVE_FS
7293 - (void)updateCollectionBehavior
7295 NSTRACE ("[EmacsView updateCollectionBehavior]");
7297 if (! [self isFullscreen])
7299 NSWindow *win = [self window];
7300 NSWindowCollectionBehavior b = [win collectionBehavior];
7301 if (ns_use_native_fullscreen)
7302 b |= NSWindowCollectionBehaviorFullScreenPrimary;
7304 b &= ~NSWindowCollectionBehaviorFullScreenPrimary;
7306 [win setCollectionBehavior: b];
7307 fs_is_native = ns_use_native_fullscreen;
7312 - (void)toggleFullScreen: (id)sender
7320 NSTRACE ("[EmacsView toggleFullScreen:]");
7324 #ifdef HAVE_NATIVE_FS
7325 [[self window] toggleFullScreen:sender];
7331 onFirstScreen = [[w screen] isEqual:[[NSScreen screens] objectAtIndex:0]];
7334 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
7335 (FRAME_DEFAULT_FACE (f)),
7338 if (fs_state != FULLSCREEN_BOTH)
7340 NSScreen *screen = [w screen];
7342 #if defined (NS_IMPL_COCOA) && \
7343 MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7344 /* Hide ghost menu bar on secondary monitor? */
7345 if (! onFirstScreen)
7346 onFirstScreen = [NSScreen screensHaveSeparateSpaces];
7348 /* Hide dock and menubar if we are on the primary screen. */
7351 #ifdef NS_IMPL_COCOA
7352 NSApplicationPresentationOptions options
7353 = NSApplicationPresentationAutoHideDock
7354 | NSApplicationPresentationAutoHideMenuBar;
7356 [NSApp setPresentationOptions: options];
7358 [NSMenu setMenuBarVisible:NO];
7362 fw = [[EmacsFSWindow alloc]
7363 initWithContentRect:[w contentRectForFrameRect:wr]
7364 styleMask:NSWindowStyleMaskBorderless
7365 backing:NSBackingStoreBuffered
7369 [fw setContentView:[w contentView]];
7370 [fw setTitle:[w title]];
7371 [fw setDelegate:self];
7372 [fw setAcceptsMouseMovedEvents: YES];
7373 #if !defined (NS_IMPL_COCOA) || \
7374 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
7375 [fw useOptimizedDrawing: YES];
7377 [fw setBackgroundColor: col];
7378 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
7381 f->border_width = 0;
7382 FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
7383 tobar_height = FRAME_TOOLBAR_HEIGHT (f);
7384 FRAME_TOOLBAR_HEIGHT (f) = 0;
7388 [self windowWillEnterFullScreen];
7389 [fw makeKeyAndOrderFront:NSApp];
7390 [fw makeFirstResponder:self];
7392 r = [fw frameRectForContentRect:[screen frame]];
7393 [fw setFrame: r display:YES animate:ns_use_fullscreen_animation];
7394 [self windowDidEnterFullScreen];
7405 #ifdef NS_IMPL_COCOA
7406 [NSApp setPresentationOptions: NSApplicationPresentationDefault];
7408 [NSMenu setMenuBarVisible:YES];
7412 [w setContentView:[fw contentView]];
7413 [w setBackgroundColor: col];
7414 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
7417 f->border_width = bwidth;
7418 FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
7419 if (FRAME_EXTERNAL_TOOL_BAR (f))
7420 FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
7422 // to do: consider using [NSNotificationCenter postNotificationName:] to send notifications.
7424 [self windowWillExitFullScreen];
7425 [fw setFrame: [w frame] display:YES animate:ns_use_fullscreen_animation];
7427 [w makeKeyAndOrderFront:NSApp];
7428 [self windowDidExitFullScreen];
7429 [self updateFrameSize:YES];
7435 NSTRACE ("[EmacsView handleFS]");
7437 if (fs_state != emacsframe->want_fullscreen)
7439 if (fs_state == FULLSCREEN_BOTH)
7441 NSTRACE_MSG ("fs_state == FULLSCREEN_BOTH");
7442 [self toggleFullScreen:self];
7445 switch (emacsframe->want_fullscreen)
7447 case FULLSCREEN_BOTH:
7448 NSTRACE_MSG ("FULLSCREEN_BOTH");
7449 [self toggleFullScreen:self];
7451 case FULLSCREEN_WIDTH:
7452 NSTRACE_MSG ("FULLSCREEN_WIDTH");
7453 next_maximized = FULLSCREEN_WIDTH;
7454 if (fs_state != FULLSCREEN_BOTH)
7455 [[self window] performZoom:self];
7457 case FULLSCREEN_HEIGHT:
7458 NSTRACE_MSG ("FULLSCREEN_HEIGHT");
7459 next_maximized = FULLSCREEN_HEIGHT;
7460 if (fs_state != FULLSCREEN_BOTH)
7461 [[self window] performZoom:self];
7463 case FULLSCREEN_MAXIMIZED:
7464 NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
7465 next_maximized = FULLSCREEN_MAXIMIZED;
7466 if (fs_state != FULLSCREEN_BOTH)
7467 [[self window] performZoom:self];
7469 case FULLSCREEN_NONE:
7470 NSTRACE_MSG ("FULLSCREEN_NONE");
7471 if (fs_state != FULLSCREEN_BOTH)
7473 next_maximized = FULLSCREEN_NONE;
7474 [[self window] performZoom:self];
7479 emacsframe->want_fullscreen = FULLSCREEN_NONE;
7484 - (void) setFSValue: (int)value
7486 NSTRACE ("[EmacsView setFSValue:" NSTRACE_FMT_FSTYPE "]",
7487 NSTRACE_ARG_FSTYPE(value));
7489 Lisp_Object lval = Qnil;
7492 case FULLSCREEN_BOTH:
7495 case FULLSCREEN_WIDTH:
7498 case FULLSCREEN_HEIGHT:
7501 case FULLSCREEN_MAXIMIZED:
7505 store_frame_param (emacsframe, Qfullscreen, lval);
7509 - (void)mouseEntered: (NSEvent *)theEvent
7511 NSTRACE ("[EmacsView mouseEntered:]");
7513 FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7514 = EV_TIMESTAMP (theEvent);
7518 - (void)mouseExited: (NSEvent *)theEvent
7520 Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
7522 NSTRACE ("[EmacsView mouseExited:]");
7527 FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7528 = EV_TIMESTAMP (theEvent);
7530 if (emacsframe == hlinfo->mouse_face_mouse_frame)
7532 clear_mouse_face (hlinfo);
7533 hlinfo->mouse_face_mouse_frame = 0;
7540 NSTRACE ("[EmacsView menuDown:]");
7541 if (context_menu_value == -1)
7542 context_menu_value = [sender tag];
7545 NSInteger tag = [sender tag];
7546 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
7547 emacsframe->menu_bar_vector,
7551 ns_send_appdefined (-1);
7556 - (EmacsToolbar *)toolbar
7562 /* this gets called on toolbar button click */
7563 - toolbarClicked: (id)item
7566 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
7568 NSTRACE ("[EmacsView toolbarClicked:]");
7573 /* send first event (for some reason two needed) */
7574 theEvent = [[self window] currentEvent];
7575 emacs_event->kind = TOOL_BAR_EVENT;
7576 XSETFRAME (emacs_event->arg, emacsframe);
7577 EV_TRAILER (theEvent);
7579 emacs_event->kind = TOOL_BAR_EVENT;
7580 /* XSETINT (emacs_event->code, 0); */
7581 emacs_event->arg = AREF (emacsframe->tool_bar_items,
7582 idx + TOOL_BAR_ITEM_KEY);
7583 emacs_event->modifiers = EV_MODIFIERS (theEvent);
7584 EV_TRAILER (theEvent);
7589 - toggleToolbar: (id)sender
7591 NSTRACE ("[EmacsView toggleToolbar:]");
7596 emacs_event->kind = NS_NONKEY_EVENT;
7597 emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
7598 EV_TRAILER ((id)nil);
7603 - (void)drawRect: (NSRect)rect
7605 int x = NSMinX (rect), y = NSMinY (rect);
7606 int width = NSWidth (rect), height = NSHeight (rect);
7608 NSTRACE ("[EmacsView drawRect:" NSTRACE_FMT_RECT "]",
7609 NSTRACE_ARG_RECT(rect));
7611 if (!emacsframe || !emacsframe->output_data.ns)
7614 ns_clear_frame_area (emacsframe, x, y, width, height);
7616 expose_frame (emacsframe, x, y, width, height);
7620 drawRect: may be called (at least in OS X 10.5) for invisible
7621 views as well for some reason. Thus, do not infer visibility
7624 emacsframe->async_visible = 1;
7625 emacsframe->async_iconified = 0;
7630 /* NSDraggingDestination protocol methods. Actually this is not really a
7631 protocol, but a category of Object. O well... */
7633 -(NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
7635 NSTRACE ("[EmacsView draggingEntered:]");
7636 return NSDragOperationGeneric;
7640 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
7646 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
7651 NSEvent *theEvent = [[self window] currentEvent];
7653 NSDragOperation op = [sender draggingSourceOperationMask];
7656 NSTRACE ("[EmacsView performDragOperation:]");
7661 position = [self convertPoint: [sender draggingLocation] fromView: nil];
7662 x = lrint (position.x); y = lrint (position.y);
7664 pb = [sender draggingPasteboard];
7665 type = [pb availableTypeFromArray: ns_drag_types];
7667 if (! (op & (NSDragOperationMove|NSDragOperationDelete)) &&
7668 // URL drags contain all operations (0xf), don't allow all to be set.
7671 if (op & NSDragOperationLink)
7672 modifiers |= NSEventModifierFlagControl;
7673 if (op & NSDragOperationCopy)
7674 modifiers |= NSEventModifierFlagOption;
7675 if (op & NSDragOperationGeneric)
7676 modifiers |= NSEventModifierFlagCommand;
7679 modifiers = EV_MODIFIERS2 (modifiers);
7684 else if ([type isEqualToString: NSFilenamesPboardType])
7687 NSEnumerator *fenum;
7690 if (!(files = [pb propertyListForType: type]))
7693 fenum = [files objectEnumerator];
7694 while ( (file = [fenum nextObject]) )
7696 emacs_event->kind = DRAG_N_DROP_EVENT;
7697 XSETINT (emacs_event->x, x);
7698 XSETINT (emacs_event->y, y);
7699 ns_input_file = append2 (ns_input_file,
7700 build_string ([file UTF8String]));
7701 emacs_event->modifiers = modifiers;
7702 emacs_event->arg = list2 (Qfile, build_string ([file UTF8String]));
7703 EV_TRAILER (theEvent);
7707 else if ([type isEqualToString: NSURLPboardType])
7709 NSURL *url = [NSURL URLFromPasteboard: pb];
7710 if (url == nil) return NO;
7712 emacs_event->kind = DRAG_N_DROP_EVENT;
7713 XSETINT (emacs_event->x, x);
7714 XSETINT (emacs_event->y, y);
7715 emacs_event->modifiers = modifiers;
7716 emacs_event->arg = list2 (Qurl,
7717 build_string ([[url absoluteString]
7719 EV_TRAILER (theEvent);
7721 if ([url isFileURL] != NO)
7723 NSString *file = [url path];
7724 ns_input_file = append2 (ns_input_file,
7725 build_string ([file UTF8String]));
7729 else if ([type isEqualToString: NSStringPboardType]
7730 || [type isEqualToString: NSTabularTextPboardType])
7734 if (! (data = [pb stringForType: type]))
7737 emacs_event->kind = DRAG_N_DROP_EVENT;
7738 XSETINT (emacs_event->x, x);
7739 XSETINT (emacs_event->y, y);
7740 emacs_event->modifiers = modifiers;
7741 emacs_event->arg = list2 (Qnil, build_string ([data UTF8String]));
7742 EV_TRAILER (theEvent);
7747 fprintf (stderr, "Invalid data type in dragging pasteboard");
7753 - (id) validRequestorForSendType: (NSString *)typeSent
7754 returnType: (NSString *)typeReturned
7756 NSTRACE ("[EmacsView validRequestorForSendType:returnType:]");
7757 if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
7758 && typeReturned == nil)
7760 if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
7764 return [super validRequestorForSendType: typeSent
7765 returnType: typeReturned];
7769 /* The next two methods are part of NSServicesRequests informal protocol,
7770 supposedly called when a services menu item is chosen from this app.
7771 But this should not happen because we override the services menu with our
7772 own entries which call ns-perform-service.
7773 Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
7774 So let's at least stub them out until further investigation can be done. */
7776 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
7778 /* we could call ns_string_from_pasteboard(pboard) here but then it should
7779 be written into the buffer in place of the existing selection..
7780 ordinary service calls go through functions defined in ns-win.el */
7784 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
7786 NSArray *typesDeclared;
7789 NSTRACE ("[EmacsView writeSelectionToPasteboard:types:]");
7791 /* We only support NSStringPboardType */
7792 if ([types containsObject:NSStringPboardType] == NO) {
7796 val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7797 if (CONSP (val) && SYMBOLP (XCAR (val)))
7800 if (CONSP (val) && NILP (XCDR (val)))
7803 if (! STRINGP (val))
7806 typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
7807 [pb declareTypes:typesDeclared owner:nil];
7808 ns_string_to_pasteboard (pb, val);
7813 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
7814 (gives a miniaturized version of the window); currently we use the latter for
7815 frames whose active buffer doesn't correspond to any file
7816 (e.g., '*scratch*') */
7817 - setMiniwindowImage: (BOOL) setMini
7819 id image = [[self window] miniwindowImage];
7820 NSTRACE ("[EmacsView setMiniwindowImage:%d]", setMini);
7822 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
7823 about "AppleDockIconEnabled" notwithstanding, however the set message
7824 below has its effect nonetheless. */
7825 if (image != emacsframe->output_data.ns->miniimage)
7827 if (image && [image isKindOfClass: [EmacsImage class]])
7829 [[self window] setMiniwindowImage:
7830 setMini ? emacsframe->output_data.ns->miniimage : nil];
7837 - (void) setRows: (int) r andColumns: (int) c
7839 NSTRACE ("[EmacsView setRows:%d andColumns:%d]", r, c);
7844 - (int) fullscreenState
7849 @end /* EmacsView */
7853 /* ==========================================================================
7855 EmacsWindow implementation
7857 ========================================================================== */
7859 @implementation EmacsWindow
7861 #ifdef NS_IMPL_COCOA
7862 - (id)accessibilityAttributeValue:(NSString *)attribute
7864 Lisp_Object str = Qnil;
7865 struct frame *f = SELECTED_FRAME ();
7866 struct buffer *curbuf = XBUFFER (XWINDOW (f->selected_window)->contents);
7868 NSTRACE ("[EmacsWindow accessibilityAttributeValue:]");
7870 if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
7871 return NSAccessibilityTextFieldRole;
7873 if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]
7874 && curbuf && ! NILP (BVAR (curbuf, mark_active)))
7876 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7878 else if (curbuf && [attribute isEqualToString:NSAccessibilityValueAttribute])
7880 if (! NILP (BVAR (curbuf, mark_active)))
7881 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7885 ptrdiff_t start_byte = BUF_BEGV_BYTE (curbuf);
7886 ptrdiff_t byte_range = BUF_ZV_BYTE (curbuf) - start_byte;
7887 ptrdiff_t range = BUF_ZV (curbuf) - BUF_BEGV (curbuf);
7889 if (! NILP (BVAR (curbuf, enable_multibyte_characters)))
7890 str = make_uninit_multibyte_string (range, byte_range);
7892 str = make_uninit_string (range);
7893 /* To check: This returns emacs-utf-8, which is a superset of utf-8.
7894 Is this a problem? */
7895 memcpy (SDATA (str), BYTE_POS_ADDR (start_byte), byte_range);
7902 if (CONSP (str) && SYMBOLP (XCAR (str)))
7905 if (CONSP (str) && NILP (XCDR (str)))
7910 const char *utfStr = SSDATA (str);
7911 NSString *nsStr = [NSString stringWithUTF8String: utfStr];
7916 return [super accessibilityAttributeValue:attribute];
7918 #endif /* NS_IMPL_COCOA */
7920 /* Constrain size and placement of a frame.
7922 By returning the original "frameRect", the frame is not
7923 constrained. This can lead to unwanted situations where, for
7924 example, the menu bar covers the frame.
7926 The default implementation (accessed using "super") constrains the
7927 frame to the visible area of SCREEN, minus the menu bar (if
7928 present) and the Dock. Note that default implementation also calls
7929 windowWillResize, with the frame it thinks should have. (This can
7930 make the frame exit maximized mode.)
7932 Note that this should work in situations where multiple monitors
7933 are present. Common configurations are side-by-side monitors and a
7934 monitor on top of another (e.g. when a laptop is placed under a
7936 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
7938 NSTRACE ("[EmacsWindow constrainFrameRect:" NSTRACE_FMT_RECT " toScreen:]",
7939 NSTRACE_ARG_RECT (frameRect));
7941 #ifdef NS_IMPL_COCOA
7942 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7943 // If separate spaces is on, it is like each screen is independent. There is
7944 // no spanning of frames across screens.
7945 if ([NSScreen screensHaveSeparateSpaces])
7947 NSTRACE_MSG ("Screens have separate spaces");
7948 frameRect = [super constrainFrameRect:frameRect toScreen:screen];
7949 NSTRACE_RETURN_RECT (frameRect);
7955 return constrain_frame_rect(frameRect,
7956 [(EmacsView *)[self delegate] isFullscreen]);
7960 - (void)performZoom:(id)sender
7962 NSTRACE ("[EmacsWindow performZoom:]");
7964 return [super performZoom:sender];
7967 - (void)zoom:(id)sender
7969 NSTRACE ("[EmacsWindow zoom:]");
7971 ns_update_auto_hide_menu_bar();
7973 // Below are three zoom implementations. In the final commit, the
7974 // idea is that the last should be included.
7977 // Native zoom done using the standard zoom animation. Size of the
7978 // resulting frame reduced to accommodate the Dock and, if present,
7980 [super zoom:sender];
7983 // Native zoom done using the standard zoom animation, plus an
7984 // explicit resize to cover the full screen, except the menu-bar and
7985 // dock, if present.
7986 [super zoom:sender];
7988 // After the native zoom, resize the resulting frame to fill the
7989 // entire screen, except the menu-bar.
7991 // This works for all practical purposes. (The only minor oddity is
7992 // when transiting from full-height frame to a maximized, the
7993 // animation reduces the height of the frame slightly (to the 4
7994 // pixels needed to accommodate the Doc) before it snaps back into
7995 // full height. The user would need a very trained eye to spot
7997 NSScreen * screen = [self screen];
8000 int fs_state = [(EmacsView *)[self delegate] fullscreenState];
8002 NSTRACE_FSTYPE ("fullscreenState", fs_state);
8004 NSRect sr = [screen frame];
8005 struct EmacsMargins margins
8006 = ns_screen_margins_ignoring_hidden_dock(screen);
8008 NSRect wr = [self frame];
8009 NSTRACE_RECT ("Rect after zoom", wr);
8013 if (fs_state == FULLSCREEN_MAXIMIZED
8014 || fs_state == FULLSCREEN_HEIGHT)
8016 newWr.origin.y = sr.origin.y + margins.bottom;
8017 newWr.size.height = sr.size.height - margins.top - margins.bottom;
8020 if (fs_state == FULLSCREEN_MAXIMIZED
8021 || fs_state == FULLSCREEN_WIDTH)
8023 newWr.origin.x = sr.origin.x + margins.left;
8024 newWr.size.width = sr.size.width - margins.right - margins.left;
8027 if (newWr.size.width != wr.size.width
8028 || newWr.size.height != wr.size.height
8029 || newWr.origin.x != wr.origin.x
8030 || newWr.origin.y != wr.origin.y)
8032 NSTRACE_MSG ("New frame different");
8033 [self setFrame: newWr display: NO];
8037 // Non-native zoom which is done instantaneously. The resulting
8038 // frame covers the entire screen, except the menu-bar and dock, if
8040 NSScreen * screen = [self screen];
8043 NSRect sr = [screen frame];
8044 struct EmacsMargins margins
8045 = ns_screen_margins_ignoring_hidden_dock(screen);
8047 sr.size.height -= (margins.top + margins.bottom);
8048 sr.size.width -= (margins.left + margins.right);
8049 sr.origin.x += margins.left;
8050 sr.origin.y += margins.bottom;
8052 sr = [[self delegate] windowWillUseStandardFrame:self
8054 [self setFrame: sr display: NO];
8059 - (void)setFrame:(NSRect)windowFrame
8060 display:(BOOL)displayViews
8062 NSTRACE ("[EmacsWindow setFrame:" NSTRACE_FMT_RECT " display:%d]",
8063 NSTRACE_ARG_RECT (windowFrame), displayViews);
8065 [super setFrame:windowFrame display:displayViews];
8068 - (void)setFrame:(NSRect)windowFrame
8069 display:(BOOL)displayViews
8070 animate:(BOOL)performAnimation
8072 NSTRACE ("[EmacsWindow setFrame:" NSTRACE_FMT_RECT
8073 " display:%d performAnimation:%d]",
8074 NSTRACE_ARG_RECT (windowFrame), displayViews, performAnimation);
8076 [super setFrame:windowFrame display:displayViews animate:performAnimation];
8079 - (void)setFrameTopLeftPoint:(NSPoint)point
8081 NSTRACE ("[EmacsWindow setFrameTopLeftPoint:" NSTRACE_FMT_POINT "]",
8082 NSTRACE_ARG_POINT (point));
8084 [super setFrameTopLeftPoint:point];
8086 @end /* EmacsWindow */
8089 @implementation EmacsFSWindow
8091 - (BOOL)canBecomeKeyWindow
8096 - (BOOL)canBecomeMainWindow
8103 /* ==========================================================================
8105 EmacsScroller implementation
8107 ========================================================================== */
8110 @implementation EmacsScroller
8112 /* for repeat button push */
8113 #define SCROLL_BAR_FIRST_DELAY 0.5
8114 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
8116 + (CGFloat) scrollerWidth
8118 /* TODO: if we want to allow variable widths, this is the place to do it,
8119 however neither GNUstep nor Cocoa support it very well */
8121 #if !defined (NS_IMPL_COCOA) || \
8122 MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
8123 r = [NSScroller scrollerWidth];
8125 r = [NSScroller scrollerWidthForControlSize: NSControlSizeRegular
8126 scrollerStyle: NSScrollerStyleLegacy];
8131 - initFrame: (NSRect )r window: (Lisp_Object)nwin
8133 NSTRACE ("[EmacsScroller initFrame: window:]");
8135 if (r.size.width > r.size.height)
8140 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
8141 [self setContinuous: YES];
8142 [self setEnabled: YES];
8144 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
8145 locked against the top and bottom edges, and right edge on OS X, where
8146 scrollers are on right. */
8147 #ifdef NS_IMPL_GNUSTEP
8148 [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
8150 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
8153 window = XWINDOW (nwin);
8156 pixel_length = NSWidth (r);
8158 pixel_length = NSHeight (r);
8159 if (pixel_length == 0) pixel_length = 1;
8160 min_portion = 20 / pixel_length;
8162 frame = XFRAME (window->frame);
8163 if (FRAME_LIVE_P (frame))
8166 EmacsView *view = FRAME_NS_VIEW (frame);
8167 NSView *sview = [[view window] contentView];
8168 NSArray *subs = [sview subviews];
8170 /* disable optimization stopping redraw of other scrollbars */
8171 view->scrollbarsNeedingUpdate = 0;
8172 for (i =[subs count]-1; i >= 0; i--)
8173 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
8174 view->scrollbarsNeedingUpdate++;
8175 [sview addSubview: self];
8178 /* [self setFrame: r]; */
8184 - (void)setFrame: (NSRect)newRect
8186 NSTRACE ("[EmacsScroller setFrame:]");
8188 /* block_input (); */
8190 pixel_length = NSWidth (newRect);
8192 pixel_length = NSHeight (newRect);
8193 if (pixel_length == 0) pixel_length = 1;
8194 min_portion = 20 / pixel_length;
8195 [super setFrame: newRect];
8196 /* unblock_input (); */
8202 NSTRACE ("[EmacsScroller dealloc]");
8206 wset_horizontal_scroll_bar (window, Qnil);
8208 wset_vertical_scroll_bar (window, Qnil);
8217 NSTRACE ("[EmacsScroller condemn]");
8225 NSTRACE ("[EmacsScroller reprieve]");
8233 NSTRACE ("[EmacsScroller judge]");
8234 bool ret = condemned;
8239 /* ensure other scrollbar updates after deletion */
8240 view = (EmacsView *)FRAME_NS_VIEW (frame);
8242 view->scrollbarsNeedingUpdate++;
8246 wset_horizontal_scroll_bar (window, Qnil);
8248 wset_vertical_scroll_bar (window, Qnil);
8251 [self removeFromSuperview];
8259 - (void)resetCursorRects
8261 NSRect visible = [self visibleRect];
8262 NSTRACE ("[EmacsScroller resetCursorRects]");
8264 if (!NSIsEmptyRect (visible))
8265 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
8266 [[NSCursor arrowCursor] setOnMouseEntered: YES];
8270 - (int) checkSamePosition: (int) position portion: (int) portion
8273 return em_position ==position && em_portion ==portion && em_whole ==whole
8274 && portion != whole; /* needed for resize empty buf */
8278 - setPosition: (int)position portion: (int)portion whole: (int)whole
8280 NSTRACE ("[EmacsScroller setPosition:portion:whole:]");
8282 em_position = position;
8283 em_portion = portion;
8286 if (portion >= whole)
8288 #ifdef NS_IMPL_COCOA
8289 [self setKnobProportion: 1.0];
8290 [self setDoubleValue: 1.0];
8292 [self setFloatValue: 0.0 knobProportion: 1.0];
8299 portion = max ((float)whole*min_portion/pixel_length, portion);
8300 pos = (float)position / (whole - portion);
8301 por = (CGFloat)portion/whole;
8302 #ifdef NS_IMPL_COCOA
8303 [self setKnobProportion: por];
8304 [self setDoubleValue: pos];
8306 [self setFloatValue: pos knobProportion: por];
8313 /* set up emacs_event */
8314 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
8318 NSTRACE ("[EmacsScroller sendScrollEventAtLoc:fromEvent:]");
8323 emacs_event->part = last_hit_part;
8324 emacs_event->code = 0;
8325 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
8326 XSETWINDOW (win, window);
8327 emacs_event->frame_or_window = win;
8328 emacs_event->timestamp = EV_TIMESTAMP (e);
8329 emacs_event->arg = Qnil;
8333 emacs_event->kind = HORIZONTAL_SCROLL_BAR_CLICK_EVENT;
8334 XSETINT (emacs_event->x, em_whole * loc / pixel_length);
8335 XSETINT (emacs_event->y, em_whole);
8339 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
8340 XSETINT (emacs_event->x, loc);
8341 XSETINT (emacs_event->y, pixel_length-20);
8346 n_emacs_events_pending++;
8347 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
8350 hold_event (emacs_event);
8351 EVENT_INIT (*emacs_event);
8352 ns_send_appdefined (-1);
8356 /* called manually thru timer to implement repeated button action w/hold-down */
8357 - repeatScroll: (NSTimer *)scrollEntry
8359 NSEvent *e = [[self window] currentEvent];
8360 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
8361 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
8363 NSTRACE ("[EmacsScroller repeatScroll:]");
8365 /* clear timer if need be */
8366 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
8368 [scroll_repeat_entry invalidate];
8369 [scroll_repeat_entry release];
8370 scroll_repeat_entry = nil;
8376 = [[NSTimer scheduledTimerWithTimeInterval:
8377 SCROLL_BAR_CONTINUOUS_DELAY
8379 selector: @selector (repeatScroll:)
8385 [self sendScrollEventAtLoc: 0 fromEvent: e];
8390 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
8391 mouseDragged events without going into a modal loop. */
8392 - (void)mouseDown: (NSEvent *)e
8395 /* hitPart is only updated AFTER event is passed on */
8396 NSScrollerPart part = [self testPart: [e locationInWindow]];
8397 CGFloat inc = 0.0, loc, kloc, pos;
8400 NSTRACE ("[EmacsScroller mouseDown:]");
8404 case NSScrollerDecrementPage:
8405 last_hit_part = horizontal ? scroll_bar_before_handle : scroll_bar_above_handle; break;
8406 case NSScrollerIncrementPage:
8407 last_hit_part = horizontal ? scroll_bar_after_handle : scroll_bar_below_handle; break;
8408 case NSScrollerDecrementLine:
8409 last_hit_part = horizontal ? scroll_bar_left_arrow : scroll_bar_up_arrow; break;
8410 case NSScrollerIncrementLine:
8411 last_hit_part = horizontal ? scroll_bar_right_arrow : scroll_bar_down_arrow; break;
8412 case NSScrollerKnob:
8413 last_hit_part = horizontal ? scroll_bar_horizontal_handle : scroll_bar_handle; break;
8414 case NSScrollerKnobSlot: /* GNUstep-only */
8415 last_hit_part = scroll_bar_move_ratio; break;
8416 default: /* NSScrollerNoPart? */
8417 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
8422 if (part == NSScrollerKnob || part == NSScrollerKnobSlot)
8424 /* handle, or on GNUstep possibly slot */
8425 NSEvent *fake_event;
8428 /* compute float loc in slot and mouse offset on knob */
8429 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
8433 length = NSWidth (sr);
8434 loc = ([e locationInWindow].x - NSMinX (sr));
8438 length = NSHeight (sr);
8439 loc = length - ([e locationInWindow].y - NSMinY (sr));
8447 else if (loc >= length)
8457 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
8460 kloc = ([e locationInWindow].x - NSMinX (kr));
8462 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
8464 last_mouse_offset = kloc;
8466 if (part != NSScrollerKnob)
8467 /* this is a slot click on GNUstep: go straight there */
8470 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
8471 fake_event = [NSEvent mouseEventWithType: NSEventTypeLeftMouseUp
8472 location: [e locationInWindow]
8473 modifierFlags: [e modifierFlags]
8474 timestamp: [e timestamp]
8475 windowNumber: [e windowNumber]
8476 context: [e context]
8477 eventNumber: [e eventNumber]
8478 clickCount: [e clickCount]
8479 pressure: [e pressure]];
8480 [super mouseUp: fake_event];
8484 pos = 0; /* ignored */
8486 /* set a timer to repeat, as we can't let superclass do this modally */
8488 = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
8490 selector: @selector (repeatScroll:)
8496 if (part != NSScrollerKnob)
8497 [self sendScrollEventAtLoc: pos fromEvent: e];
8501 /* Called as we manually track scroller drags, rather than superclass. */
8502 - (void)mouseDragged: (NSEvent *)e
8508 NSTRACE ("[EmacsScroller mouseDragged:]");
8510 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
8515 length = NSWidth (sr);
8516 loc = ([e locationInWindow].x - NSMinX (sr));
8520 length = NSHeight (sr);
8521 loc = length - ([e locationInWindow].y - NSMinY (sr));
8528 else if (loc >= length + last_mouse_offset)
8530 loc = length + last_mouse_offset;
8533 pos = (loc - last_mouse_offset);
8534 [self sendScrollEventAtLoc: pos fromEvent: e];
8538 - (void)mouseUp: (NSEvent *)e
8540 NSTRACE ("[EmacsScroller mouseUp:]");
8542 if (scroll_repeat_entry)
8544 [scroll_repeat_entry invalidate];
8545 [scroll_repeat_entry release];
8546 scroll_repeat_entry = nil;
8548 last_hit_part = scroll_bar_above_handle;
8552 /* treat scrollwheel events in the bar as though they were in the main window */
8553 - (void) scrollWheel: (NSEvent *)theEvent
8555 NSTRACE ("[EmacsScroller scrollWheel:]");
8557 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
8558 [view mouseDown: theEvent];
8561 @end /* EmacsScroller */
8564 #ifdef NS_IMPL_GNUSTEP
8565 /* Dummy class to get rid of startup warnings. */
8566 @implementation EmacsDocument
8572 /* ==========================================================================
8574 Font-related functions; these used to be in nsfaces.m
8576 ========================================================================== */
8580 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
8582 struct font *font = XFONT_OBJECT (font_object);
8583 EmacsView *view = FRAME_NS_VIEW (f);
8584 int font_ascent, font_descent;
8587 fontset = fontset_from_font (font_object);
8588 FRAME_FONTSET (f) = fontset;
8590 if (FRAME_FONT (f) == font)
8591 /* This font is already set in frame F. There's nothing more to
8595 FRAME_FONT (f) = font;
8597 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
8598 FRAME_COLUMN_WIDTH (f) = font->average_width;
8599 get_font_ascent_descent (font, &font_ascent, &font_descent);
8600 FRAME_LINE_HEIGHT (f) = font_ascent + font_descent;
8602 /* Compute the scroll bar width in character columns. */
8603 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
8605 int wid = FRAME_COLUMN_WIDTH (f);
8606 FRAME_CONFIG_SCROLL_BAR_COLS (f)
8607 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
8611 int wid = FRAME_COLUMN_WIDTH (f);
8612 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
8615 /* Compute the scroll bar height in character lines. */
8616 if (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) > 0)
8618 int height = FRAME_LINE_HEIGHT (f);
8619 FRAME_CONFIG_SCROLL_BAR_LINES (f)
8620 = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + height - 1) / height;
8624 int height = FRAME_LINE_HEIGHT (f);
8625 FRAME_CONFIG_SCROLL_BAR_LINES (f) = (14 + height - 1) / height;
8628 /* Now make the frame display the given font. */
8629 if (FRAME_NS_WINDOW (f) != 0 && ! [view isFullscreen])
8630 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
8631 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 3,
8638 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
8639 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
8643 ns_xlfd_to_fontname (const char *xlfd)
8644 /* --------------------------------------------------------------------------
8645 Convert an X font name (XLFD) to an NS font name.
8646 Only family is used.
8647 The string returned is temporarily allocated.
8648 -------------------------------------------------------------------------- */
8650 char *name = xmalloc (180);
8654 if (!strncmp (xlfd, "--", 2))
8655 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
8657 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
8659 /* stopgap for malformed XLFD input */
8660 if (strlen (name) == 0)
8661 strcpy (name, "Monaco");
8663 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
8664 also uppercase after '-' or ' ' */
8665 name[0] = c_toupper (name[0]);
8666 for (len =strlen (name), i =0; i<len; i++)
8672 name[i+1] = c_toupper (name[i+1]);
8674 else if (name[i] == '_')
8678 name[i+1] = c_toupper (name[i+1]);
8681 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
8682 ret = [[NSString stringWithUTF8String: name] UTF8String];
8689 syms_of_nsterm (void)
8691 NSTRACE ("syms_of_nsterm");
8693 ns_antialias_threshold = 10.0;
8695 /* from 23+ we need to tell emacs what modifiers there are.. */
8696 DEFSYM (Qmodifier_value, "modifier-value");
8697 DEFSYM (Qalt, "alt");
8698 DEFSYM (Qhyper, "hyper");
8699 DEFSYM (Qmeta, "meta");
8700 DEFSYM (Qsuper, "super");
8701 DEFSYM (Qcontrol, "control");
8702 DEFSYM (QUTF8_STRING, "UTF8_STRING");
8704 DEFSYM (Qfile, "file");
8705 DEFSYM (Qurl, "url");
8707 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
8708 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
8709 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
8710 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
8711 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
8713 DEFVAR_LISP ("ns-input-file", ns_input_file,
8714 "The file specified in the last NS event.");
8715 ns_input_file =Qnil;
8717 DEFVAR_LISP ("ns-working-text", ns_working_text,
8718 "String for visualizing working composition sequence.");
8719 ns_working_text =Qnil;
8721 DEFVAR_LISP ("ns-input-font", ns_input_font,
8722 "The font specified in the last NS event.");
8723 ns_input_font =Qnil;
8725 DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
8726 "The fontsize specified in the last NS event.");
8727 ns_input_fontsize =Qnil;
8729 DEFVAR_LISP ("ns-input-line", ns_input_line,
8730 "The line specified in the last NS event.");
8731 ns_input_line =Qnil;
8733 DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
8734 "The service name specified in the last NS event.");
8735 ns_input_spi_name =Qnil;
8737 DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
8738 "The service argument specified in the last NS event.");
8739 ns_input_spi_arg =Qnil;
8741 DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
8742 "This variable describes the behavior of the alternate or option key.\n\
8743 Set to the symbol control, meta, alt, super, or hyper means it is taken to be\n\
8745 Set to none means that the alternate / option key is not interpreted by Emacs\n\
8746 at all, allowing it to be used at a lower level for accented character entry.");
8747 ns_alternate_modifier = Qmeta;
8749 DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
8750 "This variable describes the behavior of the right alternate or option key.\n\
8751 Set to the symbol control, meta, alt, super, or hyper means it is taken to be\n\
8753 Set to left means be the same key as `ns-alternate-modifier'.\n\
8754 Set to none means that the alternate / option key is not interpreted by Emacs\n\
8755 at all, allowing it to be used at a lower level for accented character entry.");
8756 ns_right_alternate_modifier = Qleft;
8758 DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
8759 "This variable describes the behavior of the command key.\n\
8760 Set to the symbol control, meta, alt, super, or hyper means it is taken to be\n\
8762 ns_command_modifier = Qsuper;
8764 DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
8765 "This variable describes the behavior of the right command key.\n\
8766 Set to the symbol control, meta, alt, super, or hyper means it is taken to be\n\
8768 Set to left means be the same key as `ns-command-modifier'.\n\
8769 Set to none means that the command / option key is not interpreted by Emacs\n\
8770 at all, allowing it to be used at a lower level for accented character entry.");
8771 ns_right_command_modifier = Qleft;
8773 DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
8774 "This variable describes the behavior of the control key.\n\
8775 Set to the symbol control, meta, alt, super, or hyper means it is taken to be\n\
8777 ns_control_modifier = Qcontrol;
8779 DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
8780 "This variable describes the behavior of the right control key.\n\
8781 Set to the symbol control, meta, alt, super, or hyper means it is taken to be\n\
8783 Set to left means be the same key as `ns-control-modifier'.\n\
8784 Set to none means that the control / option key is not interpreted by Emacs\n\
8785 at all, allowing it to be used at a lower level for accented character entry.");
8786 ns_right_control_modifier = Qleft;
8788 DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
8789 "This variable describes the behavior of the function key (on laptops).\n\
8790 Set to the symbol control, meta, alt, super, or hyper means it is taken to be\n\
8792 Set to none means that the function key is not interpreted by Emacs at all,\n\
8793 allowing it to be used at a lower level for accented character entry.");
8794 ns_function_modifier = Qnone;
8796 DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
8797 "Non-nil (the default) means to render text antialiased.");
8798 ns_antialias_text = Qt;
8800 DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
8801 "Whether to confirm application quit using dialog.");
8802 ns_confirm_quit = Qnil;
8804 DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
8805 doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
8806 Only works on OSX 10.6 or later. */);
8807 ns_auto_hide_menu_bar = Qnil;
8809 DEFVAR_BOOL ("ns-use-native-fullscreen", ns_use_native_fullscreen,
8810 doc: /*Non-nil means to use native fullscreen on OSX >= 10.7.
8811 Nil means use fullscreen the old (< 10.7) way. The old way works better with
8812 multiple monitors, but lacks tool bar. This variable is ignored on OSX < 10.7.
8813 Default is t for OSX >= 10.7, nil otherwise. */);
8814 #ifdef HAVE_NATIVE_FS
8815 ns_use_native_fullscreen = YES;
8817 ns_use_native_fullscreen = NO;
8819 ns_last_use_native_fullscreen = ns_use_native_fullscreen;
8821 DEFVAR_BOOL ("ns-use-fullscreen-animation", ns_use_fullscreen_animation,
8822 doc: /*Non-nil means use animation on non-native fullscreen.
8823 For native fullscreen, this does nothing.
8824 Default is nil. */);
8825 ns_use_fullscreen_animation = NO;
8827 DEFVAR_BOOL ("ns-use-srgb-colorspace", ns_use_srgb_colorspace,
8828 doc: /*Non-nil means to use sRGB colorspace on OSX >= 10.7.
8829 Note that this does not apply to images.
8830 This variable is ignored on OSX < 10.7 and GNUstep. */);
8831 ns_use_srgb_colorspace = YES;
8833 /* TODO: move to common code */
8834 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
8835 doc: /* Which toolkit scroll bars Emacs uses, if any.
8836 A value of nil means Emacs doesn't use toolkit scroll bars.
8837 With the X Window system, the value is a symbol describing the
8838 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
8839 With MS Windows or Nextstep, the value is t. */);
8840 Vx_toolkit_scroll_bars = Qt;
8842 DEFVAR_BOOL ("x-use-underline-position-properties",
8843 x_use_underline_position_properties,
8844 doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
8845 A value of nil means ignore them. If you encounter fonts with bogus
8846 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
8847 to 4.1, set this to nil. */);
8848 x_use_underline_position_properties = 0;
8850 DEFVAR_BOOL ("x-underline-at-descent-line",
8851 x_underline_at_descent_line,
8852 doc: /* Non-nil means to draw the underline at the same place as the descent line.
8853 A value of nil means to draw the underline according to the value of the
8854 variable `x-use-underline-position-properties', which is usually at the
8855 baseline level. The default value is nil. */);
8856 x_underline_at_descent_line = 0;
8858 /* Tell Emacs about this window system. */
8859 Fprovide (Qns, Qnil);
8861 DEFSYM (Qcocoa, "cocoa");
8862 DEFSYM (Qgnustep, "gnustep");
8864 #ifdef NS_IMPL_COCOA
8865 Fprovide (Qcocoa, Qnil);
8868 Fprovide (Qgnustep, Qnil);