1 /* NeXT/Open/GNUstep / macOS communication module. -*- coding: utf-8 -*-
3 Copyright (C) 1989, 1993-1994, 2005-2006, 2008-2017 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 macOS/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
71 static EmacsMenu *dockMenu;
73 static EmacsMenu *mainMenu;
76 /* ==========================================================================
78 NSTRACE, Trace support.
80 ========================================================================== */
84 /* The following use "volatile" since they can be accessed from
86 volatile int nstrace_num = 0;
87 volatile int nstrace_depth = 0;
89 /* When 0, no trace is emitted. This is used by NSTRACE_WHEN and
90 NSTRACE_UNLESS to silence functions called.
92 TODO: This should really be a thread-local variable, to avoid that
93 a function with disabled trace thread silence trace output in
94 another. However, in practice this seldom is a problem. */
95 volatile int nstrace_enabled_global = 1;
97 /* Called when nstrace_enabled goes out of scope. */
98 void nstrace_leave(int * pointer_to_nstrace_enabled)
100 if (*pointer_to_nstrace_enabled)
107 /* Called when nstrace_saved_enabled_global goes out of scope. */
108 void nstrace_restore_global_trace_state(int * pointer_to_saved_enabled_global)
110 nstrace_enabled_global = *pointer_to_saved_enabled_global;
114 char const * nstrace_fullscreen_type_name (int fs_type)
118 case -1: return "-1";
119 case FULLSCREEN_NONE: return "FULLSCREEN_NONE";
120 case FULLSCREEN_WIDTH: return "FULLSCREEN_WIDTH";
121 case FULLSCREEN_HEIGHT: return "FULLSCREEN_HEIGHT";
122 case FULLSCREEN_BOTH: return "FULLSCREEN_BOTH";
123 case FULLSCREEN_MAXIMIZED: return "FULLSCREEN_MAXIMIZED";
124 default: return "FULLSCREEN_?????";
130 /* ==========================================================================
132 NSColor, EmacsColor category.
134 ========================================================================== */
135 @implementation NSColor (EmacsColor)
136 + (NSColor *)colorForEmacsRed:(CGFloat)red green:(CGFloat)green
137 blue:(CGFloat)blue alpha:(CGFloat)alpha
140 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
141 if (ns_use_srgb_colorspace)
142 return [NSColor colorWithSRGBRed: red
148 return [NSColor colorWithCalibratedRed: red
154 - (NSColor *)colorUsingDefaultColorSpace
157 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
158 if (ns_use_srgb_colorspace)
159 return [self colorUsingColorSpace: [NSColorSpace sRGBColorSpace]];
162 return [self colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
167 /* ==========================================================================
171 ========================================================================== */
173 /* Convert a symbol indexed with an NSxxx value to a value as defined
174 in keyboard.c (lispy_function_key). I hope this is a correct way
175 of doing things... */
176 static unsigned convert_ns_to_X_keysym[] =
178 NSHomeFunctionKey, 0x50,
179 NSLeftArrowFunctionKey, 0x51,
180 NSUpArrowFunctionKey, 0x52,
181 NSRightArrowFunctionKey, 0x53,
182 NSDownArrowFunctionKey, 0x54,
183 NSPageUpFunctionKey, 0x55,
184 NSPageDownFunctionKey, 0x56,
185 NSEndFunctionKey, 0x57,
186 NSBeginFunctionKey, 0x58,
187 NSSelectFunctionKey, 0x60,
188 NSPrintFunctionKey, 0x61,
189 NSClearLineFunctionKey, 0x0B,
190 NSExecuteFunctionKey, 0x62,
191 NSInsertFunctionKey, 0x63,
192 NSUndoFunctionKey, 0x65,
193 NSRedoFunctionKey, 0x66,
194 NSMenuFunctionKey, 0x67,
195 NSFindFunctionKey, 0x68,
196 NSHelpFunctionKey, 0x6A,
197 NSBreakFunctionKey, 0x6B,
199 NSF1FunctionKey, 0xBE,
200 NSF2FunctionKey, 0xBF,
201 NSF3FunctionKey, 0xC0,
202 NSF4FunctionKey, 0xC1,
203 NSF5FunctionKey, 0xC2,
204 NSF6FunctionKey, 0xC3,
205 NSF7FunctionKey, 0xC4,
206 NSF8FunctionKey, 0xC5,
207 NSF9FunctionKey, 0xC6,
208 NSF10FunctionKey, 0xC7,
209 NSF11FunctionKey, 0xC8,
210 NSF12FunctionKey, 0xC9,
211 NSF13FunctionKey, 0xCA,
212 NSF14FunctionKey, 0xCB,
213 NSF15FunctionKey, 0xCC,
214 NSF16FunctionKey, 0xCD,
215 NSF17FunctionKey, 0xCE,
216 NSF18FunctionKey, 0xCF,
217 NSF19FunctionKey, 0xD0,
218 NSF20FunctionKey, 0xD1,
219 NSF21FunctionKey, 0xD2,
220 NSF22FunctionKey, 0xD3,
221 NSF23FunctionKey, 0xD4,
222 NSF24FunctionKey, 0xD5,
224 NSBackspaceCharacter, 0x08, /* 8: Not on some KBs. */
225 NSDeleteCharacter, 0xFF, /* 127: Big 'delete' key upper right. */
226 NSDeleteFunctionKey, 0x9F, /* 63272: Del forw key off main array. */
228 NSTabCharacter, 0x09,
229 0x19, 0x09, /* left tab->regular since pass shift */
230 NSCarriageReturnCharacter, 0x0D,
231 NSNewlineCharacter, 0x0D,
232 NSEnterCharacter, 0x8D,
234 0x41|NSEventModifierFlagNumericPad, 0xAE, /* KP_Decimal */
235 0x43|NSEventModifierFlagNumericPad, 0xAA, /* KP_Multiply */
236 0x45|NSEventModifierFlagNumericPad, 0xAB, /* KP_Add */
237 0x4B|NSEventModifierFlagNumericPad, 0xAF, /* KP_Divide */
238 0x4E|NSEventModifierFlagNumericPad, 0xAD, /* KP_Subtract */
239 0x51|NSEventModifierFlagNumericPad, 0xBD, /* KP_Equal */
240 0x52|NSEventModifierFlagNumericPad, 0xB0, /* KP_0 */
241 0x53|NSEventModifierFlagNumericPad, 0xB1, /* KP_1 */
242 0x54|NSEventModifierFlagNumericPad, 0xB2, /* KP_2 */
243 0x55|NSEventModifierFlagNumericPad, 0xB3, /* KP_3 */
244 0x56|NSEventModifierFlagNumericPad, 0xB4, /* KP_4 */
245 0x57|NSEventModifierFlagNumericPad, 0xB5, /* KP_5 */
246 0x58|NSEventModifierFlagNumericPad, 0xB6, /* KP_6 */
247 0x59|NSEventModifierFlagNumericPad, 0xB7, /* KP_7 */
248 0x5B|NSEventModifierFlagNumericPad, 0xB8, /* KP_8 */
249 0x5C|NSEventModifierFlagNumericPad, 0xB9, /* KP_9 */
251 0x1B, 0x1B /* escape */
254 /* On macOS picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
255 the maximum font size to NOT antialias. On GNUstep there is currently
256 no way to control this behavior. */
257 float ns_antialias_threshold;
259 NSArray *ns_send_types = 0, *ns_return_types = 0;
260 static NSArray *ns_drag_types = 0;
261 NSString *ns_app_name = @"Emacs"; /* default changed later */
263 /* Display variables */
264 struct ns_display_info *x_display_list; /* Chain of existing displays */
265 long context_menu_value = 0;
268 static struct frame *ns_updating_frame;
269 static NSView *focus_view = NULL;
270 static int ns_window_num = 0;
271 #ifdef NS_IMPL_GNUSTEP
272 static NSRect uRect; // TODO: This is dead, remove it?
274 static BOOL gsaved = NO;
275 static BOOL ns_fake_keydown = NO;
277 static BOOL ns_menu_bar_is_hidden = NO;
279 /*static int debug_lock = 0; */
282 static BOOL send_appdefined = YES;
283 #define NO_APPDEFINED_DATA (-8)
284 static int last_appdefined_event_data = NO_APPDEFINED_DATA;
285 static NSTimer *timed_entry = 0;
286 static NSTimer *scroll_repeat_entry = nil;
287 static fd_set select_readfds, select_writefds;
288 enum { SELECT_HAVE_READ = 1, SELECT_HAVE_WRITE = 2, SELECT_HAVE_TMO = 4 };
289 static int select_nfds = 0, select_valid = 0;
290 static struct timespec select_timeout = { 0, 0 };
291 static int selfds[2] = { -1, -1 };
292 static pthread_mutex_t select_mutex;
293 static NSAutoreleasePool *outerpool;
294 static struct input_event *emacs_event = NULL;
295 static struct input_event *q_event_ptr = NULL;
296 static int n_emacs_events_pending = 0;
297 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
298 *ns_pending_service_args;
299 static BOOL ns_do_open_file = NO;
300 static BOOL ns_last_use_native_fullscreen;
302 /* Non-zero means that a HELP_EVENT has been generated since Emacs
305 static BOOL any_help_event_p = NO;
308 struct input_event *q;
314 static NSString *represented_filename = nil;
315 static struct frame *represented_frame = 0;
319 * State for pending menu activation:
320 * MENU_NONE Normal state
321 * MENU_PENDING A menu has been clicked on, but has been canceled so we can
322 * run lisp to update the menu.
323 * MENU_OPENING Menu is up to date, and the click event is redone so the menu
327 #define MENU_PENDING 1
328 #define MENU_OPENING 2
329 static int menu_will_open_state = MENU_NONE;
331 /* Saved position for menu click. */
332 static CGPoint menu_mouse_point;
335 /* Convert modifiers in a NeXTstep event to emacs style modifiers. */
336 #define NS_FUNCTION_KEY_MASK 0x800000
337 #define NSLeftControlKeyMask (0x000001 | NSEventModifierFlagControl)
338 #define NSRightControlKeyMask (0x002000 | NSEventModifierFlagControl)
339 #define NSLeftCommandKeyMask (0x000008 | NSEventModifierFlagCommand)
340 #define NSRightCommandKeyMask (0x000010 | NSEventModifierFlagCommand)
341 #define NSLeftAlternateKeyMask (0x000020 | NSEventModifierFlagOption)
342 #define NSRightAlternateKeyMask (0x000040 | NSEventModifierFlagOption)
343 #define EV_MODIFIERS2(flags) \
344 (((flags & NSEventModifierFlagHelp) ? \
345 hyper_modifier : 0) \
346 | (!EQ (ns_right_alternate_modifier, Qleft) && \
347 ((flags & NSRightAlternateKeyMask) \
348 == NSRightAlternateKeyMask) ? \
349 parse_solitary_modifier (ns_right_alternate_modifier) : 0) \
350 | ((flags & NSEventModifierFlagOption) ? \
351 parse_solitary_modifier (ns_alternate_modifier) : 0) \
352 | ((flags & NSEventModifierFlagShift) ? \
353 shift_modifier : 0) \
354 | (!EQ (ns_right_control_modifier, Qleft) && \
355 ((flags & NSRightControlKeyMask) \
356 == NSRightControlKeyMask) ? \
357 parse_solitary_modifier (ns_right_control_modifier) : 0) \
358 | ((flags & NSEventModifierFlagControl) ? \
359 parse_solitary_modifier (ns_control_modifier) : 0) \
360 | ((flags & NS_FUNCTION_KEY_MASK) ? \
361 parse_solitary_modifier (ns_function_modifier) : 0) \
362 | (!EQ (ns_right_command_modifier, Qleft) && \
363 ((flags & NSRightCommandKeyMask) \
364 == NSRightCommandKeyMask) ? \
365 parse_solitary_modifier (ns_right_command_modifier) : 0) \
366 | ((flags & NSEventModifierFlagCommand) ? \
367 parse_solitary_modifier (ns_command_modifier):0))
368 #define EV_MODIFIERS(e) EV_MODIFIERS2 ([e modifierFlags])
370 #define EV_UDMODIFIERS(e) \
371 ((([e type] == NSEventTypeLeftMouseDown) ? down_modifier : 0) \
372 | (([e type] == NSEventTypeRightMouseDown) ? down_modifier : 0) \
373 | (([e type] == NSEventTypeOtherMouseDown) ? down_modifier : 0) \
374 | (([e type] == NSEventTypeLeftMouseDragged) ? down_modifier : 0) \
375 | (([e type] == NSEventTypeRightMouseDragged) ? down_modifier : 0) \
376 | (([e type] == NSEventTypeOtherMouseDragged) ? down_modifier : 0) \
377 | (([e type] == NSEventTypeLeftMouseUp) ? up_modifier : 0) \
378 | (([e type] == NSEventTypeRightMouseUp) ? up_modifier : 0) \
379 | (([e type] == NSEventTypeOtherMouseUp) ? up_modifier : 0))
381 #define EV_BUTTON(e) \
382 ((([e type] == NSEventTypeLeftMouseDown) || ([e type] == NSEventTypeLeftMouseUp)) ? 0 : \
383 (([e type] == NSEventTypeRightMouseDown) || ([e type] == NSEventTypeRightMouseUp)) ? 2 : \
384 [e buttonNumber] - 1)
386 /* Convert the time field to a timestamp in milliseconds. */
387 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
389 /* This is a piece of code which is common to all the event handling
390 methods. Maybe it should even be a function. */
391 #define EV_TRAILER(e) \
393 XSETFRAME (emacs_event->frame_or_window, emacsframe); \
397 #define EV_TRAILER2(e) \
399 if (e) emacs_event->timestamp = EV_TIMESTAMP (e); \
402 Lisp_Object tem = Vinhibit_quit; \
403 Vinhibit_quit = Qt; \
404 n_emacs_events_pending++; \
405 kbd_buffer_store_event_hold (emacs_event, q_event_ptr); \
406 Vinhibit_quit = tem; \
409 hold_event (emacs_event); \
410 EVENT_INIT (*emacs_event); \
411 ns_send_appdefined (-1); \
414 /* TODO: get rid of need for these forward declarations */
415 static void ns_condemn_scroll_bars (struct frame *f);
416 static void ns_judge_scroll_bars (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)
440 ns_finish_events (void)
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 /* macOS 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 macOS 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. macOS 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 /* macOS (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 macOS, 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 Mac OS X 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];
1428 /* --------------------------------------------------------------------------
1429 Ensure the bell is hidden.
1430 -------------------------------------------------------------------------- */
1432 NSTRACE ("hide_bell");
1434 if (bell_view != nil)
1441 /* ==========================================================================
1443 Frame / window manager related functions
1445 ========================================================================== */
1449 ns_raise_frame (struct frame *f)
1450 /* --------------------------------------------------------------------------
1451 Bring window to foreground and make it active
1452 -------------------------------------------------------------------------- */
1456 check_window_system (f);
1457 view = FRAME_NS_VIEW (f);
1459 if (FRAME_VISIBLE_P (f))
1460 [[view window] makeKeyAndOrderFront: NSApp];
1466 ns_lower_frame (struct frame *f)
1467 /* --------------------------------------------------------------------------
1469 -------------------------------------------------------------------------- */
1473 check_window_system (f);
1474 view = FRAME_NS_VIEW (f);
1476 [[view window] orderBack: NSApp];
1482 ns_frame_raise_lower (struct frame *f, bool raise)
1483 /* --------------------------------------------------------------------------
1485 -------------------------------------------------------------------------- */
1487 NSTRACE ("ns_frame_raise_lower");
1497 ns_frame_rehighlight (struct frame *frame)
1498 /* --------------------------------------------------------------------------
1499 External (hook): called on things like window switching within frame
1500 -------------------------------------------------------------------------- */
1502 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
1503 struct frame *old_highlight = dpyinfo->x_highlight_frame;
1505 NSTRACE ("ns_frame_rehighlight");
1506 if (dpyinfo->x_focus_frame)
1508 dpyinfo->x_highlight_frame
1509 = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1510 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1511 : dpyinfo->x_focus_frame);
1512 if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
1514 fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
1515 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
1519 dpyinfo->x_highlight_frame = 0;
1521 if (dpyinfo->x_highlight_frame &&
1522 dpyinfo->x_highlight_frame != old_highlight)
1526 x_update_cursor (old_highlight, 1);
1527 x_set_frame_alpha (old_highlight);
1529 if (dpyinfo->x_highlight_frame)
1531 x_update_cursor (dpyinfo->x_highlight_frame, 1);
1532 x_set_frame_alpha (dpyinfo->x_highlight_frame);
1539 x_make_frame_visible (struct frame *f)
1540 /* --------------------------------------------------------------------------
1541 External: Show the window (X11 semantics)
1542 -------------------------------------------------------------------------- */
1544 NSTRACE ("x_make_frame_visible");
1545 /* XXX: at some points in past this was not needed, as the only place that
1546 called this (frame.c:Fraise_frame ()) also called raise_lower;
1547 if this ends up the case again, comment this out again. */
1548 if (!FRAME_VISIBLE_P (f))
1550 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1552 SET_FRAME_VISIBLE (f, 1);
1555 /* Making a new frame from a fullscreen frame will make the new frame
1556 fullscreen also. So skip handleFS as this will print an error. */
1557 if ([view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH
1558 && [view isFullscreen])
1561 if (f->want_fullscreen != FULLSCREEN_NONE)
1572 x_make_frame_invisible (struct frame *f)
1573 /* --------------------------------------------------------------------------
1574 External: Hide the window (X11 semantics)
1575 -------------------------------------------------------------------------- */
1578 NSTRACE ("x_make_frame_invisible");
1579 check_window_system (f);
1580 view = FRAME_NS_VIEW (f);
1581 [[view window] orderOut: NSApp];
1582 SET_FRAME_VISIBLE (f, 0);
1583 SET_FRAME_ICONIFIED (f, 0);
1588 x_iconify_frame (struct frame *f)
1589 /* --------------------------------------------------------------------------
1590 External: Iconify window
1591 -------------------------------------------------------------------------- */
1594 struct ns_display_info *dpyinfo;
1596 NSTRACE ("x_iconify_frame");
1597 check_window_system (f);
1598 view = FRAME_NS_VIEW (f);
1599 dpyinfo = FRAME_DISPLAY_INFO (f);
1601 if (dpyinfo->x_highlight_frame == f)
1602 dpyinfo->x_highlight_frame = 0;
1604 if ([[view window] windowNumber] <= 0)
1606 /* the window is still deferred. Make it very small, bring it
1607 on screen and order it out. */
1608 NSRect s = { { 100, 100}, {0, 0} };
1610 t = [[view window] frame];
1611 [[view window] setFrame: s display: NO];
1612 [[view window] orderBack: NSApp];
1613 [[view window] orderOut: NSApp];
1614 [[view window] setFrame: t display: NO];
1617 /* Processing input while Emacs is being minimized can cause a
1618 crash, so block it for the duration. */
1620 [[view window] miniaturize: NSApp];
1624 /* Free X resources of frame F. */
1627 x_free_frame_resources (struct frame *f)
1630 struct ns_display_info *dpyinfo;
1631 Mouse_HLInfo *hlinfo;
1633 NSTRACE ("x_free_frame_resources");
1634 check_window_system (f);
1635 view = FRAME_NS_VIEW (f);
1636 dpyinfo = FRAME_DISPLAY_INFO (f);
1637 hlinfo = MOUSE_HL_INFO (f);
1639 [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1643 free_frame_menubar (f);
1644 free_frame_faces (f);
1646 if (f == dpyinfo->x_focus_frame)
1647 dpyinfo->x_focus_frame = 0;
1648 if (f == dpyinfo->x_highlight_frame)
1649 dpyinfo->x_highlight_frame = 0;
1650 if (f == hlinfo->mouse_face_mouse_frame)
1651 reset_mouse_highlight (hlinfo);
1653 if (f->output_data.ns->miniimage != nil)
1654 [f->output_data.ns->miniimage release];
1656 [[view window] close];
1659 xfree (f->output_data.ns);
1665 x_destroy_window (struct frame *f)
1666 /* --------------------------------------------------------------------------
1667 External: Delete the window
1668 -------------------------------------------------------------------------- */
1670 NSTRACE ("x_destroy_window");
1671 check_window_system (f);
1672 x_free_frame_resources (f);
1678 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1679 /* --------------------------------------------------------------------------
1680 External: Position the window
1681 -------------------------------------------------------------------------- */
1683 NSView *view = FRAME_NS_VIEW (f);
1684 NSArray *screens = [NSScreen screens];
1685 NSScreen *fscreen = [screens objectAtIndex: 0];
1686 NSScreen *screen = [[view window] screen];
1688 NSTRACE ("x_set_offset");
1695 if (view != nil && screen && fscreen)
1697 f->left_pos = f->size_hint_flags & XNegative
1698 ? [screen visibleFrame].size.width + f->left_pos - FRAME_PIXEL_WIDTH (f)
1700 /* We use visibleFrame here to take menu bar into account.
1701 Ideally we should also adjust left/top with visibleFrame.origin. */
1703 f->top_pos = f->size_hint_flags & YNegative
1704 ? ([screen visibleFrame].size.height + f->top_pos
1705 - FRAME_PIXEL_HEIGHT (f) - FRAME_NS_TITLEBAR_HEIGHT (f)
1706 - FRAME_TOOLBAR_HEIGHT (f))
1708 #ifdef NS_IMPL_GNUSTEP
1709 if (f->left_pos < 100)
1710 f->left_pos = 100; /* don't overlap menu */
1712 /* Constrain the setFrameTopLeftPoint so we don't move behind the
1714 NSPoint pt = NSMakePoint (SCREENMAXBOUND (f->left_pos),
1715 SCREENMAXBOUND ([fscreen frame].size.height
1717 NSTRACE_POINT ("setFrameTopLeftPoint", pt);
1718 [[view window] setFrameTopLeftPoint: pt];
1719 f->size_hint_flags &= ~(XNegative|YNegative);
1727 x_set_window_size (struct frame *f,
1728 bool change_gravity,
1732 /* --------------------------------------------------------------------------
1733 Adjust window pixel size based on given character grid size
1734 Impl is a bit more complex than other terms, need to do some
1736 -------------------------------------------------------------------------- */
1738 EmacsView *view = FRAME_NS_VIEW (f);
1739 NSWindow *window = [view window];
1740 NSRect wr = [window frame];
1741 int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1742 int pixelwidth, pixelheight;
1743 int orig_height = wr.size.height;
1745 NSTRACE ("x_set_window_size");
1750 NSTRACE_RECT ("current", wr);
1751 NSTRACE_MSG ("Width:%d Height:%d Pixelwise:%d", width, height, pixelwise);
1752 NSTRACE_MSG ("Font %d x %d", FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f));
1758 pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
1759 pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
1763 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, width);
1764 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, height);
1767 /* If we have a toolbar, take its height into account. */
1768 if (tb && ! [view isFullscreen])
1770 /* NOTE: previously this would generate wrong result if toolbar not
1771 yet displayed and fixing toolbar_height=32 helped, but
1772 now (200903) seems no longer needed */
1773 FRAME_TOOLBAR_HEIGHT (f) =
1774 NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1775 - FRAME_NS_TITLEBAR_HEIGHT (f);
1777 /* Only breaks things here, removed by martin 2015-09-30. */
1778 #ifdef NS_IMPL_GNUSTEP
1779 FRAME_TOOLBAR_HEIGHT (f) -= 3;
1784 FRAME_TOOLBAR_HEIGHT (f) = 0;
1786 wr.size.width = pixelwidth + f->border_width;
1787 wr.size.height = pixelheight;
1788 if (! [view isFullscreen])
1789 wr.size.height += FRAME_NS_TITLEBAR_HEIGHT (f)
1790 + FRAME_TOOLBAR_HEIGHT (f);
1792 /* Do not try to constrain to this screen. We may have multiple
1793 screens, and want Emacs to span those. Constraining to screen
1794 prevents that, and that is not nice to the user. */
1795 if (f->output_data.ns->zooming)
1796 f->output_data.ns->zooming = 0;
1798 wr.origin.y += orig_height - wr.size.height;
1800 frame_size_history_add
1801 (f, Qx_set_window_size_1, width, height,
1802 list5 (Fcons (make_number (pixelwidth), make_number (pixelheight)),
1803 Fcons (make_number (wr.size.width), make_number (wr.size.height)),
1804 make_number (f->border_width),
1805 make_number (FRAME_NS_TITLEBAR_HEIGHT (f)),
1806 make_number (FRAME_TOOLBAR_HEIGHT (f))));
1808 [window setFrame: wr display: YES];
1810 [view updateFrameSize: NO];
1816 ns_fullscreen_hook (struct frame *f)
1818 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1820 NSTRACE ("ns_fullscreen_hook");
1822 if (!FRAME_VISIBLE_P (f))
1825 if (! [view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH)
1827 /* Old style fs don't initiate correctly if created from
1828 init/default-frame alist, so use a timer (not nice...).
1830 [NSTimer scheduledTimerWithTimeInterval: 0.5 target: view
1831 selector: @selector (handleFS)
1832 userInfo: nil repeats: NO];
1841 /* ==========================================================================
1845 ========================================================================== */
1849 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1851 struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1852 if (idx < 1 || idx >= color_table->avail)
1854 return color_table->colors[idx];
1859 ns_index_color (NSColor *color, struct frame *f)
1861 struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1865 if (!color_table->colors)
1867 color_table->size = NS_COLOR_CAPACITY;
1868 color_table->avail = 1; /* skip idx=0 as marker */
1869 color_table->colors = xmalloc (color_table->size * sizeof (NSColor *));
1870 color_table->colors[0] = nil;
1871 color_table->empty_indices = [[NSMutableSet alloc] init];
1874 /* Do we already have this color? */
1875 for (i = 1; i < color_table->avail; i++)
1876 if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1879 if ([color_table->empty_indices count] > 0)
1881 NSNumber *index = [color_table->empty_indices anyObject];
1882 [color_table->empty_indices removeObject: index];
1883 idx = [index unsignedLongValue];
1887 if (color_table->avail == color_table->size)
1888 color_table->colors =
1889 xpalloc (color_table->colors, &color_table->size, 1,
1890 min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1891 idx = color_table->avail++;
1894 color_table->colors[idx] = color;
1896 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1902 ns_get_color (const char *name, NSColor **col)
1903 /* --------------------------------------------------------------------------
1905 -------------------------------------------------------------------------- */
1906 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1907 X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1908 See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1911 static char hex[20];
1913 float r = -1.0, g, b;
1914 NSString *nsname = [NSString stringWithUTF8String: name];
1916 NSTRACE ("ns_get_color(%s, **)", name);
1920 if ([nsname isEqualToString: @"ns_selection_bg_color"])
1922 #ifdef NS_IMPL_COCOA
1923 NSString *defname = [[NSUserDefaults standardUserDefaults]
1924 stringForKey: @"AppleHighlightColor"];
1929 if ((new = [NSColor selectedTextBackgroundColor]) != nil)
1931 *col = [new colorUsingDefaultColorSpace];
1936 nsname = NS_SELECTION_BG_COLOR_DEFAULT;
1938 name = [nsname UTF8String];
1940 else if ([nsname isEqualToString: @"ns_selection_fg_color"])
1942 /* NOTE: macOS applications normally don't set foreground
1943 selection, but text may be unreadable if we don't.
1945 if ((new = [NSColor selectedTextColor]) != nil)
1947 *col = [new colorUsingDefaultColorSpace];
1952 nsname = NS_SELECTION_FG_COLOR_DEFAULT;
1953 name = [nsname UTF8String];
1956 /* First, check for some sort of numeric specification. */
1959 if (name[0] == '0' || name[0] == '1' || name[0] == '.') /* RGB decimal */
1961 NSScanner *scanner = [NSScanner scannerWithString: nsname];
1962 [scanner scanFloat: &r];
1963 [scanner scanFloat: &g];
1964 [scanner scanFloat: &b];
1966 else if (!strncmp(name, "rgb:", 4)) /* A newer X11 format -- rgb:r/g/b */
1967 scaling = (snprintf (hex, sizeof hex, "%s", name + 4) - 2) / 3;
1968 else if (name[0] == '#') /* An old X11 format; convert to newer */
1970 int len = (strlen(name) - 1);
1971 int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1973 scaling = strlen(name+start) / 3;
1974 for (i = 0; i < 3; i++)
1975 sprintf (hex + i * (scaling + 1), "%.*s/", scaling,
1976 name + start + i * scaling);
1977 hex[3 * (scaling + 1) - 1] = '\0';
1982 unsigned int rr, gg, bb;
1983 float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1984 if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1994 *col = [NSColor colorForEmacsRed: r green: g blue: b alpha: 1.0];
1999 /* Otherwise, color is expected to be from a list */
2001 NSEnumerator *lenum, *cenum;
2005 #ifdef NS_IMPL_GNUSTEP
2006 /* XXX: who is wrong, the requestor or the implementation? */
2007 if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
2009 nsname = @"highlightColor";
2012 lenum = [[NSColorList availableColorLists] objectEnumerator];
2013 while ( (clist = [lenum nextObject]) && new == nil)
2015 cenum = [[clist allKeys] objectEnumerator];
2016 while ( (name = [cenum nextObject]) && new == nil )
2018 if ([name compare: nsname
2019 options: NSCaseInsensitiveSearch] == NSOrderedSame )
2020 new = [clist colorWithKey: name];
2026 *col = [new colorUsingDefaultColorSpace];
2033 ns_lisp_to_color (Lisp_Object color, NSColor **col)
2034 /* --------------------------------------------------------------------------
2035 Convert a Lisp string object to a NS color
2036 -------------------------------------------------------------------------- */
2038 NSTRACE ("ns_lisp_to_color");
2039 if (STRINGP (color))
2040 return ns_get_color (SSDATA (color), col);
2041 else if (SYMBOLP (color))
2042 return ns_get_color (SSDATA (SYMBOL_NAME (color)), col);
2048 ns_query_color(void *col, XColor *color_def, int setPixel)
2049 /* --------------------------------------------------------------------------
2050 Get ARGB values out of NSColor col and put them into color_def.
2051 If setPixel, set the pixel to a concatenated version.
2052 and set color_def pixel to the resulting index.
2053 -------------------------------------------------------------------------- */
2055 EmacsCGFloat r, g, b, a;
2057 [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
2058 color_def->red = r * 65535;
2059 color_def->green = g * 65535;
2060 color_def->blue = b * 65535;
2062 if (setPixel == YES)
2064 = ARGB_TO_ULONG((int)(a*255),
2065 (int)(r*255), (int)(g*255), (int)(b*255));
2070 ns_defined_color (struct frame *f,
2075 /* --------------------------------------------------------------------------
2076 Return true if named color found, and set color_def rgb accordingly.
2077 If makeIndex and alloc are nonzero put the color in the color_table,
2078 and set color_def pixel to the resulting index.
2079 If makeIndex is zero, set color_def pixel to ARGB.
2080 Return false if not found
2081 -------------------------------------------------------------------------- */
2084 NSTRACE_WHEN (NSTRACE_GROUP_COLOR, "ns_defined_color");
2087 if (ns_get_color (name, &col) != 0) /* Color not found */
2092 if (makeIndex && alloc)
2093 color_def->pixel = ns_index_color (col, f);
2094 ns_query_color (col, color_def, !makeIndex);
2101 x_set_frame_alpha (struct frame *f)
2102 /* --------------------------------------------------------------------------
2103 change the entire-frame transparency
2104 -------------------------------------------------------------------------- */
2106 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2108 double alpha_min = 1.0;
2110 NSTRACE ("x_set_frame_alpha");
2112 if (dpyinfo->x_highlight_frame == f)
2113 alpha = f->alpha[0];
2115 alpha = f->alpha[1];
2117 if (FLOATP (Vframe_alpha_lower_limit))
2118 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
2119 else if (INTEGERP (Vframe_alpha_lower_limit))
2120 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
2124 else if (1.0 < alpha)
2126 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
2129 #ifdef NS_IMPL_COCOA
2131 EmacsView *view = FRAME_NS_VIEW (f);
2132 [[view window] setAlphaValue: alpha];
2138 /* ==========================================================================
2142 ========================================================================== */
2146 frame_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
2147 /* --------------------------------------------------------------------------
2148 Programmatically reposition mouse pointer in pixel coordinates
2149 -------------------------------------------------------------------------- */
2151 NSTRACE ("frame_set_mouse_pixel_position");
2154 /* FIXME: this does not work, and what about GNUstep? */
2155 #ifdef NS_IMPL_COCOA
2156 [FRAME_NS_VIEW (f) lockFocus];
2157 PSsetmouse ((float)pix_x, (float)pix_y);
2158 [FRAME_NS_VIEW (f) unlockFocus];
2164 note_mouse_movement (struct frame *frame, CGFloat x, CGFloat y)
2165 /* ------------------------------------------------------------------------
2166 Called by EmacsView on mouseMovement events. Passes on
2167 to emacs mainstream code if we moved off of a rect of interest
2168 known as last_mouse_glyph.
2169 ------------------------------------------------------------------------ */
2171 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
2174 // NSTRACE ("note_mouse_movement");
2176 dpyinfo->last_mouse_motion_frame = frame;
2177 r = &dpyinfo->last_mouse_glyph;
2179 /* Note, this doesn't get called for enter/leave, since we don't have a
2180 position. Those are taken care of in the corresponding NSView methods. */
2182 /* has movement gone beyond last rect we were tracking? */
2183 if (x < r->origin.x || x >= r->origin.x + r->size.width
2184 || y < r->origin.y || y >= r->origin.y + r->size.height)
2186 ns_update_begin (frame);
2187 frame->mouse_moved = 1;
2188 note_mouse_highlight (frame, x, y);
2189 remember_mouse_glyph (frame, x, y, r);
2190 ns_update_end (frame);
2199 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
2200 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
2202 /* --------------------------------------------------------------------------
2203 External (hook): inform emacs about mouse position and hit parts.
2204 If a scrollbar is being dragged, set bar_window, part, x, y, time.
2205 x & y should be position in the scrollbar (the whole bar, not the handle)
2206 and length of scrollbar respectively
2207 -------------------------------------------------------------------------- */
2211 Lisp_Object frame, tail;
2213 struct ns_display_info *dpyinfo;
2215 NSTRACE ("ns_mouse_position");
2219 fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
2223 dpyinfo = FRAME_DISPLAY_INFO (*fp);
2227 /* Clear the mouse-moved flag for every frame on this display. */
2228 FOR_EACH_FRAME (tail, frame)
2229 if (FRAME_NS_P (XFRAME (frame))
2230 && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
2231 XFRAME (frame)->mouse_moved = 0;
2233 dpyinfo->last_mouse_scroll_bar = nil;
2234 if (dpyinfo->last_mouse_frame
2235 && FRAME_LIVE_P (dpyinfo->last_mouse_frame))
2236 f = dpyinfo->last_mouse_frame;
2238 f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame : SELECTED_FRAME ();
2240 if (f && FRAME_NS_P (f))
2242 view = FRAME_NS_VIEW (*fp);
2244 position = [[view window] mouseLocationOutsideOfEventStream];
2245 position = [view convertPoint: position fromView: nil];
2246 remember_mouse_glyph (f, position.x, position.y,
2247 &dpyinfo->last_mouse_glyph);
2248 NSTRACE_POINT ("position", position);
2250 if (bar_window) *bar_window = Qnil;
2251 if (part) *part = scroll_bar_above_handle;
2253 if (x) XSETINT (*x, lrint (position.x));
2254 if (y) XSETINT (*y, lrint (position.y));
2256 *time = dpyinfo->last_mouse_movement_time;
2265 ns_frame_up_to_date (struct frame *f)
2266 /* --------------------------------------------------------------------------
2267 External (hook): Fix up mouse highlighting right after a full update.
2268 Can't use FRAME_MOUSE_UPDATE due to ns_frame_begin and ns_frame_end calls.
2269 -------------------------------------------------------------------------- */
2271 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_frame_up_to_date");
2275 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
2276 if (f == hlinfo->mouse_face_mouse_frame)
2280 note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
2281 hlinfo->mouse_face_mouse_x,
2282 hlinfo->mouse_face_mouse_y);
2291 ns_define_frame_cursor (struct frame *f, Cursor cursor)
2292 /* --------------------------------------------------------------------------
2293 External (RIF): set frame mouse pointer type.
2294 -------------------------------------------------------------------------- */
2296 NSTRACE ("ns_define_frame_cursor");
2297 if (FRAME_POINTER_TYPE (f) != cursor)
2299 EmacsView *view = FRAME_NS_VIEW (f);
2300 FRAME_POINTER_TYPE (f) = cursor;
2301 [[view window] invalidateCursorRectsForView: view];
2302 /* Redisplay assumes this function also draws the changed frame
2303 cursor, but this function doesn't, so do it explicitly. */
2304 x_update_cursor (f, 1);
2310 /* ==========================================================================
2314 ========================================================================== */
2318 ns_convert_key (unsigned code)
2319 /* --------------------------------------------------------------------------
2320 Internal call used by NSView-keyDown.
2321 -------------------------------------------------------------------------- */
2323 const unsigned last_keysym = ARRAYELTS (convert_ns_to_X_keysym);
2325 /* An array would be faster, but less easy to read. */
2326 for (keysym = 0; keysym < last_keysym; keysym += 2)
2327 if (code == convert_ns_to_X_keysym[keysym])
2328 return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
2330 /* if decide to use keyCode and Carbon table, use this line:
2331 return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
2336 x_get_keysym_name (int keysym)
2337 /* --------------------------------------------------------------------------
2338 Called by keyboard.c. Not sure if the return val is important, except
2340 -------------------------------------------------------------------------- */
2342 static char value[16];
2343 NSTRACE ("x_get_keysym_name");
2344 sprintf (value, "%d", keysym);
2350 /* ==========================================================================
2352 Block drawing operations
2354 ========================================================================== */
2358 ns_redraw_scroll_bars (struct frame *f)
2362 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
2363 NSTRACE ("ns_redraw_scroll_bars");
2364 for (i =[subviews count]-1; i >= 0; i--)
2366 view = [subviews objectAtIndex: i];
2367 if (![view isKindOfClass: [EmacsScroller class]]) continue;
2374 ns_clear_frame (struct frame *f)
2375 /* --------------------------------------------------------------------------
2376 External (hook): Erase the entire frame
2377 -------------------------------------------------------------------------- */
2379 NSView *view = FRAME_NS_VIEW (f);
2382 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_clear_frame");
2384 /* comes on initial frame because we have
2385 after-make-frame-functions = select-frame */
2386 if (!FRAME_DEFAULT_FACE (f))
2389 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2394 ns_focus (f, &r, 1);
2395 [ns_lookup_indexed_color (NS_FACE_BACKGROUND
2396 (FACE_FROM_ID (f, DEFAULT_FACE_ID)), f) set];
2400 /* as of 2006/11 or so this is now needed */
2401 ns_redraw_scroll_bars (f);
2407 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2408 /* --------------------------------------------------------------------------
2409 External (RIF): Clear section of frame
2410 -------------------------------------------------------------------------- */
2412 NSRect r = NSMakeRect (x, y, width, height);
2413 NSView *view = FRAME_NS_VIEW (f);
2414 struct face *face = FRAME_DEFAULT_FACE (f);
2419 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_clear_frame_area");
2421 r = NSIntersectionRect (r, [view frame]);
2422 ns_focus (f, &r, 1);
2423 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2432 ns_copy_bits (struct frame *f, NSRect src, NSRect dest)
2434 NSTRACE ("ns_copy_bits");
2436 if (FRAME_NS_VIEW (f))
2438 hide_bell(); // Ensure the bell image isn't scrolled.
2440 ns_focus (f, &dest, 1);
2441 [FRAME_NS_VIEW (f) scrollRect: src
2442 by: NSMakeSize (dest.origin.x - src.origin.x,
2443 dest.origin.y - src.origin.y)];
2449 ns_scroll_run (struct window *w, struct run *run)
2450 /* --------------------------------------------------------------------------
2451 External (RIF): Insert or delete n lines at line vpos
2452 -------------------------------------------------------------------------- */
2454 struct frame *f = XFRAME (w->frame);
2455 int x, y, width, height, from_y, to_y, bottom_y;
2457 NSTRACE ("ns_scroll_run");
2459 /* begin copy from other terms */
2460 /* Get frame-relative bounding box of the text display area of W,
2461 without mode lines. Include in this box the left and right
2463 window_box (w, ANY_AREA, &x, &y, &width, &height);
2465 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2466 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2467 bottom_y = y + height;
2471 /* Scrolling up. Make sure we don't copy part of the mode
2472 line at the bottom. */
2473 if (from_y + run->height > bottom_y)
2474 height = bottom_y - from_y;
2476 height = run->height;
2480 /* Scrolling down. Make sure we don't copy over the mode line.
2482 if (to_y + run->height > bottom_y)
2483 height = bottom_y - to_y;
2485 height = run->height;
2487 /* end copy from other terms */
2497 NSRect srcRect = NSMakeRect (x, from_y, width, height);
2498 NSRect dstRect = NSMakeRect (x, to_y, width, height);
2500 ns_copy_bits (f, srcRect , dstRect);
2508 ns_after_update_window_line (struct window *w, struct glyph_row *desired_row)
2509 /* --------------------------------------------------------------------------
2510 External (RIF): preparatory to fringe update after text was updated
2511 -------------------------------------------------------------------------- */
2516 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_after_update_window_line");
2518 /* begin copy from other terms */
2521 if (!desired_row->mode_line_p && !w->pseudo_window_p)
2522 desired_row->redraw_fringe_bitmaps_p = 1;
2524 /* When a window has disappeared, make sure that no rest of
2525 full-width rows stays visible in the internal border. */
2526 if (windows_or_buffers_changed
2527 && desired_row->full_width_p
2528 && (f = XFRAME (w->frame),
2529 width = FRAME_INTERNAL_BORDER_WIDTH (f),
2531 && (height = desired_row->visible_height,
2534 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2537 ns_clear_frame_area (f, 0, y, width, height);
2538 ns_clear_frame_area (f,
2539 FRAME_PIXEL_WIDTH (f) - width,
2547 ns_shift_glyphs_for_insert (struct frame *f,
2548 int x, int y, int width, int height,
2550 /* --------------------------------------------------------------------------
2551 External (RIF): copy an area horizontally, don't worry about clearing src
2552 -------------------------------------------------------------------------- */
2554 NSRect srcRect = NSMakeRect (x, y, width, height);
2555 NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2557 NSTRACE ("ns_shift_glyphs_for_insert");
2559 ns_copy_bits (f, srcRect, dstRect);
2564 /* ==========================================================================
2566 Character encoding and metrics
2568 ========================================================================== */
2572 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2573 /* --------------------------------------------------------------------------
2574 External (RIF); compute left/right overhang of whole string and set in s
2575 -------------------------------------------------------------------------- */
2577 struct font *font = s->font;
2581 struct font_metrics metrics;
2582 unsigned int codes[2];
2583 codes[0] = *(s->char2b);
2584 codes[1] = *(s->char2b + s->nchars - 1);
2586 font->driver->text_extents (font, codes, 2, &metrics);
2587 s->left_overhang = -metrics.lbearing;
2589 = metrics.rbearing > metrics.width
2590 ? metrics.rbearing - metrics.width : 0;
2594 s->left_overhang = 0;
2595 if (EQ (font->driver->type, Qns))
2596 s->right_overhang = ((struct nsfont_info *)font)->ital ?
2597 FONT_HEIGHT (font) * 0.2 : 0;
2599 s->right_overhang = 0;
2605 /* ==========================================================================
2607 Fringe and cursor drawing
2609 ========================================================================== */
2612 extern int max_used_fringe_bitmap;
2614 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2615 struct draw_fringe_bitmap_params *p)
2616 /* --------------------------------------------------------------------------
2617 External (RIF); fringe-related
2618 -------------------------------------------------------------------------- */
2620 /* Fringe bitmaps comes in two variants, normal and periodic. A
2621 periodic bitmap is used to create a continuous pattern. Since a
2622 bitmap is rendered one text line at a time, the start offset (dh)
2623 of the bitmap varies. Concretely, this is used for the empty
2626 For a bitmap, "h + dh" is the full height and is always
2627 invariant. For a normal bitmap "dh" is zero.
2629 For example, when the period is three and the full height is 72
2630 the following combinations exists:
2636 struct frame *f = XFRAME (WINDOW_FRAME (w));
2637 struct face *face = p->face;
2638 static EmacsImage **bimgs = NULL;
2639 static int nBimgs = 0;
2641 NSTRACE_WHEN (NSTRACE_GROUP_FRINGE, "ns_draw_fringe_bitmap");
2642 NSTRACE_MSG ("which:%d cursor:%d overlay:%d width:%d height:%d period:%d",
2643 p->which, p->cursor_p, p->overlay_p, p->wd, p->h, p->dh);
2645 /* grow bimgs if needed */
2646 if (nBimgs < max_used_fringe_bitmap)
2648 bimgs = xrealloc (bimgs, max_used_fringe_bitmap * sizeof *bimgs);
2649 memset (bimgs + nBimgs, 0,
2650 (max_used_fringe_bitmap - nBimgs) * sizeof *bimgs);
2651 nBimgs = max_used_fringe_bitmap;
2654 /* Must clip because of partially visible lines. */
2655 ns_clip_to_row (w, row, ANY_AREA, YES);
2659 int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
2661 if (bx >= 0 && nx > 0)
2663 NSRect r = NSMakeRect (bx, by, nx, ny);
2665 [ns_lookup_indexed_color (face->background, f) set];
2672 NSRect r = NSMakeRect (p->x, p->y, p->wd, p->h);
2673 EmacsImage *img = bimgs[p->which - 1];
2677 // Note: For "periodic" images, allocate one EmacsImage for
2678 // the base image, and use it for all dh:s.
2679 unsigned short *bits = p->bits;
2680 int full_height = p->h + p->dh;
2682 unsigned char *cbits = xmalloc (full_height);
2684 for (i = 0; i < full_height; i++)
2686 img = [[EmacsImage alloc] initFromXBM: cbits width: 8
2689 bimgs[p->which - 1] = img;
2693 NSTRACE_RECT ("r", r);
2696 /* Since we composite the bitmap instead of just blitting it, we need
2697 to erase the whole background. */
2698 [ns_lookup_indexed_color(face->background, f) set];
2704 bm_color = ns_lookup_indexed_color(face->foreground, f);
2705 else if (p->overlay_p)
2706 bm_color = ns_lookup_indexed_color(face->background, f);
2708 bm_color = f->output_data.ns->cursor_color;
2709 [img setXBMColor: bm_color];
2712 #ifdef NS_IMPL_COCOA
2713 // Note: For periodic images, the full image height is "h + hd".
2714 // By using the height h, a suitable part of the image is used.
2715 NSRect fromRect = NSMakeRect(0, 0, p->wd, p->h);
2717 NSTRACE_RECT ("fromRect", fromRect);
2721 operation: NSCompositingOperationSourceOver
2727 NSPoint pt = r.origin;
2729 [img compositeToPoint: pt operation: NSCompositingOperationSourceOver];
2738 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2739 int x, int y, enum text_cursor_kinds cursor_type,
2740 int cursor_width, bool on_p, bool active_p)
2741 /* --------------------------------------------------------------------------
2742 External call (RIF): draw cursor.
2743 Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2744 -------------------------------------------------------------------------- */
2747 int fx, fy, h, cursor_height;
2748 struct frame *f = WINDOW_XFRAME (w);
2749 struct glyph *phys_cursor_glyph;
2750 struct glyph *cursor_glyph;
2752 NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2754 /* If cursor is out of bounds, don't draw garbage. This can happen
2755 in mini-buffer windows when switching between echo area glyphs
2758 NSTRACE ("ns_draw_window_cursor");
2763 w->phys_cursor_type = cursor_type;
2764 w->phys_cursor_on_p = on_p;
2766 if (cursor_type == NO_CURSOR)
2768 w->phys_cursor_width = 0;
2772 if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2774 if (glyph_row->exact_window_width_line_p
2775 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2777 glyph_row->cursor_in_fringe_p = 1;
2778 draw_fringe_bitmap (w, glyph_row, 0);
2783 /* We draw the cursor (with NSRectFill), then draw the glyph on top
2784 (other terminals do it the other way round). We must set
2785 w->phys_cursor_width to the cursor width. For bar cursors, that
2786 is CURSOR_WIDTH; for box cursors, it is the glyph width. */
2787 get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2789 /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2790 to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2791 if (cursor_type == BAR_CURSOR)
2793 if (cursor_width < 1)
2794 cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2796 /* The bar cursor should never be wider than the glyph. */
2797 if (cursor_width < w->phys_cursor_width)
2798 w->phys_cursor_width = cursor_width;
2800 /* If we have an HBAR, "cursor_width" MAY specify height. */
2801 else if (cursor_type == HBAR_CURSOR)
2803 cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2804 if (cursor_height > glyph_row->height)
2805 cursor_height = glyph_row->height;
2806 if (h > cursor_height) // Cursor smaller than line height, move down
2807 fy += h - cursor_height;
2811 r.origin.x = fx, r.origin.y = fy;
2813 r.size.width = w->phys_cursor_width;
2815 /* Prevent the cursor from being drawn outside the text area. */
2816 ns_clip_to_row (w, glyph_row, TEXT_AREA, NO); /* do ns_focus(f, &r, 1); if remove */
2819 face = FACE_FROM_ID_OR_NULL (f, phys_cursor_glyph->face_id);
2820 if (face && NS_FACE_BACKGROUND (face)
2821 == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2823 [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2824 hollow_color = FRAME_CURSOR_COLOR (f);
2827 [FRAME_CURSOR_COLOR (f) set];
2829 #ifdef NS_IMPL_COCOA
2830 /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2831 atomic. Cleaner ways of doing this should be investigated.
2832 One way would be to set a global variable DRAWING_CURSOR
2833 when making the call to draw_phys..(), don't focus in that
2834 case, then move the ns_unfocus() here after that call. */
2835 NSDisableScreenUpdates ();
2838 switch (cursor_type)
2840 case DEFAULT_CURSOR:
2843 case FILLED_BOX_CURSOR:
2846 case HOLLOW_BOX_CURSOR:
2849 NSRectFill (NSInsetRect (r, 1, 1));
2850 [FRAME_CURSOR_COLOR (f) set];
2857 /* If the character under cursor is R2L, draw the bar cursor
2858 on the right of its glyph, rather than on the left. */
2859 cursor_glyph = get_phys_cursor_glyph (w);
2860 if ((cursor_glyph->resolved_level & 1) != 0)
2861 s.origin.x += cursor_glyph->pixel_width - s.size.width;
2868 /* draw the character under the cursor */
2869 if (cursor_type != NO_CURSOR)
2870 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2872 #ifdef NS_IMPL_COCOA
2873 NSEnableScreenUpdates ();
2880 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2881 /* --------------------------------------------------------------------------
2882 External (RIF): Draw a vertical line.
2883 -------------------------------------------------------------------------- */
2885 struct frame *f = XFRAME (WINDOW_FRAME (w));
2887 NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2889 NSTRACE ("ns_draw_vertical_window_border");
2891 face = FACE_FROM_ID_OR_NULL (f, VERTICAL_BORDER_FACE_ID);
2893 ns_focus (f, &r, 1);
2895 [ns_lookup_indexed_color(face->foreground, f) set];
2903 ns_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
2904 /* --------------------------------------------------------------------------
2905 External (RIF): Draw a window divider.
2906 -------------------------------------------------------------------------- */
2908 struct frame *f = XFRAME (WINDOW_FRAME (w));
2910 NSRect r = NSMakeRect (x0, y0, x1-x0, y1-y0);
2912 NSTRACE ("ns_draw_window_divider");
2914 face = FACE_FROM_ID_OR_NULL (f, WINDOW_DIVIDER_FACE_ID);
2916 ns_focus (f, &r, 1);
2918 [ns_lookup_indexed_color(face->foreground, f) set];
2925 ns_show_hourglass (struct frame *f)
2927 /* TODO: add NSProgressIndicator to all frames. */
2931 ns_hide_hourglass (struct frame *f)
2933 /* TODO: remove NSProgressIndicator from all frames. */
2936 /* ==========================================================================
2938 Glyph drawing operations
2940 ========================================================================== */
2943 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2944 /* --------------------------------------------------------------------------
2945 Wrapper utility to account for internal border width on full-width lines,
2946 and allow top full-width rows to hit the frame top. nr should be pointer
2947 to two successive NSRects. Number of rects actually used is returned.
2948 -------------------------------------------------------------------------- */
2950 int n = get_glyph_string_clip_rects (s, nr, 2);
2954 /* --------------------------------------------------------------------
2955 Draw a wavy line under glyph string s. The wave fills wave_height
2962 wave_height = 3 | * * * *
2963 --------------------------------------------------------------------- */
2966 ns_draw_underwave (struct glyph_string *s, EmacsCGFloat width, EmacsCGFloat x)
2968 int wave_height = 3, wave_length = 2;
2969 int y, dx, dy, odd, xmax;
2974 dy = wave_height - 1;
2975 y = s->ybase - wave_height + 3;
2978 /* Find and set clipping rectangle */
2979 waveClip = NSMakeRect (x, y, width, wave_height);
2980 [[NSGraphicsContext currentContext] saveGraphicsState];
2981 NSRectClip (waveClip);
2983 /* Draw the waves */
2984 a.x = x - ((int)(x) % dx) + (EmacsCGFloat) 0.5;
2986 odd = (int)(a.x/dx) % 2;
2987 a.y = b.y = y + 0.5;
2996 [NSBezierPath strokeLineFromPoint:a toPoint:b];
2997 a.x = b.x, a.y = b.y;
2998 b.x += dx, b.y = y + 0.5 + odd*dy;
3002 /* Restore previous clipping rectangle(s) */
3003 [[NSGraphicsContext currentContext] restoreGraphicsState];
3009 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
3010 NSColor *defaultCol, CGFloat width, CGFloat x)
3011 /* --------------------------------------------------------------------------
3012 Draw underline, overline, and strike-through on glyph string s.
3013 -------------------------------------------------------------------------- */
3015 if (s->for_overlaps)
3019 if (face->underline_p)
3021 if (s->face->underline_type == FACE_UNDER_WAVE)
3023 if (face->underline_defaulted_p)
3026 [ns_lookup_indexed_color (face->underline_color, s->f) set];
3028 ns_draw_underwave (s, width, x);
3030 else if (s->face->underline_type == FACE_UNDER_LINE)
3034 unsigned long thickness, position;
3036 /* If the prev was underlined, match its appearance. */
3037 if (s->prev && s->prev->face->underline_p
3038 && s->prev->face->underline_type == FACE_UNDER_LINE
3039 && s->prev->underline_thickness > 0)
3041 thickness = s->prev->underline_thickness;
3042 position = s->prev->underline_position;
3047 unsigned long descent;
3050 descent = s->y + s->height - s->ybase;
3052 /* Use underline thickness of font, defaulting to 1. */
3053 thickness = (font && font->underline_thickness > 0)
3054 ? font->underline_thickness : 1;
3056 /* Determine the offset of underlining from the baseline. */
3057 if (x_underline_at_descent_line)
3058 position = descent - thickness;
3059 else if (x_use_underline_position_properties
3060 && font && font->underline_position >= 0)
3061 position = font->underline_position;
3063 position = lround (font->descent / 2);
3065 position = underline_minimum_offset;
3067 position = max (position, underline_minimum_offset);
3069 /* Ensure underlining is not cropped. */
3070 if (descent <= position)
3072 position = descent - 1;
3075 else if (descent < position + thickness)
3079 s->underline_thickness = thickness;
3080 s->underline_position = position;
3082 r = NSMakeRect (x, s->ybase + position, width, thickness);
3084 if (face->underline_defaulted_p)
3087 [ns_lookup_indexed_color (face->underline_color, s->f) set];
3091 /* Do overline. We follow other terms in using a thickness of 1
3092 and ignoring overline_margin. */
3093 if (face->overline_p)
3096 r = NSMakeRect (x, s->y, width, 1);
3098 if (face->overline_color_defaulted_p)
3101 [ns_lookup_indexed_color (face->overline_color, s->f) set];
3105 /* Do strike-through. We follow other terms for thickness and
3106 vertical position.*/
3107 if (face->strike_through_p)
3110 /* Y-coordinate and height of the glyph string's first glyph.
3111 We cannot use s->y and s->height because those could be
3112 larger if there are taller display elements (e.g., characters
3113 displayed with a larger font) in the same glyph row. */
3114 int glyph_y = s->ybase - s->first_glyph->ascent;
3115 int glyph_height = s->first_glyph->ascent + s->first_glyph->descent;
3116 /* Strike-through width and offset from the glyph string's
3118 unsigned long h = 1;
3121 dy = lrint ((glyph_height - h) / 2);
3122 r = NSMakeRect (x, glyph_y + dy, width, 1);
3124 if (face->strike_through_color_defaulted_p)
3127 [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
3133 ns_draw_box (NSRect r, CGFloat thickness, NSColor *col,
3134 char left_p, char right_p)
3135 /* --------------------------------------------------------------------------
3136 Draw an unfilled rect inside r, optionally leaving left and/or right open.
3137 Note we can't just use an NSDrawRect command, because of the possibility
3138 of some sides not being drawn, and because the rect will be filled.
3139 -------------------------------------------------------------------------- */
3145 s.size.height = thickness;
3147 s.origin.y += r.size.height - thickness;
3150 s.size.height = r.size.height;
3151 s.origin.y = r.origin.y;
3153 /* left, right (optional) */
3154 s.size.width = thickness;
3159 s.origin.x += r.size.width - thickness;
3166 ns_draw_relief (NSRect r, int thickness, char raised_p,
3167 char top_p, char bottom_p, char left_p, char right_p,
3168 struct glyph_string *s)
3169 /* --------------------------------------------------------------------------
3170 Draw a relief rect inside r, optionally leaving some sides open.
3171 Note we can't just use an NSDrawBezel command, because of the possibility
3172 of some sides not being drawn, and because the rect will be filled.
3173 -------------------------------------------------------------------------- */
3175 static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
3176 NSColor *newBaseCol = nil;
3179 NSTRACE ("ns_draw_relief");
3183 if (s->face->use_box_color_for_shadows_p)
3185 newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
3187 /* else if (s->first_glyph->type == IMAGE_GLYPH
3189 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
3191 newBaseCol = IMAGE_BACKGROUND (s->img, s->f, 0);
3195 newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
3198 if (newBaseCol == nil)
3199 newBaseCol = [NSColor grayColor];
3201 if (newBaseCol != baseCol) /* TODO: better check */
3204 baseCol = [newBaseCol retain];
3206 lightCol = [[baseCol highlightWithLevel: 0.2] retain];
3208 darkCol = [[baseCol shadowWithLevel: 0.3] retain];
3211 [(raised_p ? lightCol : darkCol) set];
3213 /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
3216 sr.size.height = thickness;
3217 if (top_p) NSRectFill (sr);
3220 sr.size.height = r.size.height;
3221 sr.size.width = thickness;
3222 if (left_p) NSRectFill (sr);
3224 [(raised_p ? darkCol : lightCol) set];
3227 sr.size.width = r.size.width;
3228 sr.size.height = thickness;
3229 sr.origin.y += r.size.height - thickness;
3230 if (bottom_p) NSRectFill (sr);
3233 sr.size.height = r.size.height;
3234 sr.origin.y = r.origin.y;
3235 sr.size.width = thickness;
3236 sr.origin.x += r.size.width - thickness;
3237 if (right_p) NSRectFill (sr);
3242 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
3243 /* --------------------------------------------------------------------------
3244 Function modeled after x_draw_glyph_string_box ().
3245 Sets up parameters for drawing.
3246 -------------------------------------------------------------------------- */
3248 int right_x, last_x;
3249 char left_p, right_p;
3250 struct glyph *last_glyph;
3255 if (s->hl == DRAW_MOUSE_FACE)
3257 face = FACE_FROM_ID_OR_NULL (s->f,
3258 MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3260 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3265 thickness = face->box_line_width;
3267 NSTRACE ("ns_dumpglyphs_box_or_relief");
3269 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
3270 ? WINDOW_RIGHT_EDGE_X (s->w)
3271 : window_box_right (s->w, s->area));
3272 last_glyph = (s->cmp || s->img
3273 ? s->first_glyph : s->first_glyph + s->nchars-1);
3275 right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
3276 ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
3278 left_p = (s->first_glyph->left_box_line_p
3279 || (s->hl == DRAW_MOUSE_FACE
3280 && (s->prev == NULL || s->prev->hl != s->hl)));
3281 right_p = (last_glyph->right_box_line_p
3282 || (s->hl == DRAW_MOUSE_FACE
3283 && (s->next == NULL || s->next->hl != s->hl)));
3285 r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
3287 /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
3288 if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
3290 ns_draw_box (r, abs (thickness),
3291 ns_lookup_indexed_color (face->box_color, s->f),
3296 ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
3297 1, 1, left_p, right_p, s);
3303 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
3304 /* --------------------------------------------------------------------------
3305 Modeled after x_draw_glyph_string_background, which draws BG in
3306 certain cases. Others are left to the text rendering routine.
3307 -------------------------------------------------------------------------- */
3309 NSTRACE ("ns_maybe_dumpglyphs_background");
3311 if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
3313 int box_line_width = max (s->face->box_line_width, 0);
3314 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
3315 /* When xdisp.c ignores FONT_HEIGHT, we cannot trust font
3316 dimensions, since the actual glyphs might be much
3317 smaller. So in that case we always clear the rectangle
3318 with background color. */
3319 || FONT_TOO_HIGH (s->font)
3320 || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
3323 if (s->hl == DRAW_MOUSE_FACE)
3326 = FACE_FROM_ID_OR_NULL (s->f,
3327 MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3329 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3332 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3334 [(NS_FACE_BACKGROUND (face) != 0
3335 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
3336 : FRAME_BACKGROUND_COLOR (s->f)) set];
3339 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (s->f);
3340 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
3343 if (s->hl != DRAW_CURSOR)
3345 NSRect r = NSMakeRect (s->x, s->y + box_line_width,
3346 s->background_width,
3347 s->height-2*box_line_width);
3351 s->background_filled_p = 1;
3358 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
3359 /* --------------------------------------------------------------------------
3360 Renders an image and associated borders.
3361 -------------------------------------------------------------------------- */
3363 EmacsImage *img = s->img->pixmap;
3364 int box_line_vwidth = max (s->face->box_line_width, 0);
3365 int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3366 int bg_x, bg_y, bg_height;
3373 NSTRACE ("ns_dumpglyphs_image");
3375 if (s->face->box != FACE_NO_BOX
3376 && s->first_glyph->left_box_line_p && s->slice.x == 0)
3377 x += abs (s->face->box_line_width);
3380 bg_y = s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
3381 bg_height = s->height;
3382 /* other terms have this, but was causing problems w/tabbar mode */
3383 /* - 2 * box_line_vwidth; */
3385 if (s->slice.x == 0) x += s->img->hmargin;
3386 if (s->slice.y == 0) y += s->img->vmargin;
3388 /* Draw BG: if we need larger area than image itself cleared, do that,
3389 otherwise, since we composite the image under NS (instead of mucking
3390 with its background color), we must clear just the image area. */
3391 if (s->hl == DRAW_MOUSE_FACE)
3393 face = FACE_FROM_ID_OR_NULL (s->f,
3394 MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3396 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3399 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3401 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
3403 if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
3404 || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
3406 br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
3407 s->background_filled_p = 1;
3411 br = NSMakeRect (x, y, s->slice.width, s->slice.height);
3416 /* Draw the image.. do we need to draw placeholder if img ==nil? */
3419 #ifdef NS_IMPL_COCOA
3420 NSRect dr = NSMakeRect (x, y, s->slice.width, s->slice.height);
3421 NSRect ir = NSMakeRect (s->slice.x,
3422 s->img->height - s->slice.y - s->slice.height,
3423 s->slice.width, s->slice.height);
3426 operation: NSCompositingOperationSourceOver
3431 [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3432 operation: NSCompositingOperationSourceOver];
3436 if (s->hl == DRAW_CURSOR)
3438 [FRAME_CURSOR_COLOR (s->f) set];
3439 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3440 tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3442 /* Currently on NS img->mask is always 0. Since
3443 get_window_cursor_type specifies a hollow box cursor when on
3444 a non-masked image we never reach this clause. But we put it
3445 in in anticipation of better support for image masks on
3447 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3451 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3454 /* Draw underline, overline, strike-through. */
3455 ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3457 /* Draw relief, if requested */
3458 if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3460 if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3462 th = tool_bar_button_relief >= 0 ?
3463 tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3464 raised_p = (s->hl == DRAW_IMAGE_RAISED);
3468 th = abs (s->img->relief);
3469 raised_p = (s->img->relief > 0);
3472 r.origin.x = x - th;
3473 r.origin.y = y - th;
3474 r.size.width = s->slice.width + 2*th-1;
3475 r.size.height = s->slice.height + 2*th-1;
3476 ns_draw_relief (r, th, raised_p,
3478 s->slice.y + s->slice.height == s->img->height,
3480 s->slice.x + s->slice.width == s->img->width, s);
3483 /* If there is no mask, the background won't be seen,
3484 so draw a rectangle on the image for the cursor.
3485 Do this for all images, getting transparency right is not reliable. */
3486 if (s->hl == DRAW_CURSOR)
3488 int thickness = abs (s->img->relief);
3489 if (thickness == 0) thickness = 1;
3490 ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3496 ns_dumpglyphs_stretch (struct glyph_string *s)
3501 NSColor *fgCol, *bgCol;
3503 if (!s->background_filled_p)
3505 n = ns_get_glyph_string_clip_rect (s, r);
3506 *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3508 ns_focus (s->f, r, n);
3510 if (s->hl == DRAW_MOUSE_FACE)
3512 face = FACE_FROM_ID_OR_NULL (s->f,
3513 MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3515 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3518 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3520 bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3521 fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3523 for (i = 0; i < n; ++i)
3525 if (!s->row->full_width_p)
3527 int overrun, leftoverrun;
3529 /* truncate to avoid overwriting fringe and/or scrollbar */
3530 overrun = max (0, (s->x + s->background_width)
3531 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3532 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3533 r[i].size.width -= overrun;
3535 /* truncate to avoid overwriting to left of the window box */
3536 leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3537 + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3539 if (leftoverrun > 0)
3541 r[i].origin.x += leftoverrun;
3542 r[i].size.width -= leftoverrun;
3545 /* XXX: Try to work between problem where a stretch glyph on
3546 a partially-visible bottom row will clear part of the
3547 modeline, and another where list-buffers headers and similar
3548 rows erroneously have visible_height set to 0. Not sure
3549 where this is coming from as other terms seem not to show. */
3550 r[i].size.height = min (s->height, s->row->visible_height);
3555 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3556 overwriting cursor (usually when cursor on a tab) */
3557 if (s->hl == DRAW_CURSOR)
3562 width = s->w->phys_cursor_width;
3563 r[i].size.width -= width;
3564 r[i].origin.x += width;
3568 /* Draw overlining, etc. on the cursor. */
3569 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3570 ns_draw_text_decoration (s, face, bgCol, width, x);
3572 ns_draw_text_decoration (s, face, fgCol, width, x);
3579 /* Draw overlining, etc. on the stretch glyph (or the part
3580 of the stretch glyph after the cursor). */
3581 ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3585 s->background_filled_p = 1;
3591 ns_draw_glyph_string_foreground (struct glyph_string *s)
3594 struct font *font = s->font;
3596 /* If first glyph of S has a left box line, start drawing the text
3597 of S to the right of that box line. */
3598 if (s->face && s->face->box != FACE_NO_BOX
3599 && s->first_glyph->left_box_line_p)
3600 x = s->x + eabs (s->face->box_line_width);
3604 flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3605 (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3606 (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3607 NS_DUMPGLYPH_NORMAL));
3610 (s, s->cmp_from, s->nchars, x, s->ybase,
3611 (flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3612 || flags == NS_DUMPGLYPH_MOUSEFACE);
3617 ns_draw_composite_glyph_string_foreground (struct glyph_string *s)
3620 struct font *font = s->font;
3622 /* If first glyph of S has a left box line, start drawing the text
3623 of S to the right of that box line. */
3624 if (s->face && s->face->box != FACE_NO_BOX
3625 && s->first_glyph->left_box_line_p)
3626 x = s->x + eabs (s->face->box_line_width);
3630 /* S is a glyph string for a composition. S->cmp_from is the index
3631 of the first character drawn for glyphs of this composition.
3632 S->cmp_from == 0 means we are drawing the very first character of
3633 this composition. */
3635 /* Draw a rectangle for the composition if the font for the very
3636 first character of the composition could not be loaded. */
3637 if (s->font_not_found_p)
3639 if (s->cmp_from == 0)
3641 NSRect r = NSMakeRect (s->x, s->y, s->width-1, s->height -1);
3642 ns_draw_box (r, 1, FRAME_CURSOR_COLOR (s->f), 1, 1);
3645 else if (! s->first_glyph->u.cmp.automatic)
3649 for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
3650 /* TAB in a composition means display glyphs with padding
3651 space on the left or right. */
3652 if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
3654 int xx = x + s->cmp->offsets[j * 2];
3655 int yy = y - s->cmp->offsets[j * 2 + 1];
3657 font->driver->draw (s, j, j + 1, xx, yy, false);
3658 if (s->face->overstrike)
3659 font->driver->draw (s, j, j + 1, xx + 1, yy, false);
3664 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
3669 for (i = j = s->cmp_from; i < s->cmp_to; i++)
3671 glyph = LGSTRING_GLYPH (gstring, i);
3672 if (NILP (LGLYPH_ADJUSTMENT (glyph)))
3673 width += LGLYPH_WIDTH (glyph);
3676 int xoff, yoff, wadjust;
3680 font->driver->draw (s, j, i, x, y, false);
3681 if (s->face->overstrike)
3682 font->driver->draw (s, j, i, x + 1, y, false);
3685 xoff = LGLYPH_XOFF (glyph);
3686 yoff = LGLYPH_YOFF (glyph);
3687 wadjust = LGLYPH_WADJUST (glyph);
3688 font->driver->draw (s, i, i + 1, x + xoff, y + yoff, false);
3689 if (s->face->overstrike)
3690 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff,
3699 font->driver->draw (s, j, i, x, y, false);
3700 if (s->face->overstrike)
3701 font->driver->draw (s, j, i, x + 1, y, false);
3707 ns_draw_glyph_string (struct glyph_string *s)
3708 /* --------------------------------------------------------------------------
3709 External (RIF): Main draw-text call.
3710 -------------------------------------------------------------------------- */
3712 /* TODO (optimize): focus for box and contents draw */
3715 char box_drawn_p = 0;
3716 struct font *font = s->face->font;
3717 if (! font) font = FRAME_FONT (s->f);
3719 NSTRACE_WHEN (NSTRACE_GROUP_GLYPHS, "ns_draw_glyph_string");
3721 if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3724 struct glyph_string *next;
3726 for (width = 0, next = s->next;
3727 next && width < s->right_overhang;
3728 width += next->width, next = next->next)
3729 if (next->first_glyph->type != IMAGE_GLYPH)
3731 if (next->first_glyph->type != STRETCH_GLYPH)
3733 n = ns_get_glyph_string_clip_rect (s->next, r);
3734 ns_focus (s->f, r, n);
3735 ns_maybe_dumpglyphs_background (s->next, 1);
3740 ns_dumpglyphs_stretch (s->next);
3742 next->num_clips = 0;
3746 if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3747 && (s->first_glyph->type == CHAR_GLYPH
3748 || s->first_glyph->type == COMPOSITE_GLYPH))
3750 n = ns_get_glyph_string_clip_rect (s, r);
3751 ns_focus (s->f, r, n);
3752 ns_maybe_dumpglyphs_background (s, 1);
3753 ns_dumpglyphs_box_or_relief (s);
3758 switch (s->first_glyph->type)
3762 n = ns_get_glyph_string_clip_rect (s, r);
3763 ns_focus (s->f, r, n);
3764 ns_dumpglyphs_image (s, r[0]);
3769 ns_dumpglyphs_stretch (s);
3773 case COMPOSITE_GLYPH:
3774 n = ns_get_glyph_string_clip_rect (s, r);
3775 ns_focus (s->f, r, n);
3777 if (s->for_overlaps || (s->cmp_from > 0
3778 && ! s->first_glyph->u.cmp.automatic))
3779 s->background_filled_p = 1;
3781 ns_maybe_dumpglyphs_background
3782 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3784 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3786 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3787 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3788 NS_FACE_FOREGROUND (s->face) = tmp;
3792 BOOL isComposite = s->first_glyph->type == COMPOSITE_GLYPH;
3795 ns_draw_composite_glyph_string_foreground (s);
3797 ns_draw_glyph_string_foreground (s);
3801 NSColor *col = (NS_FACE_FOREGROUND (s->face) != 0
3802 ? ns_lookup_indexed_color (NS_FACE_FOREGROUND (s->face),
3804 : FRAME_FOREGROUND_COLOR (s->f));
3807 /* Draw underline, overline, strike-through. */
3808 ns_draw_text_decoration (s, s->face, col, s->width, s->x);
3811 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3813 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3814 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3815 NS_FACE_FOREGROUND (s->face) = tmp;
3821 case GLYPHLESS_GLYPH:
3822 n = ns_get_glyph_string_clip_rect (s, r);
3823 ns_focus (s->f, r, n);
3825 if (s->for_overlaps || (s->cmp_from > 0
3826 && ! s->first_glyph->u.cmp.automatic))
3827 s->background_filled_p = 1;
3829 ns_maybe_dumpglyphs_background
3830 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3832 /* Not yet implemented. */
3841 /* Draw box if not done already. */
3842 if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3844 n = ns_get_glyph_string_clip_rect (s, r);
3845 ns_focus (s->f, r, n);
3846 ns_dumpglyphs_box_or_relief (s);
3855 /* ==========================================================================
3859 ========================================================================== */
3863 ns_send_appdefined (int value)
3864 /* --------------------------------------------------------------------------
3865 Internal: post an appdefined event which EmacsApp-sendEvent will
3866 recognize and take as a command to halt the event loop.
3867 -------------------------------------------------------------------------- */
3869 NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_send_appdefined(%d)", value);
3871 // GNUstep needs postEvent to happen on the main thread.
3872 // Cocoa needs nextEventMatchingMask to happen on the main thread too.
3873 if (! [[NSThread currentThread] isMainThread])
3875 EmacsApp *app = (EmacsApp *)NSApp;
3876 app->nextappdefined = value;
3877 [app performSelectorOnMainThread:@selector (sendFromMainThread:)
3883 /* Only post this event if we haven't already posted one. This will end
3884 the [NXApp run] main loop after having processed all events queued at
3887 #ifdef NS_IMPL_COCOA
3888 if (! send_appdefined)
3890 /* OS X 10.10.1 swallows the AppDefined event we are sending ourselves
3891 in certain situations (rapid incoming events).
3892 So check if we have one, if not add one. */
3893 NSEvent *appev = [NSApp nextEventMatchingMask:NSEventMaskApplicationDefined
3894 untilDate:[NSDate distantPast]
3895 inMode:NSDefaultRunLoopMode
3897 if (! appev) send_appdefined = YES;
3901 if (send_appdefined)
3905 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
3906 send_appdefined = NO;
3908 /* Don't need wakeup timer any more */
3911 [timed_entry invalidate];
3912 [timed_entry release];
3916 nxev = [NSEvent otherEventWithType: NSEventTypeApplicationDefined
3917 location: NSMakePoint (0, 0)
3920 windowNumber: [[NSApp mainWindow] windowNumber]
3921 context: [NSApp context]
3926 /* Post an application defined event on the event queue. When this is
3927 received the [NXApp run] will return, thus having processed all
3928 events which are currently queued. */
3929 [NSApp postEvent: nxev atStart: NO];
3933 #ifdef HAVE_NATIVE_FS
3937 Lisp_Object frame, tail;
3939 if (ns_last_use_native_fullscreen == ns_use_native_fullscreen)
3942 ns_last_use_native_fullscreen = ns_use_native_fullscreen;
3944 FOR_EACH_FRAME (tail, frame)
3946 struct frame *f = XFRAME (frame);
3949 EmacsView *view = FRAME_NS_VIEW (f);
3950 [view updateCollectionBehavior];
3956 /* GNUstep does not have cancelTracking. */
3957 #ifdef NS_IMPL_COCOA
3958 /* Check if menu open should be canceled or continued as normal. */
3960 ns_check_menu_open (NSMenu *menu)
3962 /* Click in menu bar? */
3963 NSArray *a = [[NSApp mainMenu] itemArray];
3967 if (menu == nil) // Menu tracking ended.
3969 if (menu_will_open_state == MENU_OPENING)
3970 menu_will_open_state = MENU_NONE;
3974 for (i = 0; ! found && i < [a count]; i++)
3975 found = menu == [[a objectAtIndex:i] submenu];
3978 if (menu_will_open_state == MENU_NONE && emacs_event)
3980 NSEvent *theEvent = [NSApp currentEvent];
3981 struct frame *emacsframe = SELECTED_FRAME ();
3983 [menu cancelTracking];
3984 menu_will_open_state = MENU_PENDING;
3985 emacs_event->kind = MENU_BAR_ACTIVATE_EVENT;
3986 EV_TRAILER (theEvent);
3988 CGEventRef ourEvent = CGEventCreate (NULL);
3989 menu_mouse_point = CGEventGetLocation (ourEvent);
3990 CFRelease (ourEvent);
3992 else if (menu_will_open_state == MENU_OPENING)
3994 menu_will_open_state = MENU_NONE;
3999 /* Redo saved menu click if state is MENU_PENDING. */
4001 ns_check_pending_open_menu ()
4003 if (menu_will_open_state == MENU_PENDING)
4005 CGEventSourceRef source
4006 = CGEventSourceCreate (kCGEventSourceStateHIDSystemState);
4008 CGEventRef event = CGEventCreateMouseEvent (source,
4009 kCGEventLeftMouseDown,
4011 kCGMouseButtonLeft);
4012 CGEventSetType (event, kCGEventLeftMouseDown);
4013 CGEventPost (kCGHIDEventTap, event);
4017 menu_will_open_state = MENU_OPENING;
4020 #endif /* NS_IMPL_COCOA */
4023 ns_read_socket (struct terminal *terminal, struct input_event *hold_quit)
4024 /* --------------------------------------------------------------------------
4025 External (hook): Post an event to ourself and keep reading events until
4026 we read it back again. In effect process all events which were waiting.
4027 From 21+ we have to manage the event buffer ourselves.
4028 -------------------------------------------------------------------------- */
4030 struct input_event ev;
4033 NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_read_socket");
4035 #ifdef HAVE_NATIVE_FS
4039 if ([NSApp modalWindow] != nil)
4042 if (hold_event_q.nr > 0)
4045 for (i = 0; i < hold_event_q.nr; ++i)
4046 kbd_buffer_store_event_hold (&hold_event_q.q[i], hold_quit);
4047 hold_event_q.nr = 0;
4051 if ([NSThread isMainThread])
4054 n_emacs_events_pending = 0;
4055 ns_init_events (&ev);
4056 q_event_ptr = hold_quit;
4058 /* we manage autorelease pools by allocate/reallocate each time around
4059 the loop; strict nesting is occasionally violated but seems not to
4060 matter.. earlier methods using full nesting caused major memory leaks */
4061 [outerpool release];
4062 outerpool = [[NSAutoreleasePool alloc] init];
4064 /* If have pending open-file requests, attend to the next one of those. */
4065 if (ns_pending_files && [ns_pending_files count] != 0
4066 && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
4068 [ns_pending_files removeObjectAtIndex: 0];
4070 /* Deal with pending service requests. */
4071 else if (ns_pending_service_names && [ns_pending_service_names count] != 0
4073 NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
4074 withArg: [ns_pending_service_args objectAtIndex: 0]])
4076 [ns_pending_service_names removeObjectAtIndex: 0];
4077 [ns_pending_service_args removeObjectAtIndex: 0];
4081 ptrdiff_t specpdl_count = SPECPDL_INDEX ();
4082 /* Run and wait for events. We must always send one NX_APPDEFINED event
4083 to ourself, otherwise [NXApp run] will never exit. */
4084 send_appdefined = YES;
4085 ns_send_appdefined (-1);
4090 nevents = n_emacs_events_pending;
4091 n_emacs_events_pending = 0;
4092 ns_finish_events ();
4102 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
4103 fd_set *exceptfds, struct timespec const *timeout,
4104 sigset_t const *sigmask)
4105 /* --------------------------------------------------------------------------
4106 Replacement for select, checking for events
4107 -------------------------------------------------------------------------- */
4111 struct input_event event;
4114 NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_select");
4116 #ifdef HAVE_NATIVE_FS
4120 if (hold_event_q.nr > 0)
4122 /* We already have events pending. */
4128 for (k = 0; k < nfds+1; k++)
4130 if (readfds && FD_ISSET(k, readfds)) ++nr;
4131 if (writefds && FD_ISSET(k, writefds)) ++nr;
4135 || ![NSThread isMainThread]
4136 || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0))
4137 return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
4139 [outerpool release];
4140 outerpool = [[NSAutoreleasePool alloc] init];
4143 send_appdefined = YES;
4146 pthread_mutex_lock (&select_mutex);
4151 select_readfds = *readfds;
4152 select_valid += SELECT_HAVE_READ;
4156 select_writefds = *writefds;
4157 select_valid += SELECT_HAVE_WRITE;
4162 select_timeout = *timeout;
4163 select_valid += SELECT_HAVE_TMO;
4166 pthread_mutex_unlock (&select_mutex);
4168 /* Inform fd_handler that select should be called */
4170 emacs_write_sig (selfds[1], &c, 1);
4172 else if (nr == 0 && timeout)
4174 /* No file descriptor, just a timeout, no need to wake fd_handler */
4175 double time = timespectod (*timeout);
4176 timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
4179 @selector (timeout_handler:)
4184 else /* No timeout and no file descriptors, can this happen? */
4186 /* Send appdefined so we exit from the loop */
4187 ns_send_appdefined (-1);
4191 ns_init_events (&event);
4195 ns_finish_events ();
4196 if (nr > 0 && readfds)
4199 emacs_write_sig (selfds[1], &c, 1);
4203 t = last_appdefined_event_data;
4205 if (t != NO_APPDEFINED_DATA)
4207 last_appdefined_event_data = NO_APPDEFINED_DATA;
4211 /* The NX_APPDEFINED event we received was a timeout. */
4216 /* The NX_APPDEFINED event we received was the result of
4217 at least one real input event arriving. */
4223 /* Received back from select () in fd_handler; copy the results */
4224 pthread_mutex_lock (&select_mutex);
4225 if (readfds) *readfds = select_readfds;
4226 if (writefds) *writefds = select_writefds;
4227 pthread_mutex_unlock (&select_mutex);
4242 /* ==========================================================================
4246 ========================================================================== */
4250 ns_set_vertical_scroll_bar (struct window *window,
4251 int portion, int whole, int position)
4252 /* --------------------------------------------------------------------------
4253 External (hook): Update or add scrollbar
4254 -------------------------------------------------------------------------- */
4258 struct frame *f = XFRAME (WINDOW_FRAME (window));
4259 EmacsView *view = FRAME_NS_VIEW (f);
4261 int window_y, window_height;
4262 int top, left, height, width;
4263 BOOL update_p = YES;
4265 /* optimization; display engine sends WAY too many of these.. */
4266 if (!NILP (window->vertical_scroll_bar))
4268 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4269 if ([bar checkSamePosition: position portion: portion whole: whole])
4271 if (view->scrollbarsNeedingUpdate == 0)
4273 if (!windows_or_buffers_changed)
4277 view->scrollbarsNeedingUpdate--;
4282 NSTRACE ("ns_set_vertical_scroll_bar");
4284 /* Get dimensions. */
4285 window_box (window, ANY_AREA, 0, &window_y, 0, &window_height);
4287 height = window_height;
4288 width = NS_SCROLL_BAR_WIDTH (f);
4289 left = WINDOW_SCROLL_BAR_AREA_X (window);
4291 r = NSMakeRect (left, top, width, height);
4292 /* the parent view is flipped, so we need to flip y value */
4294 r.origin.y = (v.size.height - r.size.height - r.origin.y);
4296 XSETWINDOW (win, window);
4299 /* we want at least 5 lines to display a scrollbar */
4300 if (WINDOW_TOTAL_LINES (window) < 5)
4302 if (!NILP (window->vertical_scroll_bar))
4304 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4305 [bar removeFromSuperview];
4306 wset_vertical_scroll_bar (window, Qnil);
4309 ns_clear_frame_area (f, left, top, width, height);
4314 if (NILP (window->vertical_scroll_bar))
4316 if (width > 0 && height > 0)
4317 ns_clear_frame_area (f, left, top, width, height);
4319 bar = [[EmacsScroller alloc] initFrame: r window: win];
4320 wset_vertical_scroll_bar (window, make_save_ptr (bar));
4326 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4327 oldRect = [bar frame];
4328 r.size.width = oldRect.size.width;
4329 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4331 if (oldRect.origin.x != r.origin.x)
4332 ns_clear_frame_area (f, left, top, width, height);
4338 [bar setPosition: position portion: portion whole: whole];
4344 ns_set_horizontal_scroll_bar (struct window *window,
4345 int portion, int whole, int position)
4346 /* --------------------------------------------------------------------------
4347 External (hook): Update or add scrollbar
4348 -------------------------------------------------------------------------- */
4352 struct frame *f = XFRAME (WINDOW_FRAME (window));
4353 EmacsView *view = FRAME_NS_VIEW (f);
4355 int top, height, left, width;
4356 int window_x, window_width;
4357 BOOL update_p = YES;
4359 /* optimization; display engine sends WAY too many of these.. */
4360 if (!NILP (window->horizontal_scroll_bar))
4362 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4363 if ([bar checkSamePosition: position portion: portion whole: whole])
4365 if (view->scrollbarsNeedingUpdate == 0)
4367 if (!windows_or_buffers_changed)
4371 view->scrollbarsNeedingUpdate--;
4376 NSTRACE ("ns_set_horizontal_scroll_bar");
4378 /* Get dimensions. */
4379 window_box (window, ANY_AREA, &window_x, 0, &window_width, 0);
4381 width = window_width;
4382 height = NS_SCROLL_BAR_HEIGHT (f);
4383 top = WINDOW_SCROLL_BAR_AREA_Y (window);
4385 r = NSMakeRect (left, top, width, height);
4386 /* the parent view is flipped, so we need to flip y value */
4388 r.origin.y = (v.size.height - r.size.height - r.origin.y);
4390 XSETWINDOW (win, window);
4393 if (NILP (window->horizontal_scroll_bar))
4395 if (width > 0 && height > 0)
4396 ns_clear_frame_area (f, left, top, width, height);
4398 bar = [[EmacsScroller alloc] initFrame: r window: win];
4399 wset_horizontal_scroll_bar (window, make_save_ptr (bar));
4405 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4406 oldRect = [bar frame];
4407 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4409 if (oldRect.origin.y != r.origin.y)
4410 ns_clear_frame_area (f, left, top, width, height);
4416 /* If there are both horizontal and vertical scroll-bars they leave
4417 a square that belongs to neither. We need to clear it otherwise
4418 it fills with junk. */
4419 if (!NILP (window->vertical_scroll_bar))
4420 ns_clear_frame_area (f, WINDOW_SCROLL_BAR_AREA_X (window), top,
4421 NS_SCROLL_BAR_HEIGHT (f), height);
4424 [bar setPosition: position portion: portion whole: whole];
4430 ns_condemn_scroll_bars (struct frame *f)
4431 /* --------------------------------------------------------------------------
4432 External (hook): arrange for all frame's scrollbars to be removed
4433 at next call to judge_scroll_bars, except for those redeemed.
4434 -------------------------------------------------------------------------- */
4438 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
4440 NSTRACE ("ns_condemn_scroll_bars");
4442 for (i =[subviews count]-1; i >= 0; i--)
4444 view = [subviews objectAtIndex: i];
4445 if ([view isKindOfClass: [EmacsScroller class]])
4452 ns_redeem_scroll_bar (struct window *window)
4453 /* --------------------------------------------------------------------------
4454 External (hook): arrange to spare this window's scrollbar
4455 at next call to judge_scroll_bars.
4456 -------------------------------------------------------------------------- */
4459 NSTRACE ("ns_redeem_scroll_bar");
4460 if (!NILP (window->vertical_scroll_bar)
4461 && WINDOW_HAS_VERTICAL_SCROLL_BAR (window))
4463 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4467 if (!NILP (window->horizontal_scroll_bar)
4468 && WINDOW_HAS_HORIZONTAL_SCROLL_BAR (window))
4470 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4477 ns_judge_scroll_bars (struct frame *f)
4478 /* --------------------------------------------------------------------------
4479 External (hook): destroy all scrollbars on frame that weren't
4480 redeemed after call to condemn_scroll_bars.
4481 -------------------------------------------------------------------------- */
4485 EmacsView *eview = FRAME_NS_VIEW (f);
4486 NSArray *subviews = [[eview superview] subviews];
4489 NSTRACE ("ns_judge_scroll_bars");
4490 for (i = [subviews count]-1; i >= 0; --i)
4492 view = [subviews objectAtIndex: i];
4493 if (![view isKindOfClass: [EmacsScroller class]]) continue;
4499 [eview updateFrameSize: NO];
4502 /* ==========================================================================
4506 ========================================================================== */
4509 x_display_pixel_height (struct ns_display_info *dpyinfo)
4511 NSArray *screens = [NSScreen screens];
4512 NSEnumerator *enumerator = [screens objectEnumerator];
4517 while ((screen = [enumerator nextObject]) != nil)
4518 frame = NSUnionRect (frame, [screen frame]);
4520 return NSHeight (frame);
4524 x_display_pixel_width (struct ns_display_info *dpyinfo)
4526 NSArray *screens = [NSScreen screens];
4527 NSEnumerator *enumerator = [screens objectEnumerator];
4532 while ((screen = [enumerator nextObject]) != nil)
4533 frame = NSUnionRect (frame, [screen frame]);
4535 return NSWidth (frame);
4539 static Lisp_Object ns_string_to_lispmod (const char *s)
4540 /* --------------------------------------------------------------------------
4541 Convert modifier name to lisp symbol
4542 -------------------------------------------------------------------------- */
4544 if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
4546 else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
4548 else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
4550 else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
4552 else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
4554 else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
4562 ns_default (const char *parameter, Lisp_Object *result,
4563 Lisp_Object yesval, Lisp_Object noval,
4564 BOOL is_float, BOOL is_modstring)
4565 /* --------------------------------------------------------------------------
4566 Check a parameter value in user's preferences
4567 -------------------------------------------------------------------------- */
4569 const char *value = ns_get_defaults_value (parameter);
4575 if (c_strcasecmp (value, "YES") == 0)
4577 else if (c_strcasecmp (value, "NO") == 0)
4579 else if (is_float && (f = strtod (value, &pos), pos != value))
4580 *result = make_float (f);
4581 else if (is_modstring && value)
4582 *result = ns_string_to_lispmod (value);
4583 else fprintf (stderr,
4584 "Bad value for default \"%s\": \"%s\"\n", parameter, value);
4590 ns_initialize_display_info (struct ns_display_info *dpyinfo)
4591 /* --------------------------------------------------------------------------
4592 Initialize global info and storage for display.
4593 -------------------------------------------------------------------------- */
4595 NSScreen *screen = [NSScreen mainScreen];
4596 NSWindowDepth depth = [screen depth];
4598 dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
4599 dpyinfo->resy = 72.27;
4600 dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
4601 NSColorSpaceFromDepth (depth)]
4602 && ![NSCalibratedWhiteColorSpace isEqualToString:
4603 NSColorSpaceFromDepth (depth)];
4604 dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
4605 dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
4606 dpyinfo->color_table->colors = NULL;
4607 dpyinfo->root_window = 42; /* a placeholder.. */
4608 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
4609 dpyinfo->n_fonts = 0;
4610 dpyinfo->smallest_font_height = 1;
4611 dpyinfo->smallest_char_width = 1;
4613 reset_mouse_highlight (&dpyinfo->mouse_highlight);
4617 /* This and next define (many of the) public functions in this file. */
4618 /* x_... are generic versions in xdisp.c that we, and other terms, get away
4619 with using despite presence in the "system dependent" redisplay
4620 interface. In addition, many of the ns_ methods have code that is
4621 shared with all terms, indicating need for further refactoring. */
4622 extern frame_parm_handler ns_frame_parm_handlers[];
4623 static struct redisplay_interface ns_redisplay_interface =
4625 ns_frame_parm_handlers,
4629 x_clear_end_of_line,
4631 ns_after_update_window_line,
4632 ns_update_window_begin,
4633 ns_update_window_end,
4634 0, /* flush_display */
4635 x_clear_window_mouse_face,
4636 x_get_glyph_overhangs,
4637 x_fix_overlapping_area,
4638 ns_draw_fringe_bitmap,
4639 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
4640 0, /* destroy_fringe_bitmap */
4641 ns_compute_glyph_string_overhangs,
4642 ns_draw_glyph_string,
4643 ns_define_frame_cursor,
4644 ns_clear_frame_area,
4645 ns_draw_window_cursor,
4646 ns_draw_vertical_window_border,
4647 ns_draw_window_divider,
4648 ns_shift_glyphs_for_insert,
4655 ns_delete_display (struct ns_display_info *dpyinfo)
4661 /* This function is called when the last frame on a display is deleted. */
4663 ns_delete_terminal (struct terminal *terminal)
4665 struct ns_display_info *dpyinfo = terminal->display_info.ns;
4667 NSTRACE ("ns_delete_terminal");
4669 /* Protect against recursive calls. delete_frame in
4670 delete_terminal calls us back when it deletes our last frame. */
4671 if (!terminal->name)
4676 x_destroy_all_bitmaps (dpyinfo);
4677 ns_delete_display (dpyinfo);
4682 static struct terminal *
4683 ns_create_terminal (struct ns_display_info *dpyinfo)
4684 /* --------------------------------------------------------------------------
4685 Set up use of NS before we make the first connection.
4686 -------------------------------------------------------------------------- */
4688 struct terminal *terminal;
4690 NSTRACE ("ns_create_terminal");
4692 terminal = create_terminal (output_ns, &ns_redisplay_interface);
4694 terminal->display_info.ns = dpyinfo;
4695 dpyinfo->terminal = terminal;
4697 terminal->clear_frame_hook = ns_clear_frame;
4698 terminal->ring_bell_hook = ns_ring_bell;
4699 terminal->update_begin_hook = ns_update_begin;
4700 terminal->update_end_hook = ns_update_end;
4701 terminal->read_socket_hook = ns_read_socket;
4702 terminal->frame_up_to_date_hook = ns_frame_up_to_date;
4703 terminal->mouse_position_hook = ns_mouse_position;
4704 terminal->frame_rehighlight_hook = ns_frame_rehighlight;
4705 terminal->frame_raise_lower_hook = ns_frame_raise_lower;
4706 terminal->fullscreen_hook = ns_fullscreen_hook;
4707 terminal->menu_show_hook = ns_menu_show;
4708 terminal->popup_dialog_hook = ns_popup_dialog;
4709 terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
4710 terminal->set_horizontal_scroll_bar_hook = ns_set_horizontal_scroll_bar;
4711 terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
4712 terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
4713 terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
4714 terminal->delete_frame_hook = x_destroy_window;
4715 terminal->delete_terminal_hook = ns_delete_terminal;
4716 /* Other hooks are NULL by default. */
4722 struct ns_display_info *
4723 ns_term_init (Lisp_Object display_name)
4724 /* --------------------------------------------------------------------------
4725 Start the Application and get things rolling.
4726 -------------------------------------------------------------------------- */
4728 struct terminal *terminal;
4729 struct ns_display_info *dpyinfo;
4730 static int ns_initialized = 0;
4733 if (ns_initialized) return x_display_list;
4738 NSTRACE ("ns_term_init");
4740 [outerpool release];
4741 outerpool = [[NSAutoreleasePool alloc] init];
4743 /* count object allocs (About, click icon); on macOS use ObjectAlloc tool */
4744 /*GSDebugAllocationActive (YES); */
4748 Fset_input_interrupt_mode (Qnil);
4750 if (selfds[0] == -1)
4752 if (emacs_pipe (selfds) != 0)
4754 fprintf (stderr, "Failed to create pipe: %s\n",
4755 emacs_strerror (errno));
4759 fcntl (selfds[0], F_SETFL, O_NONBLOCK|fcntl (selfds[0], F_GETFL));
4760 FD_ZERO (&select_readfds);
4761 FD_ZERO (&select_writefds);
4762 pthread_mutex_init (&select_mutex, NULL);
4765 ns_pending_files = [[NSMutableArray alloc] init];
4766 ns_pending_service_names = [[NSMutableArray alloc] init];
4767 ns_pending_service_args = [[NSMutableArray alloc] init];
4769 /* Start app and create the main menu, window, view.
4770 Needs to be here because ns_initialize_display_info () uses AppKit classes.
4771 The view will then ask the NSApp to stop and return to Emacs. */
4772 [EmacsApp sharedApplication];
4775 [NSApp setDelegate: NSApp];
4777 /* Start the select thread. */
4778 [NSThread detachNewThreadSelector:@selector (fd_handler:)
4782 /* debugging: log all notifications */
4783 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
4784 selector: @selector (logNotification:)
4785 name: nil object: nil]; */
4787 dpyinfo = xzalloc (sizeof *dpyinfo);
4789 ns_initialize_display_info (dpyinfo);
4790 terminal = ns_create_terminal (dpyinfo);
4792 terminal->kboard = allocate_kboard (Qns);
4793 /* Don't let the initial kboard remain current longer than necessary.
4794 That would cause problems if a file loaded on startup tries to
4795 prompt in the mini-buffer. */
4796 if (current_kboard == initial_kboard)
4797 current_kboard = terminal->kboard;
4798 terminal->kboard->reference_count++;
4800 dpyinfo->next = x_display_list;
4801 x_display_list = dpyinfo;
4803 dpyinfo->name_list_element = Fcons (display_name, Qnil);
4805 terminal->name = xlispstrdup (display_name);
4809 if (!inhibit_x_resources)
4811 ns_default ("GSFontAntiAlias", &ns_antialias_text,
4814 /* this is a standard variable */
4815 ns_default ("AppleAntiAliasingThreshold", &tmp,
4816 make_float (10.0), make_float (6.0), YES, NO);
4817 ns_antialias_threshold = NILP (tmp) ? 10.0 : extract_float (tmp);
4820 NSTRACE_MSG ("Colors");
4823 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4827 Lisp_Object color_file, color_map, color;
4831 color_file = Fexpand_file_name (build_string ("rgb.txt"),
4832 Fsymbol_value (intern ("data-directory")));
4834 color_map = Fx_load_color_file (color_file);
4835 if (NILP (color_map))
4836 fatal ("Could not read %s.\n", SDATA (color_file));
4838 cl = [[NSColorList alloc] initWithName: @"Emacs"];
4839 for ( ; CONSP (color_map); color_map = XCDR (color_map))
4841 color = XCAR (color_map);
4842 name = SSDATA (XCAR (color));
4843 c = XINT (XCDR (color));
4845 [NSColor colorForEmacsRed: RED_FROM_ULONG (c) / 255.0
4846 green: GREEN_FROM_ULONG (c) / 255.0
4847 blue: BLUE_FROM_ULONG (c) / 255.0
4849 forKey: [NSString stringWithUTF8String: name]];
4851 [cl writeToFile: nil];
4855 NSTRACE_MSG ("Versions");
4858 #ifdef NS_IMPL_GNUSTEP
4859 Vwindow_system_version = build_string (gnustep_base_version);
4861 /*PSnextrelease (128, c); */
4862 char c[DBL_BUFSIZE_BOUND];
4863 int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4864 Vwindow_system_version = make_unibyte_string (c, len);
4868 delete_keyboard_wait_descriptor (0);
4870 ns_app_name = [[NSProcessInfo processInfo] processName];
4872 /* Set up macOS app menu */
4874 NSTRACE_MSG ("Menu init");
4876 #ifdef NS_IMPL_COCOA
4880 /* set up the application menu */
4881 svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4882 [svcsMenu setAutoenablesItems: NO];
4883 appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4884 [appMenu setAutoenablesItems: NO];
4885 mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4886 dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4888 [appMenu insertItemWithTitle: @"About Emacs"
4889 action: @selector (orderFrontStandardAboutPanel:)
4892 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4893 [appMenu insertItemWithTitle: @"Preferences..."
4894 action: @selector (showPreferencesWindow:)
4897 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4898 item = [appMenu insertItemWithTitle: @"Services"
4899 action: @selector (menuDown:)
4902 [appMenu setSubmenu: svcsMenu forItem: item];
4903 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4904 [appMenu insertItemWithTitle: @"Hide Emacs"
4905 action: @selector (hide:)
4908 item = [appMenu insertItemWithTitle: @"Hide Others"
4909 action: @selector (hideOtherApplications:)
4912 [item setKeyEquivalentModifierMask: NSEventModifierFlagCommand | NSEventModifierFlagOption];
4913 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4914 [appMenu insertItemWithTitle: @"Quit Emacs"
4915 action: @selector (terminate:)
4919 item = [mainMenu insertItemWithTitle: ns_app_name
4920 action: @selector (menuDown:)
4923 [mainMenu setSubmenu: appMenu forItem: item];
4924 [dockMenu insertItemWithTitle: @"New Frame"
4925 action: @selector (newFrame:)
4929 [NSApp setMainMenu: mainMenu];
4930 [NSApp setAppleMenu: appMenu];
4931 [NSApp setServicesMenu: svcsMenu];
4932 /* Needed at least on Cocoa, to get dock menu to show windows */
4933 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4935 [[NSNotificationCenter defaultCenter]
4936 addObserver: mainMenu
4937 selector: @selector (trackingNotification:)
4938 name: NSMenuDidBeginTrackingNotification object: mainMenu];
4939 [[NSNotificationCenter defaultCenter]
4940 addObserver: mainMenu
4941 selector: @selector (trackingNotification:)
4942 name: NSMenuDidEndTrackingNotification object: mainMenu];
4944 #endif /* macOS menu setup */
4946 /* Register our external input/output types, used for determining
4947 applicable services and also drag/drop eligibility. */
4949 NSTRACE_MSG ("Input/output types");
4951 ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
4952 ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
4954 ns_drag_types = [[NSArray arrayWithObjects:
4956 NSTabularTextPboardType,
4957 NSFilenamesPboardType,
4958 NSURLPboardType, nil] retain];
4960 /* If fullscreen is in init/default-frame-alist, focus isn't set
4961 right for fullscreen windows, so set this. */
4962 [NSApp activateIgnoringOtherApps:YES];
4964 NSTRACE_MSG ("Call NSApp run");
4967 ns_do_open_file = YES;
4969 #ifdef NS_IMPL_GNUSTEP
4970 /* GNUstep steals SIGCHLD for use in NSTask, but we don't use NSTask.
4971 We must re-catch it so subprocess works. */
4972 catch_child_signal ();
4975 NSTRACE_MSG ("ns_term_init done");
4984 ns_term_shutdown (int sig)
4986 [[NSUserDefaults standardUserDefaults] synchronize];
4988 /* code not reached in emacs.c after this is called by shut_down_emacs: */
4989 if (STRINGP (Vauto_save_list_file_name))
4990 unlink (SSDATA (Vauto_save_list_file_name));
4992 if (sig == 0 || sig == SIGTERM)
4994 [NSApp terminate: NSApp];
4996 else // force a stack trace to happen
5003 /* ==========================================================================
5005 EmacsApp implementation
5007 ========================================================================== */
5010 @implementation EmacsApp
5014 NSTRACE ("[EmacsApp init]");
5016 if ((self = [super init]))
5018 #ifdef NS_IMPL_COCOA
5019 self->isFirst = YES;
5021 #ifdef NS_IMPL_GNUSTEP
5022 self->applicationDidFinishLaunchingCalled = NO;
5029 #ifdef NS_IMPL_COCOA
5032 NSTRACE ("[EmacsApp run]");
5034 #ifndef NSAppKitVersionNumber10_9
5035 #define NSAppKitVersionNumber10_9 1265
5038 if ((int)NSAppKitVersionNumber != NSAppKitVersionNumber10_9)
5044 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
5046 if (isFirst) [self finishLaunching];
5049 shouldKeepRunning = YES;
5053 pool = [[NSAutoreleasePool alloc] init];
5056 [self nextEventMatchingMask:NSEventMaskAny
5057 untilDate:[NSDate distantFuture]
5058 inMode:NSDefaultRunLoopMode
5061 [self sendEvent:event];
5062 [self updateWindows];
5063 } while (shouldKeepRunning);
5068 - (void)stop: (id)sender
5070 NSTRACE ("[EmacsApp stop:]");
5072 shouldKeepRunning = NO;
5073 // Stop possible dialog also. Noop if no dialog present.
5074 // The file dialog still leaks 7k - 10k on 10.9 though.
5075 [super stop:sender];
5077 #endif /* NS_IMPL_COCOA */
5079 - (void)logNotification: (NSNotification *)notification
5081 NSTRACE ("[EmacsApp logNotification:]");
5083 const char *name = [[notification name] UTF8String];
5084 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
5085 && !strstr (name, "WindowNumber"))
5086 NSLog (@"notification: '%@'", [notification name]);
5090 - (void)sendEvent: (NSEvent *)theEvent
5091 /* --------------------------------------------------------------------------
5092 Called when NSApp is running for each event received. Used to stop
5093 the loop when we choose, since there's no way to just run one iteration.
5094 -------------------------------------------------------------------------- */
5096 int type = [theEvent type];
5097 NSWindow *window = [theEvent window];
5099 NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "[EmacsApp sendEvent:]");
5100 NSTRACE_MSG ("Type: %d", type);
5102 #ifdef NS_IMPL_GNUSTEP
5103 // Keyboard events aren't propagated to file dialogs for some reason.
5104 if ([NSApp modalWindow] != nil &&
5105 (type == NSEventTypeKeyDown || type == NSEventTypeKeyUp || type == NSEventTypeFlagsChanged))
5107 [[NSApp modalWindow] sendEvent: theEvent];
5112 if (represented_filename != nil && represented_frame)
5114 NSString *fstr = represented_filename;
5115 NSView *view = FRAME_NS_VIEW (represented_frame);
5116 #ifdef NS_IMPL_COCOA
5117 /* work around a bug observed on 10.3 and later where
5118 setTitleWithRepresentedFilename does not clear out previous state
5119 if given filename does not exist */
5120 if (! [[NSFileManager defaultManager] fileExistsAtPath: fstr])
5121 [[view window] setRepresentedFilename: @""];
5123 [[view window] setRepresentedFilename: fstr];
5124 [represented_filename release];
5125 represented_filename = nil;
5126 represented_frame = NULL;
5129 if (type == NSEventTypeApplicationDefined)
5131 switch ([theEvent data2])
5133 #ifdef NS_IMPL_COCOA
5134 case NSAPP_DATA2_RUNASSCRIPT:
5139 case NSAPP_DATA2_RUNFILEDIALOG:
5140 ns_run_file_dialog ();
5146 if (type == NSEventTypeCursorUpdate && window == nil)
5148 fprintf (stderr, "Dropping external cursor update event.\n");
5152 if (type == NSEventTypeApplicationDefined)
5154 /* Events posted by ns_send_appdefined interrupt the run loop here.
5155 But, if a modal window is up, an appdefined can still come through,
5156 (e.g., from a makeKeyWindow event) but stopping self also stops the
5157 modal loop. Just defer it until later. */
5158 if ([NSApp modalWindow] == nil)
5160 last_appdefined_event_data = [theEvent data1];
5165 send_appdefined = YES;
5170 #ifdef NS_IMPL_COCOA
5171 /* If no dialog and none of our frames have focus and it is a move, skip it.
5172 It is a mouse move in an auxiliary menu, i.e. on the top right on macOS,
5173 such as Wifi, sound, date or similar.
5174 This prevents "spooky" highlighting in the frame under the menu. */
5175 if (type == NSEventTypeMouseMoved && [NSApp modalWindow] == nil)
5177 struct ns_display_info *di;
5178 BOOL has_focus = NO;
5179 for (di = x_display_list; ! has_focus && di; di = di->next)
5180 has_focus = di->x_focus_frame != 0;
5186 NSTRACE_UNSILENCE();
5188 [super sendEvent: theEvent];
5192 - (void)showPreferencesWindow: (id)sender
5194 struct frame *emacsframe = SELECTED_FRAME ();
5195 NSEvent *theEvent = [NSApp currentEvent];
5199 emacs_event->kind = NS_NONKEY_EVENT;
5200 emacs_event->code = KEY_NS_SHOW_PREFS;
5201 emacs_event->modifiers = 0;
5202 EV_TRAILER (theEvent);
5206 - (void)newFrame: (id)sender
5208 NSTRACE ("[EmacsApp newFrame:]");
5210 struct frame *emacsframe = SELECTED_FRAME ();
5211 NSEvent *theEvent = [NSApp currentEvent];
5215 emacs_event->kind = NS_NONKEY_EVENT;
5216 emacs_event->code = KEY_NS_NEW_FRAME;
5217 emacs_event->modifiers = 0;
5218 EV_TRAILER (theEvent);
5222 /* Open a file (used by below, after going into queue read by ns_read_socket) */
5223 - (BOOL) openFile: (NSString *)fileName
5225 NSTRACE ("[EmacsApp openFile:]");
5227 struct frame *emacsframe = SELECTED_FRAME ();
5228 NSEvent *theEvent = [NSApp currentEvent];
5233 emacs_event->kind = NS_NONKEY_EVENT;
5234 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
5235 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
5236 ns_input_line = Qnil; /* can be start or cons start,end */
5237 emacs_event->modifiers =0;
5238 EV_TRAILER (theEvent);
5244 /* **************************************************************************
5246 EmacsApp delegate implementation
5248 ************************************************************************** */
5250 - (void)applicationDidFinishLaunching: (NSNotification *)notification
5251 /* --------------------------------------------------------------------------
5252 When application is loaded, terminate event loop in ns_term_init
5253 -------------------------------------------------------------------------- */
5255 NSTRACE ("[EmacsApp applicationDidFinishLaunching:]");
5257 #ifdef NS_IMPL_GNUSTEP
5258 ((EmacsApp *)self)->applicationDidFinishLaunchingCalled = YES;
5260 [NSApp setServicesProvider: NSApp];
5262 [self antialiasThresholdDidChange:nil];
5263 #ifdef NS_IMPL_COCOA
5264 [[NSNotificationCenter defaultCenter]
5266 selector:@selector(antialiasThresholdDidChange:)
5267 name:NSAntialiasThresholdChangedNotification
5271 ns_send_appdefined (-2);
5274 - (void)antialiasThresholdDidChange:(NSNotification *)notification
5276 #ifdef NS_IMPL_COCOA
5277 macfont_update_antialias_threshold ();
5282 /* Termination sequences:
5285 MenuBar | File | Exit:
5286 Select Quit from App menubar:
5288 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5291 Select Quit from Dock menu:
5294 Cancel -> Nothing else
5298 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5303 - (void) terminate: (id)sender
5305 NSTRACE ("[EmacsApp terminate:]");
5307 struct frame *emacsframe = SELECTED_FRAME ();
5312 emacs_event->kind = NS_NONKEY_EVENT;
5313 emacs_event->code = KEY_NS_POWER_OFF;
5314 emacs_event->arg = Qt; /* mark as non-key event */
5315 EV_TRAILER ((id)nil);
5319 runAlertPanel(NSString *title,
5320 NSString *msgFormat,
5321 NSString *defaultButton,
5322 NSString *alternateButton)
5324 #if !defined (NS_IMPL_COCOA) || \
5325 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
5326 return NSRunAlertPanel(title, msgFormat, defaultButton, alternateButton, nil)
5327 == NSAlertDefaultReturn;
5329 NSAlert *alert = [[NSAlert alloc] init];
5330 [alert setAlertStyle: NSAlertStyleCritical];
5331 [alert setMessageText: msgFormat];
5332 [alert addButtonWithTitle: defaultButton];
5333 [alert addButtonWithTitle: alternateButton];
5334 NSInteger ret = [alert runModal];
5336 return ret == NSAlertFirstButtonReturn;
5341 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
5343 NSTRACE ("[EmacsApp applicationShouldTerminate:]");
5347 if (NILP (ns_confirm_quit)) // || ns_shutdown_properly --> TO DO
5348 return NSTerminateNow;
5350 ret = runAlertPanel(ns_app_name,
5351 @"Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?",
5352 @"Save Buffers and Exit", @"Cancel");
5354 return ret ? NSTerminateNow : NSTerminateCancel;
5358 not_in_argv (NSString *arg)
5361 const char *a = [arg UTF8String];
5362 for (k = 1; k < initial_argc; ++k)
5363 if (strcmp (a, initial_argv[k]) == 0) return 0;
5367 /* Notification from the Workspace to open a file */
5368 - (BOOL)application: sender openFile: (NSString *)file
5370 if (ns_do_open_file || not_in_argv (file))
5371 [ns_pending_files addObject: file];
5376 /* Open a file as a temporary file */
5377 - (BOOL)application: sender openTempFile: (NSString *)file
5379 if (ns_do_open_file || not_in_argv (file))
5380 [ns_pending_files addObject: file];
5385 /* Notification from the Workspace to open a file noninteractively (?) */
5386 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
5388 if (ns_do_open_file || not_in_argv (file))
5389 [ns_pending_files addObject: file];
5393 /* Notification from the Workspace to open multiple files */
5394 - (void)application: sender openFiles: (NSArray *)fileList
5396 NSEnumerator *files = [fileList objectEnumerator];
5398 /* Don't open files from the command line unconditionally,
5399 Cocoa parses the command line wrong, --option value tries to open value
5400 if --option is the last option. */
5401 while ((file = [files nextObject]) != nil)
5402 if (ns_do_open_file || not_in_argv (file))
5403 [ns_pending_files addObject: file];
5405 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
5410 /* Handle dock menu requests. */
5411 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
5417 /* TODO: these may help w/IO switching btwn terminal and NSApp */
5418 - (void)applicationWillBecomeActive: (NSNotification *)notification
5420 NSTRACE ("[EmacsApp applicationWillBecomeActive:]");
5421 //ns_app_active=YES;
5424 - (void)applicationDidBecomeActive: (NSNotification *)notification
5426 NSTRACE ("[EmacsApp applicationDidBecomeActive:]");
5428 #ifdef NS_IMPL_GNUSTEP
5429 if (! applicationDidFinishLaunchingCalled)
5430 [self applicationDidFinishLaunching:notification];
5432 //ns_app_active=YES;
5434 ns_update_auto_hide_menu_bar ();
5435 // No constraining takes place when the application is not active.
5436 ns_constrain_all_frames ();
5438 - (void)applicationDidResignActive: (NSNotification *)notification
5440 NSTRACE ("[EmacsApp applicationDidResignActive:]");
5443 ns_send_appdefined (-1);
5448 /* ==========================================================================
5450 EmacsApp aux handlers for managing event loop
5452 ========================================================================== */
5455 - (void)timeout_handler: (NSTimer *)timedEntry
5456 /* --------------------------------------------------------------------------
5457 The timeout specified to ns_select has passed.
5458 -------------------------------------------------------------------------- */
5460 /*NSTRACE ("timeout_handler"); */
5461 ns_send_appdefined (-2);
5464 - (void)sendFromMainThread:(id)unused
5466 ns_send_appdefined (nextappdefined);
5469 - (void)fd_handler:(id)unused
5470 /* --------------------------------------------------------------------------
5471 Check data waiting on file descriptors and terminate if so
5472 -------------------------------------------------------------------------- */
5475 int waiting = 1, nfds;
5478 fd_set readfds, writefds, *wfds;
5479 struct timespec timeout, *tmo;
5480 NSAutoreleasePool *pool = nil;
5482 /* NSTRACE ("fd_handler"); */
5487 pool = [[NSAutoreleasePool alloc] init];
5493 FD_SET (selfds[0], &fds);
5494 result = select (selfds[0]+1, &fds, NULL, NULL, NULL);
5495 if (result > 0 && read (selfds[0], &c, 1) == 1 && c == 'g')
5500 pthread_mutex_lock (&select_mutex);
5503 if (select_valid & SELECT_HAVE_READ)
5504 readfds = select_readfds;
5508 if (select_valid & SELECT_HAVE_WRITE)
5510 writefds = select_writefds;
5515 if (select_valid & SELECT_HAVE_TMO)
5517 timeout = select_timeout;
5523 pthread_mutex_unlock (&select_mutex);
5525 FD_SET (selfds[0], &readfds);
5526 if (selfds[0] >= nfds) nfds = selfds[0]+1;
5528 result = pselect (nfds, &readfds, wfds, NULL, tmo, NULL);
5531 ns_send_appdefined (-2);
5532 else if (result > 0)
5534 if (FD_ISSET (selfds[0], &readfds))
5536 if (read (selfds[0], &c, 1) == 1 && c == 's')
5541 pthread_mutex_lock (&select_mutex);
5542 if (select_valid & SELECT_HAVE_READ)
5543 select_readfds = readfds;
5544 if (select_valid & SELECT_HAVE_WRITE)
5545 select_writefds = writefds;
5546 if (select_valid & SELECT_HAVE_TMO)
5547 select_timeout = timeout;
5548 pthread_mutex_unlock (&select_mutex);
5550 ns_send_appdefined (result);
5560 /* ==========================================================================
5564 ========================================================================== */
5566 /* called from system: queue for next pass through event loop */
5567 - (void)requestService: (NSPasteboard *)pboard
5568 userData: (NSString *)userData
5569 error: (NSString **)error
5571 [ns_pending_service_names addObject: userData];
5572 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
5573 SSDATA (ns_string_from_pasteboard (pboard))]];
5577 /* called from ns_read_socket to clear queue */
5578 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
5580 struct frame *emacsframe = SELECTED_FRAME ();
5581 NSEvent *theEvent = [NSApp currentEvent];
5583 NSTRACE ("[EmacsApp fulfillService:withArg:]");
5588 emacs_event->kind = NS_NONKEY_EVENT;
5589 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
5590 ns_input_spi_name = build_string ([name UTF8String]);
5591 ns_input_spi_arg = build_string ([arg UTF8String]);
5592 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5593 EV_TRAILER (theEvent);
5603 /* ==========================================================================
5605 EmacsView implementation
5607 ========================================================================== */
5610 @implementation EmacsView
5612 /* needed to inform when window closed from LISP */
5613 - (void) setWindowClosing: (BOOL)closing
5615 NSTRACE ("[EmacsView setWindowClosing:%d]", closing);
5617 windowClosing = closing;
5623 NSTRACE ("[EmacsView dealloc]");
5625 if (fs_state == FULLSCREEN_BOTH)
5626 [nonfs_window release];
5631 /* called on font panel selection */
5632 - (void)changeFont: (id)sender
5634 NSEvent *e = [[self window] currentEvent];
5635 struct face *face = FACE_FROM_ID (emacsframe, DEFAULT_FACE_ID);
5636 struct font *font = face->font;
5641 NSTRACE ("[EmacsView changeFont:]");
5646 #ifdef NS_IMPL_GNUSTEP
5647 nsfont = ((struct nsfont_info *)font)->nsfont;
5649 #ifdef NS_IMPL_COCOA
5650 nsfont = (NSFont *) macfont_get_nsctfont (font);
5653 if ((newFont = [sender convertFont: nsfont]))
5655 SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
5657 emacs_event->kind = NS_NONKEY_EVENT;
5658 emacs_event->modifiers = 0;
5659 emacs_event->code = KEY_NS_CHANGE_FONT;
5661 size = [newFont pointSize];
5662 ns_input_fontsize = make_number (lrint (size));
5663 ns_input_font = build_string ([[newFont familyName] UTF8String]);
5669 - (BOOL)acceptsFirstResponder
5671 NSTRACE ("[EmacsView acceptsFirstResponder]");
5676 - (void)resetCursorRects
5678 NSRect visible = [self visibleRect];
5679 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
5680 NSTRACE ("[EmacsView resetCursorRects]");
5682 if (currentCursor == nil)
5683 currentCursor = [NSCursor arrowCursor];
5685 if (!NSIsEmptyRect (visible))
5686 [self addCursorRect: visible cursor: currentCursor];
5687 [currentCursor setOnMouseEntered: YES];
5692 /*****************************************************************************/
5693 /* Keyboard handling. */
5696 - (void)keyDown: (NSEvent *)theEvent
5698 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5700 unsigned fnKeysym = 0;
5701 static NSMutableArray *nsEvArray;
5703 unsigned int flags = [theEvent modifierFlags];
5705 NSTRACE ("[EmacsView keyDown:]");
5707 /* Rhapsody and macOS give up and down events for the arrow keys */
5708 if (ns_fake_keydown == YES)
5709 ns_fake_keydown = NO;
5710 else if ([theEvent type] != NSEventTypeKeyDown)
5716 if (![[self window] isKeyWindow]
5717 && [[theEvent window] isKindOfClass: [EmacsWindow class]]
5718 /* we must avoid an infinite loop here. */
5719 && (EmacsView *)[[theEvent window] delegate] != self)
5721 /* XXX: There is an occasional condition in which, when Emacs display
5722 updates a different frame from the current one, and temporarily
5723 selects it, then processes some interrupt-driven input
5724 (dispnew.c:3878), OS will send the event to the correct NSWindow, but
5725 for some reason that window has its first responder set to the NSView
5726 most recently updated (I guess), which is not the correct one. */
5727 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
5731 if (nsEvArray == nil)
5732 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
5734 [NSCursor setHiddenUntilMouseMoves: YES];
5736 if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
5738 clear_mouse_face (hlinfo);
5739 hlinfo->mouse_face_hidden = 1;
5742 if (!processingCompose)
5744 /* When using screen sharing, no left or right information is sent,
5745 so use Left key in those cases. */
5746 int is_left_key, is_right_key;
5748 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
5749 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
5751 /* (Carbon way: [theEvent keyCode]) */
5753 /* is it a "function key"? */
5754 /* Note: Sometimes a plain key will have the NSEventModifierFlagNumericPad
5755 flag set (this is probably a bug in the OS).
5757 if (code < 0x00ff && (flags&NSEventModifierFlagNumericPad))
5759 fnKeysym = ns_convert_key ([theEvent keyCode] | NSEventModifierFlagNumericPad);
5763 fnKeysym = ns_convert_key (code);
5768 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
5769 because Emacs treats Delete and KP-Delete same (in simple.el). */
5770 if ((fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
5771 #ifdef NS_IMPL_GNUSTEP
5772 /* GNUstep uses incompatible keycodes, even for those that are
5773 supposed to be hardware independent. Just check for delete.
5774 Keypad delete does not have keysym 0xFFFF.
5775 See http://savannah.gnu.org/bugs/?25395
5777 || (fnKeysym == 0xFFFF && code == 127)
5780 code = 0xFF08; /* backspace */
5785 /* are there modifiers? */
5786 emacs_event->modifiers = 0;
5788 if (flags & NSEventModifierFlagHelp)
5789 emacs_event->modifiers |= hyper_modifier;
5791 if (flags & NSEventModifierFlagShift)
5792 emacs_event->modifiers |= shift_modifier;
5794 is_right_key = (flags & NSRightCommandKeyMask) == NSRightCommandKeyMask;
5795 is_left_key = (flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask
5796 || (! is_right_key && (flags & NSEventModifierFlagCommand) == NSEventModifierFlagCommand);
5799 emacs_event->modifiers |= parse_solitary_modifier
5800 (EQ (ns_right_command_modifier, Qleft)
5801 ? ns_command_modifier
5802 : ns_right_command_modifier);
5806 emacs_event->modifiers |= parse_solitary_modifier
5807 (ns_command_modifier);
5809 /* if super (default), take input manager's word so things like
5810 dvorak / qwerty layout work */
5811 if (EQ (ns_command_modifier, Qsuper)
5813 && [[theEvent characters] length] != 0)
5815 /* XXX: the code we get will be unshifted, so if we have
5816 a shift modifier, must convert ourselves */
5817 if (!(flags & NSEventModifierFlagShift))
5818 code = [[theEvent characters] characterAtIndex: 0];
5820 /* this is ugly and also requires linking w/Carbon framework
5821 (for LMGetKbdType) so for now leave this rare (?) case
5822 undealt with.. in future look into CGEvent methods */
5825 long smv = GetScriptManagerVariable (smKeyScript);
5826 Handle uchrHandle = GetResource
5827 ('uchr', GetScriptVariable (smv, smScriptKeys));
5829 UCKeyTranslate ((UCKeyboardLayout *) *uchrHandle,
5830 [[theEvent characters] characterAtIndex: 0],
5831 kUCKeyActionDisplay,
5832 (flags & ~NSEventModifierFlagCommand) >> 8,
5833 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
5834 &dummy, 1, &dummy, &code);
5841 is_right_key = (flags & NSRightControlKeyMask) == NSRightControlKeyMask;
5842 is_left_key = (flags & NSLeftControlKeyMask) == NSLeftControlKeyMask
5843 || (! is_right_key && (flags & NSEventModifierFlagControl) == NSEventModifierFlagControl);
5846 emacs_event->modifiers |= parse_solitary_modifier
5847 (EQ (ns_right_control_modifier, Qleft)
5848 ? ns_control_modifier
5849 : ns_right_control_modifier);
5852 emacs_event->modifiers |= parse_solitary_modifier
5853 (ns_control_modifier);
5855 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
5856 emacs_event->modifiers |=
5857 parse_solitary_modifier (ns_function_modifier);
5859 left_is_none = NILP (ns_alternate_modifier)
5860 || EQ (ns_alternate_modifier, Qnone);
5862 is_right_key = (flags & NSRightAlternateKeyMask)
5863 == NSRightAlternateKeyMask;
5864 is_left_key = (flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask
5866 && (flags & NSEventModifierFlagOption) == NSEventModifierFlagOption);
5870 if ((NILP (ns_right_alternate_modifier)
5871 || EQ (ns_right_alternate_modifier, Qnone)
5872 || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
5874 { /* accept pre-interp alt comb */
5875 if ([[theEvent characters] length] > 0)
5876 code = [[theEvent characters] characterAtIndex: 0];
5877 /*HACK: clear lone shift modifier to stop next if from firing */
5878 if (emacs_event->modifiers == shift_modifier)
5879 emacs_event->modifiers = 0;
5882 emacs_event->modifiers |= parse_solitary_modifier
5883 (EQ (ns_right_alternate_modifier, Qleft)
5884 ? ns_alternate_modifier
5885 : ns_right_alternate_modifier);
5888 if (is_left_key) /* default = meta */
5890 if (left_is_none && !fnKeysym)
5891 { /* accept pre-interp alt comb */
5892 if ([[theEvent characters] length] > 0)
5893 code = [[theEvent characters] characterAtIndex: 0];
5894 /*HACK: clear lone shift modifier to stop next if from firing */
5895 if (emacs_event->modifiers == shift_modifier)
5896 emacs_event->modifiers = 0;
5899 emacs_event->modifiers |=
5900 parse_solitary_modifier (ns_alternate_modifier);
5904 fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
5905 (unsigned) code, fnKeysym, flags, emacs_event->modifiers);
5907 /* if it was a function key or had modifiers, pass it directly to emacs */
5908 if (fnKeysym || (emacs_event->modifiers
5909 && (emacs_event->modifiers != shift_modifier)
5910 && [[theEvent charactersIgnoringModifiers] length] > 0))
5911 /*[[theEvent characters] length] */
5913 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5915 code |= (1<<28)|(3<<16);
5916 else if (code == 0x7f)
5917 code |= (1<<28)|(3<<16);
5919 emacs_event->kind = code > 0xFF
5920 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5922 emacs_event->code = code;
5923 EV_TRAILER (theEvent);
5924 processingCompose = NO;
5930 if (NS_KEYLOG && !processingCompose)
5931 fprintf (stderr, "keyDown: Begin compose sequence.\n");
5933 processingCompose = YES;
5934 [nsEvArray addObject: theEvent];
5935 [self interpretKeyEvents: nsEvArray];
5936 [nsEvArray removeObject: theEvent];
5940 #ifdef NS_IMPL_COCOA
5941 /* Needed to pick up Ctrl-tab and possibly other events that Mac OS X
5942 decided not to send key-down for.
5943 See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
5944 This only applies on Tiger and earlier.
5945 If it matches one of these, send it on to keyDown. */
5946 -(void)keyUp: (NSEvent *)theEvent
5948 int flags = [theEvent modifierFlags];
5949 int code = [theEvent keyCode];
5951 NSTRACE ("[EmacsView keyUp:]");
5953 if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
5954 code == 0x30 && (flags & NSEventModifierFlagControl) && !(flags & NSEventModifierFlagCommand))
5957 fprintf (stderr, "keyUp: passed test");
5958 ns_fake_keydown = YES;
5959 [self keyDown: theEvent];
5965 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
5968 /* <NSTextInput>: called when done composing;
5969 NOTE: also called when we delete over working text, followed immed.
5970 by doCommandBySelector: deleteBackward: */
5971 - (void)insertText: (id)aString
5974 int len = [(NSString *)aString length];
5977 NSTRACE ("[EmacsView insertText:]");
5980 NSLog (@"insertText '%@'\tlen = %d", aString, len);
5981 processingCompose = NO;
5986 /* first, clear any working text */
5987 if (workingText != nil)
5988 [self deleteWorkingText];
5990 /* now insert the string as keystrokes */
5991 for (i =0; i<len; i++)
5993 code = [aString characterAtIndex: i];
5994 /* TODO: still need this? */
5996 code = '~'; /* 0x7E */
5997 if (code != 32) /* Space */
5998 emacs_event->modifiers = 0;
6000 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
6001 emacs_event->code = code;
6002 EV_TRAILER ((id)nil);
6007 /* <NSTextInput>: inserts display of composing characters */
6008 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
6010 NSString *str = [aString respondsToSelector: @selector (string)] ?
6011 [aString string] : aString;
6013 NSTRACE ("[EmacsView setMarkedText:selectedRange:]");
6016 NSLog (@"setMarkedText '%@' len =%lu range %lu from %lu",
6017 str, (unsigned long)[str length],
6018 (unsigned long)selRange.length,
6019 (unsigned long)selRange.location);
6021 if (workingText != nil)
6022 [self deleteWorkingText];
6023 if ([str length] == 0)
6029 processingCompose = YES;
6030 workingText = [str copy];
6031 ns_working_text = build_string ([workingText UTF8String]);
6033 emacs_event->kind = NS_TEXT_EVENT;
6034 emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
6035 EV_TRAILER ((id)nil);
6039 /* delete display of composing characters [not in <NSTextInput>] */
6040 - (void)deleteWorkingText
6042 NSTRACE ("[EmacsView deleteWorkingText]");
6044 if (workingText == nil)
6047 NSLog(@"deleteWorkingText len =%lu\n", (unsigned long)[workingText length]);
6048 [workingText release];
6050 processingCompose = NO;
6055 emacs_event->kind = NS_TEXT_EVENT;
6056 emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
6057 EV_TRAILER ((id)nil);
6061 - (BOOL)hasMarkedText
6063 NSTRACE ("[EmacsView hasMarkedText]");
6065 return workingText != nil;
6069 - (NSRange)markedRange
6071 NSTRACE ("[EmacsView markedRange]");
6073 NSRange rng = workingText != nil
6074 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
6076 NSLog (@"markedRange request");
6083 NSTRACE ("[EmacsView unmarkText]");
6086 NSLog (@"unmark (accept) text");
6087 [self deleteWorkingText];
6088 processingCompose = NO;
6092 /* used to position char selection windows, etc. */
6093 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
6097 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
6099 NSTRACE ("[EmacsView firstRectForCharacterRange:]");
6102 NSLog (@"firstRectForCharRange request");
6104 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
6105 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
6106 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
6107 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
6108 +FRAME_LINE_HEIGHT (emacsframe));
6110 pt = [self convertPoint: pt toView: nil];
6111 #if !defined (NS_IMPL_COCOA) || \
6112 MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
6113 pt = [[self window] convertBaseToScreen: pt];
6117 rect = [[self window] convertRectToScreen: rect];
6123 - (NSInteger)conversationIdentifier
6125 return (NSInteger)self;
6129 - (void)doCommandBySelector: (SEL)aSelector
6131 NSTRACE ("[EmacsView doCommandBySelector:]");
6134 NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
6136 processingCompose = NO;
6137 if (aSelector == @selector (deleteBackward:))
6139 /* happens when user backspaces over an ongoing composition:
6140 throw a 'delete' into the event queue */
6143 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
6144 emacs_event->code = 0xFF08;
6145 EV_TRAILER ((id)nil);
6149 - (NSArray *)validAttributesForMarkedText
6151 static NSArray *arr = nil;
6152 if (arr == nil) arr = [NSArray new];
6153 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
6157 - (NSRange)selectedRange
6160 NSLog (@"selectedRange request");
6161 return NSMakeRange (NSNotFound, 0);
6164 #if defined (NS_IMPL_COCOA) || GNUSTEP_GUI_MAJOR_VERSION > 0 || \
6165 GNUSTEP_GUI_MINOR_VERSION > 22
6166 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
6168 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
6172 NSLog (@"characterIndexForPoint request");
6176 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
6178 static NSAttributedString *str = nil;
6179 if (str == nil) str = [NSAttributedString new];
6181 NSLog (@"attributedSubstringFromRange request");
6185 /* End <NSTextInput> impl. */
6186 /*****************************************************************************/
6189 /* This is what happens when the user presses a mouse button. */
6190 - (void)mouseDown: (NSEvent *)theEvent
6192 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6193 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
6195 NSTRACE ("[EmacsView mouseDown:]");
6197 [self deleteWorkingText];
6202 dpyinfo->last_mouse_frame = emacsframe;
6203 /* appears to be needed to prevent spurious movement events generated on
6205 emacsframe->mouse_moved = 0;
6207 if ([theEvent type] == NSEventTypeScrollWheel)
6209 CGFloat delta = [theEvent deltaY];
6210 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
6213 delta = [theEvent deltaX];
6216 NSTRACE_MSG ("deltaIsZero");
6219 emacs_event->kind = HORIZ_WHEEL_EVENT;
6222 emacs_event->kind = WHEEL_EVENT;
6224 emacs_event->code = 0;
6225 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
6226 ((delta > 0) ? up_modifier : down_modifier);
6230 emacs_event->kind = MOUSE_CLICK_EVENT;
6231 emacs_event->code = EV_BUTTON (theEvent);
6232 emacs_event->modifiers = EV_MODIFIERS (theEvent)
6233 | EV_UDMODIFIERS (theEvent);
6235 XSETINT (emacs_event->x, lrint (p.x));
6236 XSETINT (emacs_event->y, lrint (p.y));
6237 EV_TRAILER (theEvent);
6241 - (void)rightMouseDown: (NSEvent *)theEvent
6243 NSTRACE ("[EmacsView rightMouseDown:]");
6244 [self mouseDown: theEvent];
6248 - (void)otherMouseDown: (NSEvent *)theEvent
6250 NSTRACE ("[EmacsView otherMouseDown:]");
6251 [self mouseDown: theEvent];
6255 - (void)mouseUp: (NSEvent *)theEvent
6257 NSTRACE ("[EmacsView mouseUp:]");
6258 [self mouseDown: theEvent];
6262 - (void)rightMouseUp: (NSEvent *)theEvent
6264 NSTRACE ("[EmacsView rightMouseUp:]");
6265 [self mouseDown: theEvent];
6269 - (void)otherMouseUp: (NSEvent *)theEvent
6271 NSTRACE ("[EmacsView otherMouseUp:]");
6272 [self mouseDown: theEvent];
6276 - (void) scrollWheel: (NSEvent *)theEvent
6278 NSTRACE ("[EmacsView scrollWheel:]");
6279 [self mouseDown: theEvent];
6283 /* Tell emacs the mouse has moved. */
6284 - (void)mouseMoved: (NSEvent *)e
6286 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
6287 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6291 NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "[EmacsView mouseMoved:]");
6293 dpyinfo->last_mouse_movement_time = EV_TIMESTAMP (e);
6294 pt = [self convertPoint: [e locationInWindow] fromView: nil];
6295 dpyinfo->last_mouse_motion_x = pt.x;
6296 dpyinfo->last_mouse_motion_y = pt.y;
6298 /* update any mouse face */
6299 if (hlinfo->mouse_face_hidden)
6301 hlinfo->mouse_face_hidden = 0;
6302 clear_mouse_face (hlinfo);
6305 /* tooltip handling */
6306 previous_help_echo_string = help_echo_string;
6307 help_echo_string = Qnil;
6309 if (!NILP (Vmouse_autoselect_window))
6311 NSTRACE_MSG ("mouse_autoselect_window");
6312 static Lisp_Object last_mouse_window;
6314 = window_from_coordinates (emacsframe, pt.x, pt.y, 0, 0);
6316 if (WINDOWP (window)
6317 && !EQ (window, last_mouse_window)
6318 && !EQ (window, selected_window)
6319 && (focus_follows_mouse
6320 || (EQ (XWINDOW (window)->frame,
6321 XWINDOW (selected_window)->frame))))
6323 NSTRACE_MSG ("in_window");
6324 emacs_event->kind = SELECT_WINDOW_EVENT;
6325 emacs_event->frame_or_window = window;
6328 /* Remember the last window where we saw the mouse. */
6329 last_mouse_window = window;
6332 if (!note_mouse_movement (emacsframe, pt.x, pt.y))
6333 help_echo_string = previous_help_echo_string;
6335 XSETFRAME (frame, emacsframe);
6336 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
6338 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
6339 (note_mouse_highlight), which is called through the
6340 note_mouse_movement () call above */
6341 any_help_event_p = YES;
6342 gen_help_event (help_echo_string, frame, help_echo_window,
6343 help_echo_object, help_echo_pos);
6346 if (emacsframe->mouse_moved && send_appdefined)
6347 ns_send_appdefined (-1);
6351 - (void)mouseDragged: (NSEvent *)e
6353 NSTRACE ("[EmacsView mouseDragged:]");
6354 [self mouseMoved: e];
6358 - (void)rightMouseDragged: (NSEvent *)e
6360 NSTRACE ("[EmacsView rightMouseDragged:]");
6361 [self mouseMoved: e];
6365 - (void)otherMouseDragged: (NSEvent *)e
6367 NSTRACE ("[EmacsView otherMouseDragged:]");
6368 [self mouseMoved: e];
6372 - (BOOL)windowShouldClose: (id)sender
6374 NSEvent *e =[[self window] currentEvent];
6376 NSTRACE ("[EmacsView windowShouldClose:]");
6377 windowClosing = YES;
6380 emacs_event->kind = DELETE_WINDOW_EVENT;
6381 emacs_event->modifiers = 0;
6382 emacs_event->code = 0;
6384 /* Don't close this window, let this be done from lisp code. */
6388 - (void) updateFrameSize: (BOOL) delay;
6390 NSWindow *window = [self window];
6391 NSRect wr = [window frame];
6393 int oldc = cols, oldr = rows;
6394 int oldw = FRAME_PIXEL_WIDTH (emacsframe);
6395 int oldh = FRAME_PIXEL_HEIGHT (emacsframe);
6398 NSTRACE ("[EmacsView updateFrameSize:]");
6399 NSTRACE_SIZE ("Original size", NSMakeSize (oldw, oldh));
6400 NSTRACE_RECT ("Original frame", wr);
6401 NSTRACE_MSG ("Original columns: %d", cols);
6402 NSTRACE_MSG ("Original rows: %d", rows);
6404 if (! [self isFullscreen])
6406 #ifdef NS_IMPL_GNUSTEP
6407 // GNUstep does not always update the tool bar height. Force it.
6408 if (toolbar && [toolbar isVisible])
6409 update_frame_tool_bar (emacsframe);
6412 extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6413 + FRAME_TOOLBAR_HEIGHT (emacsframe);
6416 if (wait_for_tool_bar)
6418 if (FRAME_TOOLBAR_HEIGHT (emacsframe) == 0)
6420 NSTRACE_MSG ("Waiting for toolbar");
6423 wait_for_tool_bar = NO;
6426 neww = (int)wr.size.width - emacsframe->border_width;
6427 newh = (int)wr.size.height - extra;
6429 NSTRACE_SIZE ("New size", NSMakeSize (neww, newh));
6430 NSTRACE_MSG ("tool_bar_height: %d", emacsframe->tool_bar_height);
6432 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, neww);
6433 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, newh);
6435 if (cols < MINWIDTH)
6438 if (rows < MINHEIGHT)
6441 NSTRACE_MSG ("New columns: %d", cols);
6442 NSTRACE_MSG ("New rows: %d", rows);
6444 if (oldr != rows || oldc != cols || neww != oldw || newh != oldh)
6446 NSView *view = FRAME_NS_VIEW (emacsframe);
6448 change_frame_size (emacsframe,
6449 FRAME_PIXEL_TO_TEXT_WIDTH (emacsframe, neww),
6450 FRAME_PIXEL_TO_TEXT_HEIGHT (emacsframe, newh),
6452 SET_FRAME_GARBAGED (emacsframe);
6453 cancel_mouse_face (emacsframe);
6455 wr = NSMakeRect (0, 0, neww, newh);
6457 [view setFrame: wr];
6459 // to do: consider using [NSNotificationCenter postNotificationName:].
6460 [self windowDidMove: // Update top/left.
6461 [NSNotification notificationWithName:NSWindowDidMoveNotification
6462 object:[view window]]];
6466 NSTRACE_MSG ("No change");
6470 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
6471 /* normalize frame to gridded text size */
6475 NSTRACE ("[EmacsView windowWillResize:toSize: " NSTRACE_FMT_SIZE "]",
6476 NSTRACE_ARG_SIZE (frameSize));
6477 NSTRACE_RECT ("[sender frame]", [sender frame]);
6478 NSTRACE_FSTYPE ("fs_state", fs_state);
6480 if (fs_state == FULLSCREEN_MAXIMIZED
6481 && (maximized_width != (int)frameSize.width
6482 || maximized_height != (int)frameSize.height))
6483 [self setFSValue: FULLSCREEN_NONE];
6484 else if (fs_state == FULLSCREEN_WIDTH
6485 && maximized_width != (int)frameSize.width)
6486 [self setFSValue: FULLSCREEN_NONE];
6487 else if (fs_state == FULLSCREEN_HEIGHT
6488 && maximized_height != (int)frameSize.height)
6489 [self setFSValue: FULLSCREEN_NONE];
6491 if (fs_state == FULLSCREEN_NONE)
6492 maximized_width = maximized_height = -1;
6494 if (! [self isFullscreen])
6496 extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6497 + FRAME_TOOLBAR_HEIGHT (emacsframe);
6500 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, frameSize.width);
6501 if (cols < MINWIDTH)
6504 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe,
6505 frameSize.height - extra);
6506 if (rows < MINHEIGHT)
6508 #ifdef NS_IMPL_COCOA
6510 /* this sets window title to have size in it; the wm does this under GS */
6511 NSRect r = [[self window] frame];
6512 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
6520 else if (fs_state == FULLSCREEN_NONE && ! maximizing_resize)
6523 NSWindow *window = [self window];
6526 char *t = strdup ([[[self window] title] UTF8String]);
6527 char *pos = strstr (t, " — ");
6532 size_title = xmalloc (strlen (old_title) + 40);
6533 esprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
6534 [window setTitle: [NSString stringWithUTF8String: size_title]];
6539 #endif /* NS_IMPL_COCOA */
6541 NSTRACE_MSG ("cols: %d rows: %d", cols, rows);
6543 /* Restrict the new size to the text gird.
6545 Don't restrict the width if the user only adjusted the height, and
6546 vice versa. (Without this, the frame would shrink, and move
6547 slightly, if the window was resized by dragging one of its
6549 if (!frame_resize_pixelwise)
6551 NSRect r = [[self window] frame];
6553 if (r.size.width != frameSize.width)
6556 FRAME_TEXT_COLS_TO_PIXEL_WIDTH (emacsframe, cols);
6559 if (r.size.height != frameSize.height)
6562 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows) + extra;
6566 NSTRACE_RETURN_SIZE (frameSize);
6572 - (void)windowDidResize: (NSNotification *)notification
6574 NSTRACE ("[EmacsView windowDidResize:]");
6575 if (!FRAME_LIVE_P (emacsframe))
6577 NSTRACE_MSG ("Ignored (frame dead)");
6580 if (emacsframe->output_data.ns->in_animation)
6582 NSTRACE_MSG ("Ignored (in animation)");
6586 if (! [self fsIsNative])
6588 NSWindow *theWindow = [notification object];
6589 /* We can get notification on the non-FS window when in
6591 if ([self window] != theWindow) return;
6594 NSTRACE_RECT ("frame", [[notification object] frame]);
6596 #ifdef NS_IMPL_GNUSTEP
6597 NSWindow *theWindow = [notification object];
6599 /* In GNUstep, at least currently, it's possible to get a didResize
6600 without getting a willResize.. therefore we need to act as if we got
6601 the willResize now */
6602 NSSize sz = [theWindow frame].size;
6603 sz = [self windowWillResize: theWindow toSize: sz];
6604 #endif /* NS_IMPL_GNUSTEP */
6606 if (cols > 0 && rows > 0)
6608 [self updateFrameSize: YES];
6611 ns_send_appdefined (-1);
6614 #ifdef NS_IMPL_COCOA
6615 - (void)viewDidEndLiveResize
6617 NSTRACE ("[EmacsView viewDidEndLiveResize]");
6619 [super viewDidEndLiveResize];
6622 [[self window] setTitle: [NSString stringWithUTF8String: old_title]];
6626 maximizing_resize = NO;
6628 #endif /* NS_IMPL_COCOA */
6631 - (void)windowDidBecomeKey: (NSNotification *)notification
6632 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6634 [self windowDidBecomeKey];
6638 - (void)windowDidBecomeKey /* for direct calls */
6640 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6641 struct frame *old_focus = dpyinfo->x_focus_frame;
6643 NSTRACE ("[EmacsView windowDidBecomeKey]");
6645 if (emacsframe != old_focus)
6646 dpyinfo->x_focus_frame = emacsframe;
6648 ns_frame_rehighlight (emacsframe);
6652 emacs_event->kind = FOCUS_IN_EVENT;
6653 EV_TRAILER ((id)nil);
6658 - (void)windowDidResignKey: (NSNotification *)notification
6659 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6661 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6662 BOOL is_focus_frame = dpyinfo->x_focus_frame == emacsframe;
6663 NSTRACE ("[EmacsView windowDidResignKey:]");
6666 dpyinfo->x_focus_frame = 0;
6668 emacsframe->mouse_moved = 0;
6669 ns_frame_rehighlight (emacsframe);
6671 /* FIXME: for some reason needed on second and subsequent clicks away
6672 from sole-frame Emacs to get hollow box to show */
6673 if (!windowClosing && [[self window] isVisible] == YES)
6675 x_update_cursor (emacsframe, 1);
6676 x_set_frame_alpha (emacsframe);
6679 if (any_help_event_p)
6682 XSETFRAME (frame, emacsframe);
6683 help_echo_string = Qnil;
6684 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
6687 if (emacs_event && is_focus_frame)
6689 [self deleteWorkingText];
6690 emacs_event->kind = FOCUS_OUT_EVENT;
6691 EV_TRAILER ((id)nil);
6696 - (void)windowWillMiniaturize: sender
6698 NSTRACE ("[EmacsView windowWillMiniaturize:]");
6702 - (void)setFrame:(NSRect)frameRect;
6704 NSTRACE ("[EmacsView setFrame:" NSTRACE_FMT_RECT "]",
6705 NSTRACE_ARG_RECT (frameRect));
6707 [super setFrame:(NSRect)frameRect];
6723 - initFrameFromEmacs: (struct frame *)f
6731 NSTRACE ("[EmacsView initFrameFromEmacs:]");
6732 NSTRACE_MSG ("cols:%d lines:%d", f->text_cols, f->text_lines);
6735 processingCompose = NO;
6736 scrollbarsNeedingUpdate = 0;
6737 fs_state = FULLSCREEN_NONE;
6738 fs_before_fs = next_maximized = -1;
6739 #ifdef HAVE_NATIVE_FS
6740 fs_is_native = ns_use_native_fullscreen;
6744 maximized_width = maximized_height = -1;
6747 ns_userRect = NSMakeRect (0, 0, 0, 0);
6748 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
6749 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
6750 [self initWithFrame: r];
6751 [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
6753 FRAME_NS_VIEW (f) = self;
6755 #ifdef NS_IMPL_COCOA
6757 maximizing_resize = NO;
6760 win = [[EmacsWindow alloc]
6761 initWithContentRect: r
6762 styleMask: (NSWindowStyleMaskResizable |
6763 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6764 NSWindowStyleMaskTitled |
6766 NSWindowStyleMaskMiniaturizable |
6767 NSWindowStyleMaskClosable)
6768 backing: NSBackingStoreBuffered
6771 #ifdef HAVE_NATIVE_FS
6772 [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
6776 bwidth = f->border_width = wr.size.width - r.size.width;
6777 tibar_height = FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
6779 [win setAcceptsMouseMovedEvents: YES];
6780 [win setDelegate: self];
6781 #if !defined (NS_IMPL_COCOA) || \
6782 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6783 [win useOptimizedDrawing: YES];
6786 [[win contentView] addSubview: self];
6789 [self registerForDraggedTypes: ns_drag_types];
6792 name = [NSString stringWithUTF8String:
6793 NILP (tem) ? "Emacs" : SSDATA (tem)];
6794 [win setTitle: name];
6796 /* toolbar support */
6797 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
6798 [NSString stringWithFormat: @"Emacs Frame %d",
6800 [win setToolbar: toolbar];
6801 [toolbar setVisible: NO];
6803 /* Don't set frame garbaged until tool bar is up to date?
6804 This avoids an extra clear and redraw (flicker) at frame creation. */
6805 if (FRAME_EXTERNAL_TOOL_BAR (f)) wait_for_tool_bar = YES;
6806 else wait_for_tool_bar = NO;
6809 #ifdef NS_IMPL_COCOA
6811 NSButton *toggleButton;
6812 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
6813 [toggleButton setTarget: self];
6814 [toggleButton setAction: @selector (toggleToolbar: )];
6817 FRAME_TOOLBAR_HEIGHT (f) = 0;
6821 [win setMiniwindowTitle:
6822 [NSString stringWithUTF8String: SSDATA (tem)]];
6825 NSScreen *screen = [win screen];
6829 NSPoint pt = NSMakePoint
6830 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
6831 IN_BOUND (-SCREENMAX,
6832 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX));
6834 [win setFrameTopLeftPoint: pt];
6836 NSTRACE_RECT ("new frame", [win frame]);
6840 [win makeFirstResponder: self];
6842 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6843 (FACE_FROM_ID (emacsframe, DEFAULT_FACE_ID)),
6845 [win setBackgroundColor: col];
6846 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6847 [win setOpaque: NO];
6849 #if !defined (NS_IMPL_COCOA) || \
6850 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6851 [self allocateGState];
6853 [NSApp registerServicesMenuSendTypes: ns_send_types
6861 - (void)windowDidMove: sender
6863 NSWindow *win = [self window];
6864 NSRect r = [win frame];
6865 NSArray *screens = [NSScreen screens];
6866 NSScreen *screen = [screens objectAtIndex: 0];
6868 NSTRACE ("[EmacsView windowDidMove:]");
6870 if (!emacsframe->output_data.ns)
6874 emacsframe->left_pos = r.origin.x;
6875 emacsframe->top_pos =
6876 [screen frame].size.height - (r.origin.y + r.size.height);
6881 /* Called AFTER method below, but before our windowWillResize call there leads
6882 to windowDidResize -> x_set_window_size. Update emacs' notion of frame
6883 location so set_window_size moves the frame. */
6884 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
6886 NSTRACE (("[EmacsView windowShouldZoom:toFrame:" NSTRACE_FMT_RECT "]"
6887 NSTRACE_FMT_RETURN "YES"),
6888 NSTRACE_ARG_RECT (newFrame));
6890 emacsframe->output_data.ns->zooming = 1;
6895 /* Override to do something slightly nonstandard, but nice. First click on
6896 zoom button will zoom vertically. Second will zoom completely. Third
6897 returns to original. */
6898 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
6899 defaultFrame:(NSRect)defaultFrame
6901 // TODO: Rename to "currentFrame" and assign "result" properly in
6903 NSRect result = [sender frame];
6905 NSTRACE (("[EmacsView windowWillUseStandardFrame:defaultFrame:"
6906 NSTRACE_FMT_RECT "]"),
6907 NSTRACE_ARG_RECT (defaultFrame));
6908 NSTRACE_FSTYPE ("fs_state", fs_state);
6909 NSTRACE_FSTYPE ("fs_before_fs", fs_before_fs);
6910 NSTRACE_FSTYPE ("next_maximized", next_maximized);
6911 NSTRACE_RECT ("ns_userRect", ns_userRect);
6912 NSTRACE_RECT ("[sender frame]", [sender frame]);
6914 if (fs_before_fs != -1) /* Entering fullscreen */
6916 NSTRACE_MSG ("Entering fullscreen");
6917 result = defaultFrame;
6921 // Save the window size and position (frame) before the resize.
6922 if (fs_state != FULLSCREEN_MAXIMIZED
6923 && fs_state != FULLSCREEN_WIDTH)
6925 ns_userRect.size.width = result.size.width;
6926 ns_userRect.origin.x = result.origin.x;
6929 if (fs_state != FULLSCREEN_MAXIMIZED
6930 && fs_state != FULLSCREEN_HEIGHT)
6932 ns_userRect.size.height = result.size.height;
6933 ns_userRect.origin.y = result.origin.y;
6936 NSTRACE_RECT ("ns_userRect (2)", ns_userRect);
6938 if (next_maximized == FULLSCREEN_HEIGHT
6939 || (next_maximized == -1
6940 && abs ((int)(defaultFrame.size.height - result.size.height))
6941 > FRAME_LINE_HEIGHT (emacsframe)))
6944 NSTRACE_MSG ("FULLSCREEN_HEIGHT");
6945 maximized_height = result.size.height = defaultFrame.size.height;
6946 maximized_width = -1;
6947 result.origin.y = defaultFrame.origin.y;
6948 if (ns_userRect.size.height != 0)
6950 result.origin.x = ns_userRect.origin.x;
6951 result.size.width = ns_userRect.size.width;
6953 [self setFSValue: FULLSCREEN_HEIGHT];
6954 #ifdef NS_IMPL_COCOA
6955 maximizing_resize = YES;
6958 else if (next_maximized == FULLSCREEN_WIDTH)
6960 NSTRACE_MSG ("FULLSCREEN_WIDTH");
6961 maximized_width = result.size.width = defaultFrame.size.width;
6962 maximized_height = -1;
6963 result.origin.x = defaultFrame.origin.x;
6964 if (ns_userRect.size.width != 0)
6966 result.origin.y = ns_userRect.origin.y;
6967 result.size.height = ns_userRect.size.height;
6969 [self setFSValue: FULLSCREEN_WIDTH];
6971 else if (next_maximized == FULLSCREEN_MAXIMIZED
6972 || (next_maximized == -1
6973 && abs ((int)(defaultFrame.size.width - result.size.width))
6974 > FRAME_COLUMN_WIDTH (emacsframe)))
6976 NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
6978 result = defaultFrame; /* second click */
6979 maximized_width = result.size.width;
6980 maximized_height = result.size.height;
6981 [self setFSValue: FULLSCREEN_MAXIMIZED];
6982 #ifdef NS_IMPL_COCOA
6983 maximizing_resize = YES;
6989 NSTRACE_MSG ("Restore");
6990 result = ns_userRect.size.height ? ns_userRect : result;
6991 NSTRACE_RECT ("restore (2)", result);
6992 ns_userRect = NSMakeRect (0, 0, 0, 0);
6993 #ifdef NS_IMPL_COCOA
6994 maximizing_resize = fs_state != FULLSCREEN_NONE;
6996 [self setFSValue: FULLSCREEN_NONE];
6997 maximized_width = maximized_height = -1;
7001 if (fs_before_fs == -1) next_maximized = -1;
7003 NSTRACE_RECT ("Final ns_userRect", ns_userRect);
7004 NSTRACE_MSG ("Final maximized_width: %d", maximized_width);
7005 NSTRACE_MSG ("Final maximized_height: %d", maximized_height);
7006 NSTRACE_FSTYPE ("Final next_maximized", next_maximized);
7008 [self windowWillResize: sender toSize: result.size];
7010 NSTRACE_RETURN_RECT (result);
7016 - (void)windowDidDeminiaturize: sender
7018 NSTRACE ("[EmacsView windowDidDeminiaturize:]");
7019 if (!emacsframe->output_data.ns)
7022 SET_FRAME_ICONIFIED (emacsframe, 0);
7023 SET_FRAME_VISIBLE (emacsframe, 1);
7024 windows_or_buffers_changed = 63;
7028 emacs_event->kind = DEICONIFY_EVENT;
7029 EV_TRAILER ((id)nil);
7034 - (void)windowDidExpose: sender
7036 NSTRACE ("[EmacsView windowDidExpose:]");
7037 if (!emacsframe->output_data.ns)
7040 SET_FRAME_VISIBLE (emacsframe, 1);
7041 SET_FRAME_GARBAGED (emacsframe);
7043 if (send_appdefined)
7044 ns_send_appdefined (-1);
7048 - (void)windowDidMiniaturize: sender
7050 NSTRACE ("[EmacsView windowDidMiniaturize:]");
7051 if (!emacsframe->output_data.ns)
7054 SET_FRAME_ICONIFIED (emacsframe, 1);
7055 SET_FRAME_VISIBLE (emacsframe, 0);
7059 emacs_event->kind = ICONIFY_EVENT;
7060 EV_TRAILER ((id)nil);
7064 #ifdef HAVE_NATIVE_FS
7065 - (NSApplicationPresentationOptions)window:(NSWindow *)window
7066 willUseFullScreenPresentationOptions:
7067 (NSApplicationPresentationOptions)proposedOptions
7069 return proposedOptions|NSApplicationPresentationAutoHideToolbar;
7073 - (void)windowWillEnterFullScreen:(NSNotification *)notification
7075 NSTRACE ("[EmacsView windowWillEnterFullScreen:]");
7076 [self windowWillEnterFullScreen];
7078 - (void)windowWillEnterFullScreen /* provided for direct calls */
7080 NSTRACE ("[EmacsView windowWillEnterFullScreen]");
7081 fs_before_fs = fs_state;
7084 - (void)windowDidEnterFullScreen:(NSNotification *)notification
7086 NSTRACE ("[EmacsView windowDidEnterFullScreen:]");
7087 [self windowDidEnterFullScreen];
7090 - (void)windowDidEnterFullScreen /* provided for direct calls */
7092 NSTRACE ("[EmacsView windowDidEnterFullScreen]");
7093 [self setFSValue: FULLSCREEN_BOTH];
7094 if (! [self fsIsNative])
7096 [self windowDidBecomeKey];
7097 [nonfs_window orderOut:self];
7101 BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (emacsframe) ? YES : NO;
7102 #ifdef NS_IMPL_COCOA
7103 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
7104 unsigned val = (unsigned)[NSApp presentationOptions];
7106 // Mac OS X 10.7 bug fix, the menu won't appear without this.
7107 // val is non-zero on other macOS versions.
7110 NSApplicationPresentationOptions options
7111 = NSApplicationPresentationAutoHideDock
7112 | NSApplicationPresentationAutoHideMenuBar
7113 | NSApplicationPresentationFullScreen
7114 | NSApplicationPresentationAutoHideToolbar;
7116 [NSApp setPresentationOptions: options];
7120 [toolbar setVisible:tbar_visible];
7124 - (void)windowWillExitFullScreen:(NSNotification *)notification
7126 NSTRACE ("[EmacsView windowWillExitFullScreen:]");
7127 [self windowWillExitFullScreen];
7130 - (void)windowWillExitFullScreen /* provided for direct calls */
7132 NSTRACE ("[EmacsView windowWillExitFullScreen]");
7133 if (!FRAME_LIVE_P (emacsframe))
7135 NSTRACE_MSG ("Ignored (frame dead)");
7138 if (next_maximized != -1)
7139 fs_before_fs = next_maximized;
7142 - (void)windowDidExitFullScreen:(NSNotification *)notification
7144 NSTRACE ("[EmacsView windowDidExitFullScreen:]");
7145 [self windowDidExitFullScreen];
7148 - (void)windowDidExitFullScreen /* provided for direct calls */
7150 NSTRACE ("[EmacsView windowDidExitFullScreen]");
7151 if (!FRAME_LIVE_P (emacsframe))
7153 NSTRACE_MSG ("Ignored (frame dead)");
7156 [self setFSValue: fs_before_fs];
7158 #ifdef HAVE_NATIVE_FS
7159 [self updateCollectionBehavior];
7161 if (FRAME_EXTERNAL_TOOL_BAR (emacsframe))
7163 [toolbar setVisible:YES];
7164 update_frame_tool_bar (emacsframe);
7165 [self updateFrameSize:YES];
7166 [[self window] display];
7169 [toolbar setVisible:NO];
7171 if (next_maximized != -1)
7172 [[self window] performZoom:self];
7177 return fs_is_native;
7180 - (BOOL)isFullscreen
7186 res = (nonfs_window != nil);
7190 #ifdef HAVE_NATIVE_FS
7191 res = (([[self window] styleMask] & NSWindowStyleMaskFullScreen) != 0);
7197 NSTRACE ("[EmacsView isFullscreen] " NSTRACE_FMT_RETURN " %d",
7203 #ifdef HAVE_NATIVE_FS
7204 - (void)updateCollectionBehavior
7206 NSTRACE ("[EmacsView updateCollectionBehavior]");
7208 if (! [self isFullscreen])
7210 NSWindow *win = [self window];
7211 NSWindowCollectionBehavior b = [win collectionBehavior];
7212 if (ns_use_native_fullscreen)
7213 b |= NSWindowCollectionBehaviorFullScreenPrimary;
7215 b &= ~NSWindowCollectionBehaviorFullScreenPrimary;
7217 [win setCollectionBehavior: b];
7218 fs_is_native = ns_use_native_fullscreen;
7223 - (void)toggleFullScreen: (id)sender
7231 NSTRACE ("[EmacsView toggleFullScreen:]");
7235 #ifdef HAVE_NATIVE_FS
7236 [[self window] toggleFullScreen:sender];
7242 onFirstScreen = [[w screen] isEqual:[[NSScreen screens] objectAtIndex:0]];
7245 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
7246 (FACE_FROM_ID (f, DEFAULT_FACE_ID)),
7249 if (fs_state != FULLSCREEN_BOTH)
7251 NSScreen *screen = [w screen];
7253 #if defined (NS_IMPL_COCOA) && \
7254 MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7255 /* Hide ghost menu bar on secondary monitor? */
7256 if (! onFirstScreen)
7257 onFirstScreen = [NSScreen screensHaveSeparateSpaces];
7259 /* Hide dock and menubar if we are on the primary screen. */
7262 #ifdef NS_IMPL_COCOA
7263 NSApplicationPresentationOptions options
7264 = NSApplicationPresentationAutoHideDock
7265 | NSApplicationPresentationAutoHideMenuBar;
7267 [NSApp setPresentationOptions: options];
7269 [NSMenu setMenuBarVisible:NO];
7273 fw = [[EmacsFSWindow alloc]
7274 initWithContentRect:[w contentRectForFrameRect:wr]
7275 styleMask:NSWindowStyleMaskBorderless
7276 backing:NSBackingStoreBuffered
7280 [fw setContentView:[w contentView]];
7281 [fw setTitle:[w title]];
7282 [fw setDelegate:self];
7283 [fw setAcceptsMouseMovedEvents: YES];
7284 #if !defined (NS_IMPL_COCOA) || \
7285 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
7286 [fw useOptimizedDrawing: YES];
7288 [fw setBackgroundColor: col];
7289 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
7292 f->border_width = 0;
7293 FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
7294 tobar_height = FRAME_TOOLBAR_HEIGHT (f);
7295 FRAME_TOOLBAR_HEIGHT (f) = 0;
7299 [self windowWillEnterFullScreen];
7300 [fw makeKeyAndOrderFront:NSApp];
7301 [fw makeFirstResponder:self];
7303 r = [fw frameRectForContentRect:[screen frame]];
7304 [fw setFrame: r display:YES animate:ns_use_fullscreen_animation];
7305 [self windowDidEnterFullScreen];
7316 #ifdef NS_IMPL_COCOA
7317 [NSApp setPresentationOptions: NSApplicationPresentationDefault];
7319 [NSMenu setMenuBarVisible:YES];
7323 [w setContentView:[fw contentView]];
7324 [w setBackgroundColor: col];
7325 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
7328 f->border_width = bwidth;
7329 FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
7330 if (FRAME_EXTERNAL_TOOL_BAR (f))
7331 FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
7333 // to do: consider using [NSNotificationCenter postNotificationName:] to send notifications.
7335 [self windowWillExitFullScreen];
7336 [fw setFrame: [w frame] display:YES animate:ns_use_fullscreen_animation];
7338 [w makeKeyAndOrderFront:NSApp];
7339 [self windowDidExitFullScreen];
7340 [self updateFrameSize:YES];
7346 NSTRACE ("[EmacsView handleFS]");
7348 if (fs_state != emacsframe->want_fullscreen)
7350 if (fs_state == FULLSCREEN_BOTH)
7352 NSTRACE_MSG ("fs_state == FULLSCREEN_BOTH");
7353 [self toggleFullScreen:self];
7356 switch (emacsframe->want_fullscreen)
7358 case FULLSCREEN_BOTH:
7359 NSTRACE_MSG ("FULLSCREEN_BOTH");
7360 [self toggleFullScreen:self];
7362 case FULLSCREEN_WIDTH:
7363 NSTRACE_MSG ("FULLSCREEN_WIDTH");
7364 next_maximized = FULLSCREEN_WIDTH;
7365 if (fs_state != FULLSCREEN_BOTH)
7366 [[self window] performZoom:self];
7368 case FULLSCREEN_HEIGHT:
7369 NSTRACE_MSG ("FULLSCREEN_HEIGHT");
7370 next_maximized = FULLSCREEN_HEIGHT;
7371 if (fs_state != FULLSCREEN_BOTH)
7372 [[self window] performZoom:self];
7374 case FULLSCREEN_MAXIMIZED:
7375 NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
7376 next_maximized = FULLSCREEN_MAXIMIZED;
7377 if (fs_state != FULLSCREEN_BOTH)
7378 [[self window] performZoom:self];
7380 case FULLSCREEN_NONE:
7381 NSTRACE_MSG ("FULLSCREEN_NONE");
7382 if (fs_state != FULLSCREEN_BOTH)
7384 next_maximized = FULLSCREEN_NONE;
7385 [[self window] performZoom:self];
7390 emacsframe->want_fullscreen = FULLSCREEN_NONE;
7395 - (void) setFSValue: (int)value
7397 NSTRACE ("[EmacsView setFSValue:" NSTRACE_FMT_FSTYPE "]",
7398 NSTRACE_ARG_FSTYPE(value));
7400 Lisp_Object lval = Qnil;
7403 case FULLSCREEN_BOTH:
7406 case FULLSCREEN_WIDTH:
7409 case FULLSCREEN_HEIGHT:
7412 case FULLSCREEN_MAXIMIZED:
7416 store_frame_param (emacsframe, Qfullscreen, lval);
7420 - (void)mouseEntered: (NSEvent *)theEvent
7422 NSTRACE ("[EmacsView mouseEntered:]");
7424 FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7425 = EV_TIMESTAMP (theEvent);
7429 - (void)mouseExited: (NSEvent *)theEvent
7431 Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
7433 NSTRACE ("[EmacsView mouseExited:]");
7438 FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7439 = EV_TIMESTAMP (theEvent);
7441 if (emacsframe == hlinfo->mouse_face_mouse_frame)
7443 clear_mouse_face (hlinfo);
7444 hlinfo->mouse_face_mouse_frame = 0;
7451 NSTRACE ("[EmacsView menuDown:]");
7452 if (context_menu_value == -1)
7453 context_menu_value = [sender tag];
7456 NSInteger tag = [sender tag];
7457 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
7458 emacsframe->menu_bar_vector,
7462 ns_send_appdefined (-1);
7467 - (EmacsToolbar *)toolbar
7473 /* this gets called on toolbar button click */
7474 - toolbarClicked: (id)item
7477 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
7479 NSTRACE ("[EmacsView toolbarClicked:]");
7484 /* send first event (for some reason two needed) */
7485 theEvent = [[self window] currentEvent];
7486 emacs_event->kind = TOOL_BAR_EVENT;
7487 XSETFRAME (emacs_event->arg, emacsframe);
7488 EV_TRAILER (theEvent);
7490 emacs_event->kind = TOOL_BAR_EVENT;
7491 /* XSETINT (emacs_event->code, 0); */
7492 emacs_event->arg = AREF (emacsframe->tool_bar_items,
7493 idx + TOOL_BAR_ITEM_KEY);
7494 emacs_event->modifiers = EV_MODIFIERS (theEvent);
7495 EV_TRAILER (theEvent);
7500 - toggleToolbar: (id)sender
7502 NSTRACE ("[EmacsView toggleToolbar:]");
7507 emacs_event->kind = NS_NONKEY_EVENT;
7508 emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
7509 EV_TRAILER ((id)nil);
7514 - (void)drawRect: (NSRect)rect
7516 int x = NSMinX (rect), y = NSMinY (rect);
7517 int width = NSWidth (rect), height = NSHeight (rect);
7519 NSTRACE ("[EmacsView drawRect:" NSTRACE_FMT_RECT "]",
7520 NSTRACE_ARG_RECT(rect));
7522 if (!emacsframe || !emacsframe->output_data.ns)
7525 ns_clear_frame_area (emacsframe, x, y, width, height);
7527 expose_frame (emacsframe, x, y, width, height);
7531 drawRect: may be called (at least in Mac OS X 10.5) for invisible
7532 views as well for some reason. Thus, do not infer visibility
7535 emacsframe->async_visible = 1;
7536 emacsframe->async_iconified = 0;
7541 /* NSDraggingDestination protocol methods. Actually this is not really a
7542 protocol, but a category of Object. O well... */
7544 -(NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
7546 NSTRACE ("[EmacsView draggingEntered:]");
7547 return NSDragOperationGeneric;
7551 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
7557 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
7562 NSEvent *theEvent = [[self window] currentEvent];
7564 NSDragOperation op = [sender draggingSourceOperationMask];
7567 NSTRACE ("[EmacsView performDragOperation:]");
7572 position = [self convertPoint: [sender draggingLocation] fromView: nil];
7573 x = lrint (position.x); y = lrint (position.y);
7575 pb = [sender draggingPasteboard];
7576 type = [pb availableTypeFromArray: ns_drag_types];
7578 if (! (op & (NSDragOperationMove|NSDragOperationDelete)) &&
7579 // URL drags contain all operations (0xf), don't allow all to be set.
7582 if (op & NSDragOperationLink)
7583 modifiers |= NSEventModifierFlagControl;
7584 if (op & NSDragOperationCopy)
7585 modifiers |= NSEventModifierFlagOption;
7586 if (op & NSDragOperationGeneric)
7587 modifiers |= NSEventModifierFlagCommand;
7590 modifiers = EV_MODIFIERS2 (modifiers);
7595 else if ([type isEqualToString: NSFilenamesPboardType])
7598 NSEnumerator *fenum;
7601 if (!(files = [pb propertyListForType: type]))
7604 fenum = [files objectEnumerator];
7605 while ( (file = [fenum nextObject]) )
7607 emacs_event->kind = DRAG_N_DROP_EVENT;
7608 XSETINT (emacs_event->x, x);
7609 XSETINT (emacs_event->y, y);
7610 ns_input_file = append2 (ns_input_file,
7611 build_string ([file UTF8String]));
7612 emacs_event->modifiers = modifiers;
7613 emacs_event->arg = list2 (Qfile, build_string ([file UTF8String]));
7614 EV_TRAILER (theEvent);
7618 else if ([type isEqualToString: NSURLPboardType])
7620 NSURL *url = [NSURL URLFromPasteboard: pb];
7621 if (url == nil) return NO;
7623 emacs_event->kind = DRAG_N_DROP_EVENT;
7624 XSETINT (emacs_event->x, x);
7625 XSETINT (emacs_event->y, y);
7626 emacs_event->modifiers = modifiers;
7627 emacs_event->arg = list2 (Qurl,
7628 build_string ([[url absoluteString]
7630 EV_TRAILER (theEvent);
7632 if ([url isFileURL] != NO)
7634 NSString *file = [url path];
7635 ns_input_file = append2 (ns_input_file,
7636 build_string ([file UTF8String]));
7640 else if ([type isEqualToString: NSStringPboardType]
7641 || [type isEqualToString: NSTabularTextPboardType])
7645 if (! (data = [pb stringForType: type]))
7648 emacs_event->kind = DRAG_N_DROP_EVENT;
7649 XSETINT (emacs_event->x, x);
7650 XSETINT (emacs_event->y, y);
7651 emacs_event->modifiers = modifiers;
7652 emacs_event->arg = list2 (Qnil, build_string ([data UTF8String]));
7653 EV_TRAILER (theEvent);
7658 fprintf (stderr, "Invalid data type in dragging pasteboard");
7664 - (id) validRequestorForSendType: (NSString *)typeSent
7665 returnType: (NSString *)typeReturned
7667 NSTRACE ("[EmacsView validRequestorForSendType:returnType:]");
7668 if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
7669 && typeReturned == nil)
7671 if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
7675 return [super validRequestorForSendType: typeSent
7676 returnType: typeReturned];
7680 /* The next two methods are part of NSServicesRequests informal protocol,
7681 supposedly called when a services menu item is chosen from this app.
7682 But this should not happen because we override the services menu with our
7683 own entries which call ns-perform-service.
7684 Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
7685 So let's at least stub them out until further investigation can be done. */
7687 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
7689 /* we could call ns_string_from_pasteboard(pboard) here but then it should
7690 be written into the buffer in place of the existing selection..
7691 ordinary service calls go through functions defined in ns-win.el */
7695 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
7697 NSArray *typesDeclared;
7700 NSTRACE ("[EmacsView writeSelectionToPasteboard:types:]");
7702 /* We only support NSStringPboardType */
7703 if ([types containsObject:NSStringPboardType] == NO) {
7707 val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7708 if (CONSP (val) && SYMBOLP (XCAR (val)))
7711 if (CONSP (val) && NILP (XCDR (val)))
7714 if (! STRINGP (val))
7717 typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
7718 [pb declareTypes:typesDeclared owner:nil];
7719 ns_string_to_pasteboard (pb, val);
7724 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
7725 (gives a miniaturized version of the window); currently we use the latter for
7726 frames whose active buffer doesn't correspond to any file
7727 (e.g., '*scratch*') */
7728 - setMiniwindowImage: (BOOL) setMini
7730 id image = [[self window] miniwindowImage];
7731 NSTRACE ("[EmacsView setMiniwindowImage:%d]", setMini);
7733 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
7734 about "AppleDockIconEnabled" notwithstanding, however the set message
7735 below has its effect nonetheless. */
7736 if (image != emacsframe->output_data.ns->miniimage)
7738 if (image && [image isKindOfClass: [EmacsImage class]])
7740 [[self window] setMiniwindowImage:
7741 setMini ? emacsframe->output_data.ns->miniimage : nil];
7748 - (void) setRows: (int) r andColumns: (int) c
7750 NSTRACE ("[EmacsView setRows:%d andColumns:%d]", r, c);
7755 - (int) fullscreenState
7760 @end /* EmacsView */
7764 /* ==========================================================================
7766 EmacsWindow implementation
7768 ========================================================================== */
7770 @implementation EmacsWindow
7772 #ifdef NS_IMPL_COCOA
7773 - (id)accessibilityAttributeValue:(NSString *)attribute
7775 Lisp_Object str = Qnil;
7776 struct frame *f = SELECTED_FRAME ();
7777 struct buffer *curbuf = XBUFFER (XWINDOW (f->selected_window)->contents);
7779 NSTRACE ("[EmacsWindow accessibilityAttributeValue:]");
7781 if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
7782 return NSAccessibilityTextFieldRole;
7784 if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]
7785 && curbuf && ! NILP (BVAR (curbuf, mark_active)))
7787 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7789 else if (curbuf && [attribute isEqualToString:NSAccessibilityValueAttribute])
7791 if (! NILP (BVAR (curbuf, mark_active)))
7792 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7796 ptrdiff_t start_byte = BUF_BEGV_BYTE (curbuf);
7797 ptrdiff_t byte_range = BUF_ZV_BYTE (curbuf) - start_byte;
7798 ptrdiff_t range = BUF_ZV (curbuf) - BUF_BEGV (curbuf);
7800 if (! NILP (BVAR (curbuf, enable_multibyte_characters)))
7801 str = make_uninit_multibyte_string (range, byte_range);
7803 str = make_uninit_string (range);
7804 /* To check: This returns emacs-utf-8, which is a superset of utf-8.
7805 Is this a problem? */
7806 memcpy (SDATA (str), BYTE_POS_ADDR (start_byte), byte_range);
7813 if (CONSP (str) && SYMBOLP (XCAR (str)))
7816 if (CONSP (str) && NILP (XCDR (str)))
7821 const char *utfStr = SSDATA (str);
7822 NSString *nsStr = [NSString stringWithUTF8String: utfStr];
7827 return [super accessibilityAttributeValue:attribute];
7829 #endif /* NS_IMPL_COCOA */
7831 /* Constrain size and placement of a frame.
7833 By returning the original "frameRect", the frame is not
7834 constrained. This can lead to unwanted situations where, for
7835 example, the menu bar covers the frame.
7837 The default implementation (accessed using "super") constrains the
7838 frame to the visible area of SCREEN, minus the menu bar (if
7839 present) and the Dock. Note that default implementation also calls
7840 windowWillResize, with the frame it thinks should have. (This can
7841 make the frame exit maximized mode.)
7843 Note that this should work in situations where multiple monitors
7844 are present. Common configurations are side-by-side monitors and a
7845 monitor on top of another (e.g. when a laptop is placed under a
7847 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
7849 NSTRACE ("[EmacsWindow constrainFrameRect:" NSTRACE_FMT_RECT " toScreen:]",
7850 NSTRACE_ARG_RECT (frameRect));
7852 #ifdef NS_IMPL_COCOA
7853 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7854 // If separate spaces is on, it is like each screen is independent. There is
7855 // no spanning of frames across screens.
7856 if ([NSScreen screensHaveSeparateSpaces])
7858 NSTRACE_MSG ("Screens have separate spaces");
7859 frameRect = [super constrainFrameRect:frameRect toScreen:screen];
7860 NSTRACE_RETURN_RECT (frameRect);
7866 return constrain_frame_rect(frameRect,
7867 [(EmacsView *)[self delegate] isFullscreen]);
7871 - (void)performZoom:(id)sender
7873 NSTRACE ("[EmacsWindow performZoom:]");
7875 return [super performZoom:sender];
7878 - (void)zoom:(id)sender
7880 NSTRACE ("[EmacsWindow zoom:]");
7882 ns_update_auto_hide_menu_bar();
7884 // Below are three zoom implementations. In the final commit, the
7885 // idea is that the last should be included.
7888 // Native zoom done using the standard zoom animation. Size of the
7889 // resulting frame reduced to accommodate the Dock and, if present,
7891 [super zoom:sender];
7894 // Native zoom done using the standard zoom animation, plus an
7895 // explicit resize to cover the full screen, except the menu-bar and
7896 // dock, if present.
7897 [super zoom:sender];
7899 // After the native zoom, resize the resulting frame to fill the
7900 // entire screen, except the menu-bar.
7902 // This works for all practical purposes. (The only minor oddity is
7903 // when transiting from full-height frame to a maximized, the
7904 // animation reduces the height of the frame slightly (to the 4
7905 // pixels needed to accommodate the Doc) before it snaps back into
7906 // full height. The user would need a very trained eye to spot
7908 NSScreen * screen = [self screen];
7911 int fs_state = [(EmacsView *)[self delegate] fullscreenState];
7913 NSTRACE_FSTYPE ("fullscreenState", fs_state);
7915 NSRect sr = [screen frame];
7916 struct EmacsMargins margins
7917 = ns_screen_margins_ignoring_hidden_dock(screen);
7919 NSRect wr = [self frame];
7920 NSTRACE_RECT ("Rect after zoom", wr);
7924 if (fs_state == FULLSCREEN_MAXIMIZED
7925 || fs_state == FULLSCREEN_HEIGHT)
7927 newWr.origin.y = sr.origin.y + margins.bottom;
7928 newWr.size.height = sr.size.height - margins.top - margins.bottom;
7931 if (fs_state == FULLSCREEN_MAXIMIZED
7932 || fs_state == FULLSCREEN_WIDTH)
7934 newWr.origin.x = sr.origin.x + margins.left;
7935 newWr.size.width = sr.size.width - margins.right - margins.left;
7938 if (newWr.size.width != wr.size.width
7939 || newWr.size.height != wr.size.height
7940 || newWr.origin.x != wr.origin.x
7941 || newWr.origin.y != wr.origin.y)
7943 NSTRACE_MSG ("New frame different");
7944 [self setFrame: newWr display: NO];
7948 // Non-native zoom which is done instantaneously. The resulting
7949 // frame covers the entire screen, except the menu-bar and dock, if
7951 NSScreen * screen = [self screen];
7954 NSRect sr = [screen frame];
7955 struct EmacsMargins margins
7956 = ns_screen_margins_ignoring_hidden_dock(screen);
7958 sr.size.height -= (margins.top + margins.bottom);
7959 sr.size.width -= (margins.left + margins.right);
7960 sr.origin.x += margins.left;
7961 sr.origin.y += margins.bottom;
7963 sr = [[self delegate] windowWillUseStandardFrame:self
7965 [self setFrame: sr display: NO];
7970 - (void)setFrame:(NSRect)windowFrame
7971 display:(BOOL)displayViews
7973 NSTRACE ("[EmacsWindow setFrame:" NSTRACE_FMT_RECT " display:%d]",
7974 NSTRACE_ARG_RECT (windowFrame), displayViews);
7976 [super setFrame:windowFrame display:displayViews];
7979 - (void)setFrame:(NSRect)windowFrame
7980 display:(BOOL)displayViews
7981 animate:(BOOL)performAnimation
7983 NSTRACE ("[EmacsWindow setFrame:" NSTRACE_FMT_RECT
7984 " display:%d performAnimation:%d]",
7985 NSTRACE_ARG_RECT (windowFrame), displayViews, performAnimation);
7987 [super setFrame:windowFrame display:displayViews animate:performAnimation];
7990 - (void)setFrameTopLeftPoint:(NSPoint)point
7992 NSTRACE ("[EmacsWindow setFrameTopLeftPoint:" NSTRACE_FMT_POINT "]",
7993 NSTRACE_ARG_POINT (point));
7995 [super setFrameTopLeftPoint:point];
7997 @end /* EmacsWindow */
8000 @implementation EmacsFSWindow
8002 - (BOOL)canBecomeKeyWindow
8007 - (BOOL)canBecomeMainWindow
8014 /* ==========================================================================
8016 EmacsScroller implementation
8018 ========================================================================== */
8021 @implementation EmacsScroller
8023 /* for repeat button push */
8024 #define SCROLL_BAR_FIRST_DELAY 0.5
8025 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
8027 + (CGFloat) scrollerWidth
8029 /* TODO: if we want to allow variable widths, this is the place to do it,
8030 however neither GNUstep nor Cocoa support it very well */
8032 #if !defined (NS_IMPL_COCOA) || \
8033 MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
8034 r = [NSScroller scrollerWidth];
8036 r = [NSScroller scrollerWidthForControlSize: NSControlSizeRegular
8037 scrollerStyle: NSScrollerStyleLegacy];
8042 - initFrame: (NSRect )r window: (Lisp_Object)nwin
8044 NSTRACE ("[EmacsScroller initFrame: window:]");
8046 if (r.size.width > r.size.height)
8051 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
8052 [self setContinuous: YES];
8053 [self setEnabled: YES];
8055 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
8056 locked against the top and bottom edges, and right edge on macOS, where
8057 scrollers are on right. */
8058 #ifdef NS_IMPL_GNUSTEP
8059 [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
8061 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
8064 window = XWINDOW (nwin);
8067 pixel_length = NSWidth (r);
8069 pixel_length = NSHeight (r);
8070 if (pixel_length == 0) pixel_length = 1;
8071 min_portion = 20 / pixel_length;
8073 frame = XFRAME (window->frame);
8074 if (FRAME_LIVE_P (frame))
8077 EmacsView *view = FRAME_NS_VIEW (frame);
8078 NSView *sview = [[view window] contentView];
8079 NSArray *subs = [sview subviews];
8081 /* disable optimization stopping redraw of other scrollbars */
8082 view->scrollbarsNeedingUpdate = 0;
8083 for (i =[subs count]-1; i >= 0; i--)
8084 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
8085 view->scrollbarsNeedingUpdate++;
8086 [sview addSubview: self];
8089 /* [self setFrame: r]; */
8095 - (void)setFrame: (NSRect)newRect
8097 NSTRACE ("[EmacsScroller setFrame:]");
8099 /* block_input (); */
8101 pixel_length = NSWidth (newRect);
8103 pixel_length = NSHeight (newRect);
8104 if (pixel_length == 0) pixel_length = 1;
8105 min_portion = 20 / pixel_length;
8106 [super setFrame: newRect];
8107 /* unblock_input (); */
8113 NSTRACE ("[EmacsScroller dealloc]");
8117 wset_horizontal_scroll_bar (window, Qnil);
8119 wset_vertical_scroll_bar (window, Qnil);
8128 NSTRACE ("[EmacsScroller condemn]");
8136 NSTRACE ("[EmacsScroller reprieve]");
8144 NSTRACE ("[EmacsScroller judge]");
8145 bool ret = condemned;
8150 /* ensure other scrollbar updates after deletion */
8151 view = (EmacsView *)FRAME_NS_VIEW (frame);
8153 view->scrollbarsNeedingUpdate++;
8157 wset_horizontal_scroll_bar (window, Qnil);
8159 wset_vertical_scroll_bar (window, Qnil);
8162 [self removeFromSuperview];
8170 - (void)resetCursorRects
8172 NSRect visible = [self visibleRect];
8173 NSTRACE ("[EmacsScroller resetCursorRects]");
8175 if (!NSIsEmptyRect (visible))
8176 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
8177 [[NSCursor arrowCursor] setOnMouseEntered: YES];
8181 - (int) checkSamePosition: (int) position portion: (int) portion
8184 return em_position ==position && em_portion ==portion && em_whole ==whole
8185 && portion != whole; /* needed for resize empty buf */
8189 - setPosition: (int)position portion: (int)portion whole: (int)whole
8191 NSTRACE ("[EmacsScroller setPosition:portion:whole:]");
8193 em_position = position;
8194 em_portion = portion;
8197 if (portion >= whole)
8199 #ifdef NS_IMPL_COCOA
8200 [self setKnobProportion: 1.0];
8201 [self setDoubleValue: 1.0];
8203 [self setFloatValue: 0.0 knobProportion: 1.0];
8210 portion = max ((float)whole*min_portion/pixel_length, portion);
8211 pos = (float)position / (whole - portion);
8212 por = (CGFloat)portion/whole;
8213 #ifdef NS_IMPL_COCOA
8214 [self setKnobProportion: por];
8215 [self setDoubleValue: pos];
8217 [self setFloatValue: pos knobProportion: por];
8224 /* set up emacs_event */
8225 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
8229 NSTRACE ("[EmacsScroller sendScrollEventAtLoc:fromEvent:]");
8234 emacs_event->part = last_hit_part;
8235 emacs_event->code = 0;
8236 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
8237 XSETWINDOW (win, window);
8238 emacs_event->frame_or_window = win;
8239 emacs_event->timestamp = EV_TIMESTAMP (e);
8240 emacs_event->arg = Qnil;
8244 emacs_event->kind = HORIZONTAL_SCROLL_BAR_CLICK_EVENT;
8245 XSETINT (emacs_event->x, em_whole * loc / pixel_length);
8246 XSETINT (emacs_event->y, em_whole);
8250 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
8251 XSETINT (emacs_event->x, loc);
8252 XSETINT (emacs_event->y, pixel_length-20);
8257 n_emacs_events_pending++;
8258 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
8261 hold_event (emacs_event);
8262 EVENT_INIT (*emacs_event);
8263 ns_send_appdefined (-1);
8267 /* called manually thru timer to implement repeated button action w/hold-down */
8268 - repeatScroll: (NSTimer *)scrollEntry
8270 NSEvent *e = [[self window] currentEvent];
8271 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
8272 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
8274 NSTRACE ("[EmacsScroller repeatScroll:]");
8276 /* clear timer if need be */
8277 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
8279 [scroll_repeat_entry invalidate];
8280 [scroll_repeat_entry release];
8281 scroll_repeat_entry = nil;
8287 = [[NSTimer scheduledTimerWithTimeInterval:
8288 SCROLL_BAR_CONTINUOUS_DELAY
8290 selector: @selector (repeatScroll:)
8296 [self sendScrollEventAtLoc: 0 fromEvent: e];
8301 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
8302 mouseDragged events without going into a modal loop. */
8303 - (void)mouseDown: (NSEvent *)e
8306 /* hitPart is only updated AFTER event is passed on */
8307 NSScrollerPart part = [self testPart: [e locationInWindow]];
8308 CGFloat loc, kloc, pos UNINIT;
8311 NSTRACE ("[EmacsScroller mouseDown:]");
8315 case NSScrollerDecrementPage:
8316 last_hit_part = horizontal ? scroll_bar_before_handle : scroll_bar_above_handle; break;
8317 case NSScrollerIncrementPage:
8318 last_hit_part = horizontal ? scroll_bar_after_handle : scroll_bar_below_handle; break;
8319 case NSScrollerDecrementLine:
8320 last_hit_part = horizontal ? scroll_bar_left_arrow : scroll_bar_up_arrow; break;
8321 case NSScrollerIncrementLine:
8322 last_hit_part = horizontal ? scroll_bar_right_arrow : scroll_bar_down_arrow; break;
8323 case NSScrollerKnob:
8324 last_hit_part = horizontal ? scroll_bar_horizontal_handle : scroll_bar_handle; break;
8325 case NSScrollerKnobSlot: /* GNUstep-only */
8326 last_hit_part = scroll_bar_move_ratio; break;
8327 default: /* NSScrollerNoPart? */
8328 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
8333 if (part == NSScrollerKnob || part == NSScrollerKnobSlot)
8335 /* handle, or on GNUstep possibly slot */
8336 NSEvent *fake_event;
8339 /* compute float loc in slot and mouse offset on knob */
8340 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
8344 length = NSWidth (sr);
8345 loc = ([e locationInWindow].x - NSMinX (sr));
8349 length = NSHeight (sr);
8350 loc = length - ([e locationInWindow].y - NSMinY (sr));
8358 else if (loc >= length)
8368 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
8371 kloc = ([e locationInWindow].x - NSMinX (kr));
8373 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
8375 last_mouse_offset = kloc;
8377 if (part != NSScrollerKnob)
8378 /* this is a slot click on GNUstep: go straight there */
8381 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
8382 fake_event = [NSEvent mouseEventWithType: NSEventTypeLeftMouseUp
8383 location: [e locationInWindow]
8384 modifierFlags: [e modifierFlags]
8385 timestamp: [e timestamp]
8386 windowNumber: [e windowNumber]
8387 context: [e context]
8388 eventNumber: [e eventNumber]
8389 clickCount: [e clickCount]
8390 pressure: [e pressure]];
8391 [super mouseUp: fake_event];
8395 pos = 0; /* ignored */
8397 /* set a timer to repeat, as we can't let superclass do this modally */
8399 = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
8401 selector: @selector (repeatScroll:)
8407 if (part != NSScrollerKnob)
8408 [self sendScrollEventAtLoc: pos fromEvent: e];
8412 /* Called as we manually track scroller drags, rather than superclass. */
8413 - (void)mouseDragged: (NSEvent *)e
8419 NSTRACE ("[EmacsScroller mouseDragged:]");
8421 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
8426 length = NSWidth (sr);
8427 loc = ([e locationInWindow].x - NSMinX (sr));
8431 length = NSHeight (sr);
8432 loc = length - ([e locationInWindow].y - NSMinY (sr));
8439 else if (loc >= length + last_mouse_offset)
8441 loc = length + last_mouse_offset;
8444 pos = (loc - last_mouse_offset);
8445 [self sendScrollEventAtLoc: pos fromEvent: e];
8449 - (void)mouseUp: (NSEvent *)e
8451 NSTRACE ("[EmacsScroller mouseUp:]");
8453 if (scroll_repeat_entry)
8455 [scroll_repeat_entry invalidate];
8456 [scroll_repeat_entry release];
8457 scroll_repeat_entry = nil;
8459 last_hit_part = scroll_bar_above_handle;
8463 /* treat scrollwheel events in the bar as though they were in the main window */
8464 - (void) scrollWheel: (NSEvent *)theEvent
8466 NSTRACE ("[EmacsScroller scrollWheel:]");
8468 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
8469 [view mouseDown: theEvent];
8472 @end /* EmacsScroller */
8475 #ifdef NS_IMPL_GNUSTEP
8476 /* Dummy class to get rid of startup warnings. */
8477 @implementation EmacsDocument
8483 /* ==========================================================================
8485 Font-related functions; these used to be in nsfaces.m
8487 ========================================================================== */
8491 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
8493 struct font *font = XFONT_OBJECT (font_object);
8494 EmacsView *view = FRAME_NS_VIEW (f);
8495 int font_ascent, font_descent;
8498 fontset = fontset_from_font (font_object);
8499 FRAME_FONTSET (f) = fontset;
8501 if (FRAME_FONT (f) == font)
8502 /* This font is already set in frame F. There's nothing more to
8506 FRAME_FONT (f) = font;
8508 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
8509 FRAME_COLUMN_WIDTH (f) = font->average_width;
8510 get_font_ascent_descent (font, &font_ascent, &font_descent);
8511 FRAME_LINE_HEIGHT (f) = font_ascent + font_descent;
8513 /* Compute the scroll bar width in character columns. */
8514 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
8516 int wid = FRAME_COLUMN_WIDTH (f);
8517 FRAME_CONFIG_SCROLL_BAR_COLS (f)
8518 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
8522 int wid = FRAME_COLUMN_WIDTH (f);
8523 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
8526 /* Compute the scroll bar height in character lines. */
8527 if (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) > 0)
8529 int height = FRAME_LINE_HEIGHT (f);
8530 FRAME_CONFIG_SCROLL_BAR_LINES (f)
8531 = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + height - 1) / height;
8535 int height = FRAME_LINE_HEIGHT (f);
8536 FRAME_CONFIG_SCROLL_BAR_LINES (f) = (14 + height - 1) / height;
8539 /* Now make the frame display the given font. */
8540 if (FRAME_NS_WINDOW (f) != 0 && ! [view isFullscreen])
8541 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
8542 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 3,
8549 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
8550 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
8554 ns_xlfd_to_fontname (const char *xlfd)
8555 /* --------------------------------------------------------------------------
8556 Convert an X font name (XLFD) to an NS font name.
8557 Only family is used.
8558 The string returned is temporarily allocated.
8559 -------------------------------------------------------------------------- */
8561 char *name = xmalloc (180);
8565 if (!strncmp (xlfd, "--", 2))
8566 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
8568 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
8570 /* stopgap for malformed XLFD input */
8571 if (strlen (name) == 0)
8572 strcpy (name, "Monaco");
8574 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
8575 also uppercase after '-' or ' ' */
8576 name[0] = c_toupper (name[0]);
8577 for (len =strlen (name), i =0; i<len; i++)
8583 name[i+1] = c_toupper (name[i+1]);
8585 else if (name[i] == '_')
8589 name[i+1] = c_toupper (name[i+1]);
8592 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
8593 ret = [[NSString stringWithUTF8String: name] UTF8String];
8600 syms_of_nsterm (void)
8602 NSTRACE ("syms_of_nsterm");
8604 ns_antialias_threshold = 10.0;
8606 /* from 23+ we need to tell emacs what modifiers there are.. */
8607 DEFSYM (Qmodifier_value, "modifier-value");
8608 DEFSYM (Qalt, "alt");
8609 DEFSYM (Qhyper, "hyper");
8610 DEFSYM (Qmeta, "meta");
8611 DEFSYM (Qsuper, "super");
8612 DEFSYM (Qcontrol, "control");
8613 DEFSYM (QUTF8_STRING, "UTF8_STRING");
8615 DEFSYM (Qfile, "file");
8616 DEFSYM (Qurl, "url");
8618 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
8619 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
8620 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
8621 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
8622 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
8624 DEFVAR_LISP ("ns-input-file", ns_input_file,
8625 "The file specified in the last NS event.");
8626 ns_input_file =Qnil;
8628 DEFVAR_LISP ("ns-working-text", ns_working_text,
8629 "String for visualizing working composition sequence.");
8630 ns_working_text =Qnil;
8632 DEFVAR_LISP ("ns-input-font", ns_input_font,
8633 "The font specified in the last NS event.");
8634 ns_input_font =Qnil;
8636 DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
8637 "The fontsize specified in the last NS event.");
8638 ns_input_fontsize =Qnil;
8640 DEFVAR_LISP ("ns-input-line", ns_input_line,
8641 "The line specified in the last NS event.");
8642 ns_input_line =Qnil;
8644 DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
8645 "The service name specified in the last NS event.");
8646 ns_input_spi_name =Qnil;
8648 DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
8649 "The service argument specified in the last NS event.");
8650 ns_input_spi_arg =Qnil;
8652 DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
8653 "This variable describes the behavior of the alternate or option key.\n\
8654 Set to the symbol control, meta, alt, super, or hyper means it is taken to be\n\
8656 Set to none means that the alternate / option key is not interpreted by Emacs\n\
8657 at all, allowing it to be used at a lower level for accented character entry.");
8658 ns_alternate_modifier = Qmeta;
8660 DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
8661 "This variable describes the behavior of the right alternate or option key.\n\
8662 Set to the symbol control, meta, alt, super, or hyper means it is taken to be\n\
8664 Set to left means be the same key as `ns-alternate-modifier'.\n\
8665 Set to none means that the alternate / option key is not interpreted by Emacs\n\
8666 at all, allowing it to be used at a lower level for accented character entry.");
8667 ns_right_alternate_modifier = Qleft;
8669 DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
8670 "This variable describes the behavior of the command key.\n\
8671 Set to the symbol control, meta, alt, super, or hyper means it is taken to be\n\
8673 ns_command_modifier = Qsuper;
8675 DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
8676 "This variable describes the behavior of the right command key.\n\
8677 Set to the symbol control, meta, alt, super, or hyper means it is taken to be\n\
8679 Set to left means be the same key as `ns-command-modifier'.\n\
8680 Set to none means that the command / option key is not interpreted by Emacs\n\
8681 at all, allowing it to be used at a lower level for accented character entry.");
8682 ns_right_command_modifier = Qleft;
8684 DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
8685 "This variable describes the behavior of the control key.\n\
8686 Set to the symbol control, meta, alt, super, or hyper means it is taken to be\n\
8688 ns_control_modifier = Qcontrol;
8690 DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
8691 "This variable describes the behavior of the right control key.\n\
8692 Set to the symbol control, meta, alt, super, or hyper means it is taken to be\n\
8694 Set to left means be the same key as `ns-control-modifier'.\n\
8695 Set to none means that the control / option key is not interpreted by Emacs\n\
8696 at all, allowing it to be used at a lower level for accented character entry.");
8697 ns_right_control_modifier = Qleft;
8699 DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
8700 "This variable describes the behavior of the function key (on laptops).\n\
8701 Set to the symbol control, meta, alt, super, or hyper means it is taken to be\n\
8703 Set to none means that the function key is not interpreted by Emacs at all,\n\
8704 allowing it to be used at a lower level for accented character entry.");
8705 ns_function_modifier = Qnone;
8707 DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
8708 "Non-nil (the default) means to render text antialiased.");
8709 ns_antialias_text = Qt;
8711 DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
8712 "Whether to confirm application quit using dialog.");
8713 ns_confirm_quit = Qnil;
8715 DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
8716 doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
8717 Only works on Mac OS X 10.6 or later. */);
8718 ns_auto_hide_menu_bar = Qnil;
8720 DEFVAR_BOOL ("ns-use-native-fullscreen", ns_use_native_fullscreen,
8721 doc: /*Non-nil means to use native fullscreen on Mac OS X 10.7 and later.
8722 Nil means use fullscreen the old (< 10.7) way. The old way works better with
8723 multiple monitors, but lacks tool bar. This variable is ignored on
8724 Mac OS X < 10.7. Default is t for 10.7 and later, nil otherwise. */);
8725 #ifdef HAVE_NATIVE_FS
8726 ns_use_native_fullscreen = YES;
8728 ns_use_native_fullscreen = NO;
8730 ns_last_use_native_fullscreen = ns_use_native_fullscreen;
8732 DEFVAR_BOOL ("ns-use-fullscreen-animation", ns_use_fullscreen_animation,
8733 doc: /*Non-nil means use animation on non-native fullscreen.
8734 For native fullscreen, this does nothing.
8735 Default is nil. */);
8736 ns_use_fullscreen_animation = NO;
8738 DEFVAR_BOOL ("ns-use-srgb-colorspace", ns_use_srgb_colorspace,
8739 doc: /*Non-nil means to use sRGB colorspace on Mac OS X 10.7 and later.
8740 Note that this does not apply to images.
8741 This variable is ignored on Mac OS X < 10.7 and GNUstep. */);
8742 ns_use_srgb_colorspace = YES;
8744 /* TODO: move to common code */
8745 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
8746 doc: /* Which toolkit scroll bars Emacs uses, if any.
8747 A value of nil means Emacs doesn't use toolkit scroll bars.
8748 With the X Window system, the value is a symbol describing the
8749 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
8750 With MS Windows or Nextstep, the value is t. */);
8751 Vx_toolkit_scroll_bars = Qt;
8753 DEFVAR_BOOL ("x-use-underline-position-properties",
8754 x_use_underline_position_properties,
8755 doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
8756 A value of nil means ignore them. If you encounter fonts with bogus
8757 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
8758 to 4.1, set this to nil. */);
8759 x_use_underline_position_properties = 0;
8761 DEFVAR_BOOL ("x-underline-at-descent-line",
8762 x_underline_at_descent_line,
8763 doc: /* Non-nil means to draw the underline at the same place as the descent line.
8764 A value of nil means to draw the underline according to the value of the
8765 variable `x-use-underline-position-properties', which is usually at the
8766 baseline level. The default value is nil. */);
8767 x_underline_at_descent_line = 0;
8769 /* Tell Emacs about this window system. */
8770 Fprovide (Qns, Qnil);
8772 DEFSYM (Qcocoa, "cocoa");
8773 DEFSYM (Qgnustep, "gnustep");
8775 #ifdef NS_IMPL_COCOA
8776 Fprovide (Qcocoa, Qnil);
8779 Fprovide (Qgnustep, Qnil);