1 /* NeXT/Open/GNUstep / MacOSX communication module. -*- coding: utf-8 -*-
3 Copyright (C) 1989, 1993-1994, 2005-2006, 2008-2016 Free Software
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or (at
11 your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 Originally by Carl Edman
23 Updated by Christian Limpach (chris@nice.ch)
24 OpenStep/Rhapsody port by Scott Bender (sbender@harmony-ds.com)
25 MacOSX/Aqua port by Christophe de Dinechin (descubes@earthlink.net)
26 GNUstep port and post-20 update by Adrian Robert (arobert@cogsci.ucsd.edu)
29 /* This should be the first include, as it may set up #defines affecting
30 interpretation of even the system includes. */
36 #include <sys/types.h>
42 #include <c-strcase.h>
46 #include "blockinput.h"
47 #include "sysselect.h"
50 #include "character.h"
52 #include "composite.h"
55 #include "termhooks.h"
63 #ifdef NS_IMPL_GNUSTEP
72 extern NSString *NSMenuDidBeginTrackingNotification;
75 /* ==========================================================================
77 NSTRACE, Trace support.
79 ========================================================================== */
83 /* The following use "volatile" since they can be accessed from
85 volatile int nstrace_num = 0;
86 volatile int nstrace_depth = 0;
88 /* When 0, no trace is emitted. This is used by NSTRACE_WHEN and
89 NSTRACE_UNLESS to silence functions called.
91 TODO: This should really be a thread-local variable, to avoid that
92 a function with disabled trace thread silence trace output in
93 another. However, in practice this seldom is a problem. */
94 volatile int nstrace_enabled_global = 1;
96 /* Called when nstrace_enabled goes out of scope. */
97 void nstrace_leave(int * pointer_to_nstrace_enabled)
99 if (*pointer_to_nstrace_enabled)
106 /* Called when nstrace_saved_enabled_global goes out of scope. */
107 void nstrace_restore_global_trace_state(int * pointer_to_saved_enabled_global)
109 nstrace_enabled_global = *pointer_to_saved_enabled_global;
113 char const * nstrace_fullscreen_type_name (int fs_type)
117 case -1: return "-1";
118 case FULLSCREEN_NONE: return "FULLSCREEN_NONE";
119 case FULLSCREEN_WIDTH: return "FULLSCREEN_WIDTH";
120 case FULLSCREEN_HEIGHT: return "FULLSCREEN_HEIGHT";
121 case FULLSCREEN_BOTH: return "FULLSCREEN_BOTH";
122 case FULLSCREEN_MAXIMIZED: return "FULLSCREEN_MAXIMIZED";
123 default: return "FULLSCREEN_?????";
129 /* ==========================================================================
131 NSColor, EmacsColor category.
133 ========================================================================== */
134 @implementation NSColor (EmacsColor)
135 + (NSColor *)colorForEmacsRed:(CGFloat)red green:(CGFloat)green
136 blue:(CGFloat)blue alpha:(CGFloat)alpha
139 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
140 if (ns_use_srgb_colorspace)
141 return [NSColor colorWithSRGBRed: red
147 return [NSColor colorWithCalibratedRed: red
153 - (NSColor *)colorUsingDefaultColorSpace
156 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
157 if (ns_use_srgb_colorspace)
158 return [self colorUsingColorSpace: [NSColorSpace sRGBColorSpace]];
161 return [self colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
166 /* ==========================================================================
170 ========================================================================== */
172 /* Convert a symbol indexed with an NSxxx value to a value as defined
173 in keyboard.c (lispy_function_key). I hope this is a correct way
174 of doing things... */
175 static unsigned convert_ns_to_X_keysym[] =
177 NSHomeFunctionKey, 0x50,
178 NSLeftArrowFunctionKey, 0x51,
179 NSUpArrowFunctionKey, 0x52,
180 NSRightArrowFunctionKey, 0x53,
181 NSDownArrowFunctionKey, 0x54,
182 NSPageUpFunctionKey, 0x55,
183 NSPageDownFunctionKey, 0x56,
184 NSEndFunctionKey, 0x57,
185 NSBeginFunctionKey, 0x58,
186 NSSelectFunctionKey, 0x60,
187 NSPrintFunctionKey, 0x61,
188 NSClearLineFunctionKey, 0x0B,
189 NSExecuteFunctionKey, 0x62,
190 NSInsertFunctionKey, 0x63,
191 NSUndoFunctionKey, 0x65,
192 NSRedoFunctionKey, 0x66,
193 NSMenuFunctionKey, 0x67,
194 NSFindFunctionKey, 0x68,
195 NSHelpFunctionKey, 0x6A,
196 NSBreakFunctionKey, 0x6B,
198 NSF1FunctionKey, 0xBE,
199 NSF2FunctionKey, 0xBF,
200 NSF3FunctionKey, 0xC0,
201 NSF4FunctionKey, 0xC1,
202 NSF5FunctionKey, 0xC2,
203 NSF6FunctionKey, 0xC3,
204 NSF7FunctionKey, 0xC4,
205 NSF8FunctionKey, 0xC5,
206 NSF9FunctionKey, 0xC6,
207 NSF10FunctionKey, 0xC7,
208 NSF11FunctionKey, 0xC8,
209 NSF12FunctionKey, 0xC9,
210 NSF13FunctionKey, 0xCA,
211 NSF14FunctionKey, 0xCB,
212 NSF15FunctionKey, 0xCC,
213 NSF16FunctionKey, 0xCD,
214 NSF17FunctionKey, 0xCE,
215 NSF18FunctionKey, 0xCF,
216 NSF19FunctionKey, 0xD0,
217 NSF20FunctionKey, 0xD1,
218 NSF21FunctionKey, 0xD2,
219 NSF22FunctionKey, 0xD3,
220 NSF23FunctionKey, 0xD4,
221 NSF24FunctionKey, 0xD5,
223 NSBackspaceCharacter, 0x08, /* 8: Not on some KBs. */
224 NSDeleteCharacter, 0xFF, /* 127: Big 'delete' key upper right. */
225 NSDeleteFunctionKey, 0x9F, /* 63272: Del forw key off main array. */
227 NSTabCharacter, 0x09,
228 0x19, 0x09, /* left tab->regular since pass shift */
229 NSCarriageReturnCharacter, 0x0D,
230 NSNewlineCharacter, 0x0D,
231 NSEnterCharacter, 0x8D,
233 0x41|NSNumericPadKeyMask, 0xAE, /* KP_Decimal */
234 0x43|NSNumericPadKeyMask, 0xAA, /* KP_Multiply */
235 0x45|NSNumericPadKeyMask, 0xAB, /* KP_Add */
236 0x4B|NSNumericPadKeyMask, 0xAF, /* KP_Divide */
237 0x4E|NSNumericPadKeyMask, 0xAD, /* KP_Subtract */
238 0x51|NSNumericPadKeyMask, 0xBD, /* KP_Equal */
239 0x52|NSNumericPadKeyMask, 0xB0, /* KP_0 */
240 0x53|NSNumericPadKeyMask, 0xB1, /* KP_1 */
241 0x54|NSNumericPadKeyMask, 0xB2, /* KP_2 */
242 0x55|NSNumericPadKeyMask, 0xB3, /* KP_3 */
243 0x56|NSNumericPadKeyMask, 0xB4, /* KP_4 */
244 0x57|NSNumericPadKeyMask, 0xB5, /* KP_5 */
245 0x58|NSNumericPadKeyMask, 0xB6, /* KP_6 */
246 0x59|NSNumericPadKeyMask, 0xB7, /* KP_7 */
247 0x5B|NSNumericPadKeyMask, 0xB8, /* KP_8 */
248 0x5C|NSNumericPadKeyMask, 0xB9, /* KP_9 */
250 0x1B, 0x1B /* escape */
253 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
254 the maximum font size to NOT antialias. On GNUstep there is currently
255 no way to control this behavior. */
256 float ns_antialias_threshold;
258 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
259 NSString *ns_app_name = @"Emacs"; /* default changed later */
261 /* Display variables */
262 struct ns_display_info *x_display_list; /* Chain of existing displays */
263 long context_menu_value = 0;
266 static struct frame *ns_updating_frame;
267 static NSView *focus_view = NULL;
268 static int ns_window_num = 0;
269 #ifdef NS_IMPL_GNUSTEP
270 static NSRect uRect; // TODO: This is dead, remove it?
272 static BOOL gsaved = NO;
273 static BOOL ns_fake_keydown = NO;
275 static BOOL ns_menu_bar_is_hidden = NO;
277 /*static int debug_lock = 0; */
280 static BOOL send_appdefined = YES;
281 #define NO_APPDEFINED_DATA (-8)
282 static int last_appdefined_event_data = NO_APPDEFINED_DATA;
283 static NSTimer *timed_entry = 0;
284 static NSTimer *scroll_repeat_entry = nil;
285 static fd_set select_readfds, select_writefds;
286 enum { SELECT_HAVE_READ = 1, SELECT_HAVE_WRITE = 2, SELECT_HAVE_TMO = 4 };
287 static int select_nfds = 0, select_valid = 0;
288 static struct timespec select_timeout = { 0, 0 };
289 static int selfds[2] = { -1, -1 };
290 static pthread_mutex_t select_mutex;
291 static int apploopnr = 0;
292 static NSAutoreleasePool *outerpool;
293 static struct input_event *emacs_event = NULL;
294 static struct input_event *q_event_ptr = NULL;
295 static int n_emacs_events_pending = 0;
296 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
297 *ns_pending_service_args;
298 static BOOL ns_do_open_file = NO;
299 static BOOL ns_last_use_native_fullscreen;
301 /* Non-zero means that a HELP_EVENT has been generated since Emacs
304 static BOOL any_help_event_p = NO;
307 struct input_event *q;
313 static NSString *represented_filename = nil;
314 static struct frame *represented_frame = 0;
318 * State for pending menu activation:
319 * MENU_NONE Normal state
320 * MENU_PENDING A menu has been clicked on, but has been canceled so we can
321 * run lisp to update the menu.
322 * MENU_OPENING Menu is up to date, and the click event is redone so the menu
326 #define MENU_PENDING 1
327 #define MENU_OPENING 2
328 static int menu_will_open_state = MENU_NONE;
330 /* Saved position for menu click. */
331 static CGPoint menu_mouse_point;
334 /* Convert modifiers in a NeXTstep event to emacs style modifiers. */
335 #define NS_FUNCTION_KEY_MASK 0x800000
336 #define NSLeftControlKeyMask (0x000001 | NSControlKeyMask)
337 #define NSRightControlKeyMask (0x002000 | NSControlKeyMask)
338 #define NSLeftCommandKeyMask (0x000008 | NSCommandKeyMask)
339 #define NSRightCommandKeyMask (0x000010 | NSCommandKeyMask)
340 #define NSLeftAlternateKeyMask (0x000020 | NSAlternateKeyMask)
341 #define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
342 #define EV_MODIFIERS2(flags) \
343 (((flags & NSHelpKeyMask) ? \
344 hyper_modifier : 0) \
345 | (!EQ (ns_right_alternate_modifier, Qleft) && \
346 ((flags & NSRightAlternateKeyMask) \
347 == NSRightAlternateKeyMask) ? \
348 parse_solitary_modifier (ns_right_alternate_modifier) : 0) \
349 | ((flags & NSAlternateKeyMask) ? \
350 parse_solitary_modifier (ns_alternate_modifier) : 0) \
351 | ((flags & NSShiftKeyMask) ? \
352 shift_modifier : 0) \
353 | (!EQ (ns_right_control_modifier, Qleft) && \
354 ((flags & NSRightControlKeyMask) \
355 == NSRightControlKeyMask) ? \
356 parse_solitary_modifier (ns_right_control_modifier) : 0) \
357 | ((flags & NSControlKeyMask) ? \
358 parse_solitary_modifier (ns_control_modifier) : 0) \
359 | ((flags & NS_FUNCTION_KEY_MASK) ? \
360 parse_solitary_modifier (ns_function_modifier) : 0) \
361 | (!EQ (ns_right_command_modifier, Qleft) && \
362 ((flags & NSRightCommandKeyMask) \
363 == NSRightCommandKeyMask) ? \
364 parse_solitary_modifier (ns_right_command_modifier) : 0) \
365 | ((flags & NSCommandKeyMask) ? \
366 parse_solitary_modifier (ns_command_modifier):0))
367 #define EV_MODIFIERS(e) EV_MODIFIERS2 ([e modifierFlags])
369 #define EV_UDMODIFIERS(e) \
370 ((([e type] == NSLeftMouseDown) ? down_modifier : 0) \
371 | (([e type] == NSRightMouseDown) ? down_modifier : 0) \
372 | (([e type] == NSOtherMouseDown) ? down_modifier : 0) \
373 | (([e type] == NSLeftMouseDragged) ? down_modifier : 0) \
374 | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
375 | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
376 | (([e type] == NSLeftMouseUp) ? up_modifier : 0) \
377 | (([e type] == NSRightMouseUp) ? up_modifier : 0) \
378 | (([e type] == NSOtherMouseUp) ? up_modifier : 0))
380 #define EV_BUTTON(e) \
381 ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 : \
382 (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
383 [e buttonNumber] - 1)
385 /* Convert the time field to a timestamp in milliseconds. */
386 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
388 /* This is a piece of code which is common to all the event handling
389 methods. Maybe it should even be a function. */
390 #define EV_TRAILER(e) \
392 XSETFRAME (emacs_event->frame_or_window, emacsframe); \
396 #define EV_TRAILER2(e) \
398 if (e) emacs_event->timestamp = EV_TIMESTAMP (e); \
401 Lisp_Object tem = Vinhibit_quit; \
402 Vinhibit_quit = Qt; \
403 n_emacs_events_pending++; \
404 kbd_buffer_store_event_hold (emacs_event, q_event_ptr); \
405 Vinhibit_quit = tem; \
408 hold_event (emacs_event); \
409 EVENT_INIT (*emacs_event); \
410 ns_send_appdefined (-1); \
413 /* TODO: get rid of need for these forward declarations */
414 static void ns_condemn_scroll_bars (struct frame *f);
415 static void ns_judge_scroll_bars (struct frame *f);
416 void x_set_frame_alpha (struct frame *f);
419 /* ==========================================================================
423 ========================================================================== */
426 ns_set_represented_filename (NSString* fstr, struct frame *f)
428 represented_filename = [fstr retain];
429 represented_frame = f;
433 ns_init_events (struct input_event* ev)
446 hold_event (struct input_event *event)
448 if (hold_event_q.nr == hold_event_q.cap)
450 if (hold_event_q.cap == 0) hold_event_q.cap = 10;
451 else hold_event_q.cap *= 2;
453 xrealloc (hold_event_q.q, hold_event_q.cap * sizeof *hold_event_q.q);
456 hold_event_q.q[hold_event_q.nr++] = *event;
457 /* Make sure ns_read_socket is called, i.e. we have input. */
459 send_appdefined = YES;
463 append2 (Lisp_Object list, Lisp_Object item)
464 /* --------------------------------------------------------------------------
465 Utility to append to a list
466 -------------------------------------------------------------------------- */
468 return CALLN (Fnconc, list, list1 (item));
473 ns_etc_directory (void)
474 /* If running as a self-contained app bundle, return as a string the
475 filename of the etc directory, if present; else nil. */
477 NSBundle *bundle = [NSBundle mainBundle];
478 NSString *resourceDir = [bundle resourcePath];
479 NSString *resourcePath;
480 NSFileManager *fileManager = [NSFileManager defaultManager];
483 resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
484 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
486 if (isDir) return [resourcePath UTF8String];
494 /* If running as a self-contained app bundle, return as a path string
495 the filenames of the libexec and bin directories, ie libexec:bin.
496 Otherwise, return nil.
497 Normally, Emacs does not add its own bin/ directory to the PATH.
498 However, a self-contained NS build has a different layout, with
499 bin/ and libexec/ subdirectories in the directory that contains
501 We put libexec first, because init_callproc_1 uses the first
502 element to initialize exec-directory. An alternative would be
503 for init_callproc to check for invocation-directory/libexec.
506 NSBundle *bundle = [NSBundle mainBundle];
507 NSString *resourceDir = [bundle resourcePath];
508 NSString *binDir = [bundle bundlePath];
509 NSString *resourcePath, *resourcePaths;
511 NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
512 NSFileManager *fileManager = [NSFileManager defaultManager];
514 NSEnumerator *pathEnum;
517 range = [resourceDir rangeOfString: @"Contents"];
518 if (range.location != NSNotFound)
520 binDir = [binDir stringByAppendingPathComponent: @"Contents"];
522 binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
526 paths = [binDir stringsByAppendingPaths:
527 [NSArray arrayWithObjects: @"libexec", @"bin", nil]];
528 pathEnum = [paths objectEnumerator];
531 while ((resourcePath = [pathEnum nextObject]))
533 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
536 if ([resourcePaths length] > 0)
538 = [resourcePaths stringByAppendingString: pathSeparator];
540 = [resourcePaths stringByAppendingString: resourcePath];
543 if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
551 /* If running as a self-contained app bundle, return as a path string
552 the filenames of the site-lisp and lisp directories.
553 Ie, site-lisp:lisp. Otherwise, return nil. */
555 NSBundle *bundle = [NSBundle mainBundle];
556 NSString *resourceDir = [bundle resourcePath];
557 NSString *resourcePath, *resourcePaths;
558 NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
559 NSFileManager *fileManager = [NSFileManager defaultManager];
561 NSArray *paths = [resourceDir stringsByAppendingPaths:
562 [NSArray arrayWithObjects:
563 @"site-lisp", @"lisp", nil]];
564 NSEnumerator *pathEnum = [paths objectEnumerator];
567 /* Hack to skip site-lisp. */
568 if (no_site_lisp) resourcePath = [pathEnum nextObject];
570 while ((resourcePath = [pathEnum nextObject]))
572 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
575 if ([resourcePaths length] > 0)
577 = [resourcePaths stringByAppendingString: pathSeparator];
579 = [resourcePaths stringByAppendingString: resourcePath];
582 if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
589 ns_init_locale (void)
590 /* OS X doesn't set any environment variables for the locale when run
591 from the GUI. Get the locale from the OS and set LANG. */
593 NSLocale *locale = [NSLocale currentLocale];
595 NSTRACE ("ns_init_locale");
599 /* Set LANG to locale, but not if LANG is already set. */
600 setenv("LANG", [[locale localeIdentifier] UTF8String], 0);
602 @catch (NSException *e)
604 NSLog (@"Locale detection failed: %@: %@", [e name], [e reason]);
610 ns_release_object (void *obj)
611 /* --------------------------------------------------------------------------
612 Release an object (callable from C)
613 -------------------------------------------------------------------------- */
620 ns_retain_object (void *obj)
621 /* --------------------------------------------------------------------------
622 Retain an object (callable from C)
623 -------------------------------------------------------------------------- */
630 ns_alloc_autorelease_pool (void)
631 /* --------------------------------------------------------------------------
632 Allocate a pool for temporary objects (callable from C)
633 -------------------------------------------------------------------------- */
635 return [[NSAutoreleasePool alloc] init];
640 ns_release_autorelease_pool (void *pool)
641 /* --------------------------------------------------------------------------
642 Free a pool and temporary objects it refers to (callable from C)
643 -------------------------------------------------------------------------- */
645 ns_release_object (pool);
649 /* True, if the menu bar should be hidden. */
652 ns_menu_bar_should_be_hidden (void)
654 return !NILP (ns_auto_hide_menu_bar)
655 && [NSApp respondsToSelector:@selector(setPresentationOptions:)];
660 ns_menu_bar_height (NSScreen *screen)
661 /* The height of the menu bar, if visible.
663 Note: Don't use this when fullscreen is enabled -- the screen
664 sometimes includes, sometimes excludes the menu bar area. */
668 if (ns_menu_bar_should_be_hidden())
674 NSRect screenFrame = [screen frame];
675 NSRect screenVisibleFrame = [screen visibleFrame];
677 CGFloat frameTop = screenFrame.origin.y + screenFrame.size.height;
678 CGFloat visibleFrameTop = (screenVisibleFrame.origin.y
679 + screenVisibleFrame.size.height);
681 res = frameTop - visibleFrameTop;
685 NSTRACE ("ns_menu_bar_height " NSTRACE_FMT_RETURN " %.0f", res);
691 /* ==========================================================================
693 Focus (clipping) and screen update
695 ========================================================================== */
698 // Window constraining
699 // -------------------
701 // To ensure that the windows are not placed under the menu bar, they
702 // are typically moved by the call-back constrainFrameRect. However,
703 // by overriding it, it's possible to inhibit this, leaving the window
704 // in it's original position.
706 // It's possible to hide the menu bar. However, technically, it's only
707 // possible to hide it when the application is active. To ensure that
708 // this work properly, the menu bar and window constraining are
709 // deferred until the application becomes active.
711 // Even though it's not possible to manually move a window above the
712 // top of the screen, it is allowed if it's done programmatically,
713 // when the menu is hidden. This allows the editable area to cover the
714 // full screen height.
719 // Use the following extra files:
722 // ;; Hide menu and place frame slightly above the top of the screen.
723 // (setq ns-auto-hide-menu-bar t)
724 // (set-frame-position (selected-frame) 0 -20)
728 // emacs -Q -l init.el
730 // Result: No menu bar, and the title bar should be above the screen.
736 // Result: Menu bar visible, frame placed immediately below the menu.
739 static NSRect constrain_frame_rect(NSRect frameRect, bool isFullscreen)
741 NSTRACE ("constrain_frame_rect(" NSTRACE_FMT_RECT ")",
742 NSTRACE_ARG_RECT (frameRect));
744 // --------------------
745 // Collect information about the screen the frame is covering.
748 NSArray *screens = [NSScreen screens];
749 NSUInteger nr_screens = [screens count];
753 // The height of the menu bar, if present in any screen the frame is
755 int menu_bar_height = 0;
757 // A rectangle covering all the screen the frame is displayed in.
758 NSRect multiscreenRect = NSMakeRect(0, 0, 0, 0);
759 for (i = 0; i < nr_screens; ++i )
761 NSScreen *s = [screens objectAtIndex: i];
762 NSRect scrRect = [s frame];
764 NSTRACE_MSG ("Screen %d: " NSTRACE_FMT_RECT,
765 i, NSTRACE_ARG_RECT (scrRect));
767 if (NSIntersectionRect (frameRect, scrRect).size.height != 0)
769 multiscreenRect = NSUnionRect (multiscreenRect, scrRect);
773 CGFloat screen_menu_bar_height = ns_menu_bar_height (s);
774 menu_bar_height = max(menu_bar_height, screen_menu_bar_height);
779 NSTRACE_RECT ("multiscreenRect", multiscreenRect);
781 NSTRACE_MSG ("menu_bar_height: %d", menu_bar_height);
783 if (multiscreenRect.size.width == 0
784 || multiscreenRect.size.height == 0)
786 // Failed to find any monitor, give up.
787 NSTRACE_MSG ("multiscreenRect empty");
788 NSTRACE_RETURN_RECT (frameRect);
793 // --------------------
794 // Find a suitable placement.
797 if (ns_menu_bar_should_be_hidden())
799 // When the menu bar is hidden, the user may place part of the
800 // frame above the top of the screen, for example to hide the
803 // Hence, keep the original position.
807 // Ensure that the frame is below the menu bar, or below the top
810 // This assume that the menu bar is placed at the top in the
811 // rectangle that covers the monitors. (It doesn't have to be,
812 // but if it's not it's hard to do anything useful.)
813 CGFloat topOfWorkArea = (multiscreenRect.origin.y
814 + multiscreenRect.size.height
817 CGFloat topOfFrame = frameRect.origin.y + frameRect.size.height;
818 if (topOfFrame > topOfWorkArea)
820 frameRect.origin.y -= topOfFrame - topOfWorkArea;
821 NSTRACE_RECT ("After placement adjust", frameRect);
825 // Include the following section to restrict frame to the screens.
826 // (If so, update it to allow the frame to stretch down below the
829 // --------------------
830 // Ensure frame doesn't stretch below the screens.
833 CGFloat diff = multiscreenRect.origin.y - frameRect.origin.y;
837 frameRect.origin.y = multiscreenRect.origin.y;
838 frameRect.size.height -= diff;
842 NSTRACE_RETURN_RECT (frameRect);
848 ns_constrain_all_frames (void)
849 /* --------------------------------------------------------------------------
850 Ensure that the menu bar doesn't cover any frames.
851 -------------------------------------------------------------------------- */
853 Lisp_Object tail, frame;
855 NSTRACE ("ns_constrain_all_frames");
859 FOR_EACH_FRAME (tail, frame)
861 struct frame *f = XFRAME (frame);
864 EmacsView *view = FRAME_NS_VIEW (f);
866 if (![view isFullscreen])
869 setFrame:constrain_frame_rect([[view window] frame], false)
880 ns_update_auto_hide_menu_bar (void)
881 /* --------------------------------------------------------------------------
882 Show or hide the menu bar, based on user setting.
883 -------------------------------------------------------------------------- */
886 NSTRACE ("ns_update_auto_hide_menu_bar");
890 if (NSApp != nil && [NSApp isActive])
892 // Note, "setPresentationOptions" triggers an error unless the
893 // application is active.
894 BOOL menu_bar_should_be_hidden = ns_menu_bar_should_be_hidden ();
896 if (menu_bar_should_be_hidden != ns_menu_bar_is_hidden)
898 NSApplicationPresentationOptions options
899 = NSApplicationPresentationDefault;
901 if (menu_bar_should_be_hidden)
902 options |= NSApplicationPresentationAutoHideMenuBar
903 | NSApplicationPresentationAutoHideDock;
905 [NSApp setPresentationOptions: options];
907 ns_menu_bar_is_hidden = menu_bar_should_be_hidden;
909 if (!ns_menu_bar_is_hidden)
911 ns_constrain_all_frames ();
922 ns_update_begin (struct frame *f)
923 /* --------------------------------------------------------------------------
924 Prepare for a grouped sequence of drawing calls
925 external (RIF) call; whole frame, called before update_window_begin
926 -------------------------------------------------------------------------- */
928 EmacsView *view = FRAME_NS_VIEW (f);
929 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_begin");
931 ns_update_auto_hide_menu_bar ();
934 if ([view isFullscreen] && [view fsIsNative])
936 // Fix reappearing tool bar in fullscreen for OSX 10.7
937 BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (f) ? YES : NO;
938 NSToolbar *toolbar = [FRAME_NS_VIEW (f) toolbar];
939 if (! tbar_visible != ! [toolbar isVisible])
940 [toolbar setVisible: tbar_visible];
944 ns_updating_frame = f;
947 /* drawRect may have been called for say the minibuffer, and then clip path
948 is for the minibuffer. But the display engine may draw more because
949 we have set the frame as garbaged. So reset clip path to the whole
954 NSRect r = [view frame];
955 NSRect cr = [[view window] frame];
956 /* If a large frame size is set, r may be larger than the window frame
957 before constrained. In that case don't change the clip path, as we
958 will clear in to the tool bar and title bar. */
960 + FRAME_NS_TITLEBAR_HEIGHT (f)
961 + FRAME_TOOLBAR_HEIGHT (f) <= cr.size.height)
963 bp = [[NSBezierPath bezierPathWithRect: r] retain];
970 #ifdef NS_IMPL_GNUSTEP
971 uRect = NSMakeRect (0, 0, 0, 0);
977 ns_update_window_begin (struct window *w)
978 /* --------------------------------------------------------------------------
979 Prepare for a grouped sequence of drawing calls
980 external (RIF) call; for one window, called after update_begin
981 -------------------------------------------------------------------------- */
983 struct frame *f = XFRAME (WINDOW_FRAME (w));
984 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
986 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_window_begin");
987 w->output_cursor = w->cursor;
991 if (f == hlinfo->mouse_face_mouse_frame)
993 /* Don't do highlighting for mouse motion during the update. */
994 hlinfo->mouse_face_defer = 1;
996 /* If the frame needs to be redrawn,
997 simply forget about any prior mouse highlighting. */
998 if (FRAME_GARBAGED_P (f))
999 hlinfo->mouse_face_window = Qnil;
1001 /* (further code for mouse faces ifdef'd out in other terms elided) */
1009 ns_update_window_end (struct window *w, bool cursor_on_p,
1010 bool mouse_face_overwritten_p)
1011 /* --------------------------------------------------------------------------
1012 Finished a grouped sequence of drawing calls
1013 external (RIF) call; for one window called before update_end
1014 -------------------------------------------------------------------------- */
1016 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_window_end");
1018 /* note: this fn is nearly identical in all terms */
1019 if (!w->pseudo_window_p)
1024 display_and_set_cursor (w, 1,
1025 w->output_cursor.hpos, w->output_cursor.vpos,
1026 w->output_cursor.x, w->output_cursor.y);
1028 if (draw_window_fringes (w, 1))
1030 if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
1031 x_draw_right_divider (w);
1033 x_draw_vertical_border (w);
1039 /* If a row with mouse-face was overwritten, arrange for
1040 frame_up_to_date to redisplay the mouse highlight. */
1041 if (mouse_face_overwritten_p)
1042 reset_mouse_highlight (MOUSE_HL_INFO (XFRAME (w->frame)));
1047 ns_update_end (struct frame *f)
1048 /* --------------------------------------------------------------------------
1049 Finished a grouped sequence of drawing calls
1050 external (RIF) call; for whole frame, called after update_window_end
1051 -------------------------------------------------------------------------- */
1053 EmacsView *view = FRAME_NS_VIEW (f);
1055 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_end");
1057 /* if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
1058 MOUSE_HL_INFO (f)->mouse_face_defer = 0;
1063 [[view window] flushWindow];
1066 ns_updating_frame = NULL;
1070 ns_focus (struct frame *f, NSRect *r, int n)
1071 /* --------------------------------------------------------------------------
1072 Internal: Focus on given frame. During small local updates this is used to
1073 draw, however during large updates, ns_update_begin and ns_update_end are
1074 called to wrap the whole thing, in which case these calls are stubbed out.
1075 Except, on GNUstep, we accumulate the rectangle being drawn into, because
1076 the back end won't do this automatically, and will just end up flushing
1078 -------------------------------------------------------------------------- */
1080 NSTRACE_WHEN (NSTRACE_GROUP_FOCUS, "ns_focus");
1083 NSTRACE_RECT ("r", *r);
1086 if (f != ns_updating_frame)
1088 NSView *view = FRAME_NS_VIEW (f);
1089 if (view != focus_view)
1091 if (focus_view != NULL)
1093 [focus_view unlockFocus];
1094 [[focus_view window] flushWindow];
1101 /*if (view) debug_lock++; */
1108 [[NSGraphicsContext currentContext] saveGraphicsState];
1110 NSRectClipList (r, 2);
1119 ns_unfocus (struct frame *f)
1120 /* --------------------------------------------------------------------------
1121 Internal: Remove focus on given frame
1122 -------------------------------------------------------------------------- */
1124 NSTRACE_WHEN (NSTRACE_GROUP_FOCUS, "ns_unfocus");
1128 [[NSGraphicsContext currentContext] restoreGraphicsState];
1132 if (f != ns_updating_frame)
1134 if (focus_view != NULL)
1136 [focus_view unlockFocus];
1137 [[focus_view window] flushWindow];
1146 ns_clip_to_row (struct window *w, struct glyph_row *row,
1147 enum glyph_row_area area, BOOL gc)
1148 /* --------------------------------------------------------------------------
1149 Internal (but parallels other terms): Focus drawing on given row
1150 -------------------------------------------------------------------------- */
1152 struct frame *f = XFRAME (WINDOW_FRAME (w));
1154 int window_x, window_y, window_width;
1156 window_box (w, area, &window_x, &window_y, &window_width, 0);
1158 clip_rect.origin.x = window_x;
1159 clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
1160 clip_rect.origin.y = max (clip_rect.origin.y, window_y);
1161 clip_rect.size.width = window_width;
1162 clip_rect.size.height = row->visible_height;
1164 ns_focus (f, &clip_rect, 1);
1168 /* ==========================================================================
1170 Visible bell and beep.
1172 ========================================================================== */
1175 // This bell implementation shows the visual bell image asynchronously
1176 // from the rest of Emacs. This is done by adding a NSView to the
1177 // superview of the Emacs window and removing it using a timer.
1179 // Unfortunately, some Emacs operations, like scrolling, is done using
1180 // low-level primitives that copy the content of the window, including
1181 // the bell image. To some extent, this is handled by removing the
1182 // image prior to scrolling and marking that the window is in need for
1185 // To test this code, make sure that there is no artifacts of the bell
1186 // image in the following situations. Use a non-empty buffer (like the
1187 // tutorial) to ensure that a scroll is performed:
1189 // * Single-window: C-g C-v
1191 // * Side-by-windows: C-x 3 C-g C-v
1193 // * Windows above each other: C-x 2 C-g C-v
1195 @interface EmacsBell : NSImageView
1197 // Number of currently active bell:s.
1198 unsigned int nestCount;
1202 - (void)show:(NSView *)view;
1207 @implementation EmacsBell
1211 NSTRACE ("[EmacsBell init]");
1212 if ((self = [super init]))
1216 #ifdef NS_IMPL_GNUSTEP
1217 // GNUstep doesn't provide named images. This was reported in
1218 // 2011, see https://savannah.gnu.org/bugs/?33396
1220 // As a drop in replacement, a semitransparent gray square is used.
1221 self.image = [[NSImage alloc] initWithSize:NSMakeSize(32 * 5, 32 * 5)];
1222 [self.image lockFocus];
1223 [[NSColor colorForEmacsRed:0.5 green:0.5 blue:0.5 alpha:0.5] set];
1224 NSRectFill(NSMakeRect(0, 0, 32, 32));
1225 [self.image unlockFocus];
1227 self.image = [NSImage imageNamed:NSImageNameCaution];
1228 [self.image setSize:NSMakeSize(self.image.size.width * 5,
1229 self.image.size.height * 5)];
1235 - (void)show:(NSView *)view
1237 NSTRACE ("[EmacsBell show:]");
1238 NSTRACE_MSG ("nestCount: %u", nestCount);
1240 // Show the image, unless it's already shown.
1243 NSRect rect = [view bounds];
1245 pos.x = rect.origin.x + (rect.size.width - self.image.size.width )/2;
1246 pos.y = rect.origin.y + (rect.size.height - self.image.size.height)/2;
1248 [self setFrameOrigin:pos];
1249 [self setFrameSize:self.image.size];
1253 [[[view window] contentView] addSubview:self
1254 positioned:NSWindowAbove
1260 [self performSelector:@selector(hide) withObject:self afterDelay:0.5];
1266 // Note: Trace output from this method isn't shown, reason unknown.
1267 // NSTRACE ("[EmacsBell hide]");
1272 // Remove the image once the last bell became inactive.
1282 NSTRACE ("[EmacsBell remove]");
1285 NSTRACE_MSG ("removeFromSuperview");
1286 [self removeFromSuperview];
1287 mView.needsDisplay = YES;
1295 static EmacsBell * bell_view = nil;
1298 ns_ring_bell (struct frame *f)
1299 /* --------------------------------------------------------------------------
1301 -------------------------------------------------------------------------- */
1303 NSTRACE ("ns_ring_bell");
1306 struct frame *frame = SELECTED_FRAME ();
1309 if (bell_view == nil)
1311 bell_view = [[EmacsBell alloc] init];
1317 view = FRAME_NS_VIEW (frame);
1320 [bell_view show:view];
1332 static void hide_bell ()
1333 /* --------------------------------------------------------------------------
1334 Ensure the bell is hidden.
1335 -------------------------------------------------------------------------- */
1337 NSTRACE ("hide_bell");
1339 if (bell_view != nil)
1346 /* ==========================================================================
1348 Frame / window manager related functions
1350 ========================================================================== */
1354 ns_raise_frame (struct frame *f)
1355 /* --------------------------------------------------------------------------
1356 Bring window to foreground and make it active
1357 -------------------------------------------------------------------------- */
1361 check_window_system (f);
1362 view = FRAME_NS_VIEW (f);
1364 if (FRAME_VISIBLE_P (f))
1365 [[view window] makeKeyAndOrderFront: NSApp];
1371 ns_lower_frame (struct frame *f)
1372 /* --------------------------------------------------------------------------
1374 -------------------------------------------------------------------------- */
1378 check_window_system (f);
1379 view = FRAME_NS_VIEW (f);
1381 [[view window] orderBack: NSApp];
1387 ns_frame_raise_lower (struct frame *f, bool raise)
1388 /* --------------------------------------------------------------------------
1390 -------------------------------------------------------------------------- */
1392 NSTRACE ("ns_frame_raise_lower");
1402 ns_frame_rehighlight (struct frame *frame)
1403 /* --------------------------------------------------------------------------
1404 External (hook): called on things like window switching within frame
1405 -------------------------------------------------------------------------- */
1407 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
1408 struct frame *old_highlight = dpyinfo->x_highlight_frame;
1410 NSTRACE ("ns_frame_rehighlight");
1411 if (dpyinfo->x_focus_frame)
1413 dpyinfo->x_highlight_frame
1414 = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1415 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1416 : dpyinfo->x_focus_frame);
1417 if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
1419 fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
1420 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
1424 dpyinfo->x_highlight_frame = 0;
1426 if (dpyinfo->x_highlight_frame &&
1427 dpyinfo->x_highlight_frame != old_highlight)
1431 x_update_cursor (old_highlight, 1);
1432 x_set_frame_alpha (old_highlight);
1434 if (dpyinfo->x_highlight_frame)
1436 x_update_cursor (dpyinfo->x_highlight_frame, 1);
1437 x_set_frame_alpha (dpyinfo->x_highlight_frame);
1444 x_make_frame_visible (struct frame *f)
1445 /* --------------------------------------------------------------------------
1446 External: Show the window (X11 semantics)
1447 -------------------------------------------------------------------------- */
1449 NSTRACE ("x_make_frame_visible");
1450 /* XXX: at some points in past this was not needed, as the only place that
1451 called this (frame.c:Fraise_frame ()) also called raise_lower;
1452 if this ends up the case again, comment this out again. */
1453 if (!FRAME_VISIBLE_P (f))
1455 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1457 SET_FRAME_VISIBLE (f, 1);
1460 /* Making a new frame from a fullscreen frame will make the new frame
1461 fullscreen also. So skip handleFS as this will print an error. */
1462 if ([view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH
1463 && [view isFullscreen])
1466 if (f->want_fullscreen != FULLSCREEN_NONE)
1477 x_make_frame_invisible (struct frame *f)
1478 /* --------------------------------------------------------------------------
1479 External: Hide the window (X11 semantics)
1480 -------------------------------------------------------------------------- */
1483 NSTRACE ("x_make_frame_invisible");
1484 check_window_system (f);
1485 view = FRAME_NS_VIEW (f);
1486 [[view window] orderOut: NSApp];
1487 SET_FRAME_VISIBLE (f, 0);
1488 SET_FRAME_ICONIFIED (f, 0);
1493 x_iconify_frame (struct frame *f)
1494 /* --------------------------------------------------------------------------
1495 External: Iconify window
1496 -------------------------------------------------------------------------- */
1499 struct ns_display_info *dpyinfo;
1501 NSTRACE ("x_iconify_frame");
1502 check_window_system (f);
1503 view = FRAME_NS_VIEW (f);
1504 dpyinfo = FRAME_DISPLAY_INFO (f);
1506 if (dpyinfo->x_highlight_frame == f)
1507 dpyinfo->x_highlight_frame = 0;
1509 if ([[view window] windowNumber] <= 0)
1511 /* the window is still deferred. Make it very small, bring it
1512 on screen and order it out. */
1513 NSRect s = { { 100, 100}, {0, 0} };
1515 t = [[view window] frame];
1516 [[view window] setFrame: s display: NO];
1517 [[view window] orderBack: NSApp];
1518 [[view window] orderOut: NSApp];
1519 [[view window] setFrame: t display: NO];
1521 [[view window] miniaturize: NSApp];
1524 /* Free X resources of frame F. */
1527 x_free_frame_resources (struct frame *f)
1530 struct ns_display_info *dpyinfo;
1531 Mouse_HLInfo *hlinfo;
1533 NSTRACE ("x_free_frame_resources");
1534 check_window_system (f);
1535 view = FRAME_NS_VIEW (f);
1536 dpyinfo = FRAME_DISPLAY_INFO (f);
1537 hlinfo = MOUSE_HL_INFO (f);
1539 [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1543 free_frame_menubar (f);
1544 free_frame_faces (f);
1546 if (f == dpyinfo->x_focus_frame)
1547 dpyinfo->x_focus_frame = 0;
1548 if (f == dpyinfo->x_highlight_frame)
1549 dpyinfo->x_highlight_frame = 0;
1550 if (f == hlinfo->mouse_face_mouse_frame)
1551 reset_mouse_highlight (hlinfo);
1553 if (f->output_data.ns->miniimage != nil)
1554 [f->output_data.ns->miniimage release];
1556 [[view window] close];
1559 xfree (f->output_data.ns);
1565 x_destroy_window (struct frame *f)
1566 /* --------------------------------------------------------------------------
1567 External: Delete the window
1568 -------------------------------------------------------------------------- */
1570 NSTRACE ("x_destroy_window");
1571 check_window_system (f);
1572 x_free_frame_resources (f);
1578 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1579 /* --------------------------------------------------------------------------
1580 External: Position the window
1581 -------------------------------------------------------------------------- */
1583 NSView *view = FRAME_NS_VIEW (f);
1584 NSArray *screens = [NSScreen screens];
1585 NSScreen *fscreen = [screens objectAtIndex: 0];
1586 NSScreen *screen = [[view window] screen];
1588 NSTRACE ("x_set_offset");
1595 if (view != nil && screen && fscreen)
1597 f->left_pos = f->size_hint_flags & XNegative
1598 ? [screen visibleFrame].size.width + f->left_pos - FRAME_PIXEL_WIDTH (f)
1600 /* We use visibleFrame here to take menu bar into account.
1601 Ideally we should also adjust left/top with visibleFrame.origin. */
1603 f->top_pos = f->size_hint_flags & YNegative
1604 ? ([screen visibleFrame].size.height + f->top_pos
1605 - FRAME_PIXEL_HEIGHT (f) - FRAME_NS_TITLEBAR_HEIGHT (f)
1606 - FRAME_TOOLBAR_HEIGHT (f))
1608 #ifdef NS_IMPL_GNUSTEP
1609 if (f->left_pos < 100)
1610 f->left_pos = 100; /* don't overlap menu */
1612 /* Constrain the setFrameTopLeftPoint so we don't move behind the
1614 NSPoint pt = NSMakePoint (SCREENMAXBOUND (f->left_pos),
1615 SCREENMAXBOUND ([fscreen frame].size.height
1617 NSTRACE_POINT ("setFrameTopLeftPoint", pt);
1618 [[view window] setFrameTopLeftPoint: pt];
1619 f->size_hint_flags &= ~(XNegative|YNegative);
1627 x_set_window_size (struct frame *f,
1628 bool change_gravity,
1632 /* --------------------------------------------------------------------------
1633 Adjust window pixel size based on given character grid size
1634 Impl is a bit more complex than other terms, need to do some
1636 -------------------------------------------------------------------------- */
1638 EmacsView *view = FRAME_NS_VIEW (f);
1639 NSWindow *window = [view window];
1640 NSRect wr = [window frame];
1641 int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1642 int pixelwidth, pixelheight;
1643 int orig_height = wr.size.height;
1645 NSTRACE ("x_set_window_size");
1650 NSTRACE_RECT ("current", wr);
1651 NSTRACE_MSG ("Width:%d Height:%d Pixelwise:%d", width, height, pixelwise);
1652 NSTRACE_MSG ("Font %d x %d", FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f));
1658 pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
1659 pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
1663 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, width);
1664 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, height);
1667 /* If we have a toolbar, take its height into account. */
1668 if (tb && ! [view isFullscreen])
1670 /* NOTE: previously this would generate wrong result if toolbar not
1671 yet displayed and fixing toolbar_height=32 helped, but
1672 now (200903) seems no longer needed */
1673 FRAME_TOOLBAR_HEIGHT (f) =
1674 NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1675 - FRAME_NS_TITLEBAR_HEIGHT (f);
1677 /* Only breaks things here, removed by martin 2015-09-30. */
1678 #ifdef NS_IMPL_GNUSTEP
1679 FRAME_TOOLBAR_HEIGHT (f) -= 3;
1684 FRAME_TOOLBAR_HEIGHT (f) = 0;
1686 wr.size.width = pixelwidth + f->border_width;
1687 wr.size.height = pixelheight;
1688 if (! [view isFullscreen])
1689 wr.size.height += FRAME_NS_TITLEBAR_HEIGHT (f)
1690 + FRAME_TOOLBAR_HEIGHT (f);
1692 /* Do not try to constrain to this screen. We may have multiple
1693 screens, and want Emacs to span those. Constraining to screen
1694 prevents that, and that is not nice to the user. */
1695 if (f->output_data.ns->zooming)
1696 f->output_data.ns->zooming = 0;
1698 wr.origin.y += orig_height - wr.size.height;
1700 frame_size_history_add
1701 (f, Qx_set_window_size_1, width, height,
1702 list5 (Fcons (make_number (pixelwidth), make_number (pixelheight)),
1703 Fcons (make_number (wr.size.width), make_number (wr.size.height)),
1704 make_number (f->border_width),
1705 make_number (FRAME_NS_TITLEBAR_HEIGHT (f)),
1706 make_number (FRAME_TOOLBAR_HEIGHT (f))));
1708 [window setFrame: wr display: YES];
1710 /* This is a trick to compensate for Emacs' managing the scrollbar area
1711 as a fixed number of standard character columns. Instead of leaving
1712 blank space for the extra, we chopped it off above. Now for
1713 left-hand scrollbars, we shift all rendering to the left by the
1714 difference between the real width and Emacs' imagined one. For
1715 right-hand bars, don't worry about it since the extra is never used.
1716 (Obviously doesn't work for vertically split windows tho..) */
1718 NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1719 ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1720 - NS_SCROLL_BAR_WIDTH (f), 0)
1721 : NSMakePoint (0, 0);
1723 [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1724 [view setBoundsOrigin: origin];
1727 [view updateFrameSize: NO];
1733 ns_fullscreen_hook (struct frame *f)
1735 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1737 NSTRACE ("ns_fullscreen_hook");
1739 if (!FRAME_VISIBLE_P (f))
1742 if (! [view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH)
1744 /* Old style fs don't initiate correctly if created from
1745 init/default-frame alist, so use a timer (not nice...).
1747 [NSTimer scheduledTimerWithTimeInterval: 0.5 target: view
1748 selector: @selector (handleFS)
1749 userInfo: nil repeats: NO];
1758 /* ==========================================================================
1762 ========================================================================== */
1766 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1768 struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1769 if (idx < 1 || idx >= color_table->avail)
1771 return color_table->colors[idx];
1776 ns_index_color (NSColor *color, struct frame *f)
1778 struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1782 if (!color_table->colors)
1784 color_table->size = NS_COLOR_CAPACITY;
1785 color_table->avail = 1; /* skip idx=0 as marker */
1786 color_table->colors = xmalloc (color_table->size * sizeof (NSColor *));
1787 color_table->colors[0] = nil;
1788 color_table->empty_indices = [[NSMutableSet alloc] init];
1791 /* Do we already have this color? */
1792 for (i = 1; i < color_table->avail; i++)
1793 if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1796 if ([color_table->empty_indices count] > 0)
1798 NSNumber *index = [color_table->empty_indices anyObject];
1799 [color_table->empty_indices removeObject: index];
1800 idx = [index unsignedLongValue];
1804 if (color_table->avail == color_table->size)
1805 color_table->colors =
1806 xpalloc (color_table->colors, &color_table->size, 1,
1807 min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1808 idx = color_table->avail++;
1811 color_table->colors[idx] = color;
1813 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1819 ns_free_indexed_color (unsigned long idx, struct frame *f)
1821 struct ns_color_table *color_table;
1828 color_table = FRAME_DISPLAY_INFO (f)->color_table;
1830 if (idx <= 0 || idx >= color_table->size) {
1831 message1 ("ns_free_indexed_color: Color index out of range.\n");
1835 index = [NSNumber numberWithUnsignedInt: idx];
1836 if ([color_table->empty_indices containsObject: index]) {
1837 message1 ("ns_free_indexed_color: attempt to free already freed color.\n");
1841 color = color_table->colors[idx];
1843 color_table->colors[idx] = nil;
1844 [color_table->empty_indices addObject: index];
1845 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1850 ns_get_color (const char *name, NSColor **col)
1851 /* --------------------------------------------------------------------------
1853 -------------------------------------------------------------------------- */
1854 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1855 X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1856 See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1859 static char hex[20];
1861 float r = -1.0, g, b;
1862 NSString *nsname = [NSString stringWithUTF8String: name];
1864 NSTRACE ("ns_get_color(%s, **)", name);
1868 if ([nsname isEqualToString: @"ns_selection_bg_color"])
1870 #ifdef NS_IMPL_COCOA
1871 NSString *defname = [[NSUserDefaults standardUserDefaults]
1872 stringForKey: @"AppleHighlightColor"];
1877 if ((new = [NSColor selectedTextBackgroundColor]) != nil)
1879 *col = [new colorUsingDefaultColorSpace];
1884 nsname = NS_SELECTION_BG_COLOR_DEFAULT;
1886 name = [nsname UTF8String];
1888 else if ([nsname isEqualToString: @"ns_selection_fg_color"])
1890 /* NOTE: OSX applications normally don't set foreground selection, but
1891 text may be unreadable if we don't.
1893 if ((new = [NSColor selectedTextColor]) != nil)
1895 *col = [new colorUsingDefaultColorSpace];
1900 nsname = NS_SELECTION_FG_COLOR_DEFAULT;
1901 name = [nsname UTF8String];
1904 /* First, check for some sort of numeric specification. */
1907 if (name[0] == '0' || name[0] == '1' || name[0] == '.') /* RGB decimal */
1909 NSScanner *scanner = [NSScanner scannerWithString: nsname];
1910 [scanner scanFloat: &r];
1911 [scanner scanFloat: &g];
1912 [scanner scanFloat: &b];
1914 else if (!strncmp(name, "rgb:", 4)) /* A newer X11 format -- rgb:r/g/b */
1915 scaling = (snprintf (hex, sizeof hex, "%s", name + 4) - 2) / 3;
1916 else if (name[0] == '#') /* An old X11 format; convert to newer */
1918 int len = (strlen(name) - 1);
1919 int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1921 scaling = strlen(name+start) / 3;
1922 for (i = 0; i < 3; i++)
1923 sprintf (hex + i * (scaling + 1), "%.*s/", scaling,
1924 name + start + i * scaling);
1925 hex[3 * (scaling + 1) - 1] = '\0';
1931 float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1932 if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1942 *col = [NSColor colorForEmacsRed: r green: g blue: b alpha: 1.0];
1947 /* Otherwise, color is expected to be from a list */
1949 NSEnumerator *lenum, *cenum;
1953 #ifdef NS_IMPL_GNUSTEP
1954 /* XXX: who is wrong, the requestor or the implementation? */
1955 if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1957 nsname = @"highlightColor";
1960 lenum = [[NSColorList availableColorLists] objectEnumerator];
1961 while ( (clist = [lenum nextObject]) && new == nil)
1963 cenum = [[clist allKeys] objectEnumerator];
1964 while ( (name = [cenum nextObject]) && new == nil )
1966 if ([name compare: nsname
1967 options: NSCaseInsensitiveSearch] == NSOrderedSame )
1968 new = [clist colorWithKey: name];
1974 *col = [new colorUsingDefaultColorSpace];
1981 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1982 /* --------------------------------------------------------------------------
1983 Convert a Lisp string object to a NS color
1984 -------------------------------------------------------------------------- */
1986 NSTRACE ("ns_lisp_to_color");
1987 if (STRINGP (color))
1988 return ns_get_color (SSDATA (color), col);
1989 else if (SYMBOLP (color))
1990 return ns_get_color (SSDATA (SYMBOL_NAME (color)), col);
1996 ns_color_to_lisp (NSColor *col)
1997 /* --------------------------------------------------------------------------
1998 Convert a color to a lisp string with the RGB equivalent
1999 -------------------------------------------------------------------------- */
2001 EmacsCGFloat red, green, blue, alpha, gray;
2004 NSTRACE ("ns_color_to_lisp");
2007 if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
2009 if ((str =[[col colorNameComponent] UTF8String]))
2012 return build_string ((char *)str);
2015 [[col colorUsingDefaultColorSpace]
2016 getRed: &red green: &green blue: &blue alpha: &alpha];
2017 if (red == green && red == blue)
2019 [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
2020 getWhite: &gray alpha: &alpha];
2021 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
2022 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
2024 return build_string (buf);
2027 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
2028 lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
2031 return build_string (buf);
2036 ns_query_color(void *col, XColor *color_def, int setPixel)
2037 /* --------------------------------------------------------------------------
2038 Get ARGB values out of NSColor col and put them into color_def.
2039 If setPixel, set the pixel to a concatenated version.
2040 and set color_def pixel to the resulting index.
2041 -------------------------------------------------------------------------- */
2043 EmacsCGFloat r, g, b, a;
2045 [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
2046 color_def->red = r * 65535;
2047 color_def->green = g * 65535;
2048 color_def->blue = b * 65535;
2050 if (setPixel == YES)
2052 = ARGB_TO_ULONG((int)(a*255),
2053 (int)(r*255), (int)(g*255), (int)(b*255));
2058 ns_defined_color (struct frame *f,
2063 /* --------------------------------------------------------------------------
2064 Return true if named color found, and set color_def rgb accordingly.
2065 If makeIndex and alloc are nonzero put the color in the color_table,
2066 and set color_def pixel to the resulting index.
2067 If makeIndex is zero, set color_def pixel to ARGB.
2068 Return false if not found
2069 -------------------------------------------------------------------------- */
2072 NSTRACE_WHEN (NSTRACE_GROUP_COLOR, "ns_defined_color");
2075 if (ns_get_color (name, &col) != 0) /* Color not found */
2080 if (makeIndex && alloc)
2081 color_def->pixel = ns_index_color (col, f);
2082 ns_query_color (col, color_def, !makeIndex);
2089 x_set_frame_alpha (struct frame *f)
2090 /* --------------------------------------------------------------------------
2091 change the entire-frame transparency
2092 -------------------------------------------------------------------------- */
2094 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2096 double alpha_min = 1.0;
2098 NSTRACE ("x_set_frame_alpha");
2100 if (dpyinfo->x_highlight_frame == f)
2101 alpha = f->alpha[0];
2103 alpha = f->alpha[1];
2105 if (FLOATP (Vframe_alpha_lower_limit))
2106 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
2107 else if (INTEGERP (Vframe_alpha_lower_limit))
2108 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
2112 else if (1.0 < alpha)
2114 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
2117 #ifdef NS_IMPL_COCOA
2119 EmacsView *view = FRAME_NS_VIEW (f);
2120 [[view window] setAlphaValue: alpha];
2126 /* ==========================================================================
2130 ========================================================================== */
2134 frame_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
2135 /* --------------------------------------------------------------------------
2136 Programmatically reposition mouse pointer in pixel coordinates
2137 -------------------------------------------------------------------------- */
2139 NSTRACE ("frame_set_mouse_pixel_position");
2142 /* FIXME: this does not work, and what about GNUstep? */
2143 #ifdef NS_IMPL_COCOA
2144 [FRAME_NS_VIEW (f) lockFocus];
2145 PSsetmouse ((float)pix_x, (float)pix_y);
2146 [FRAME_NS_VIEW (f) unlockFocus];
2152 note_mouse_movement (struct frame *frame, CGFloat x, CGFloat y)
2153 /* ------------------------------------------------------------------------
2154 Called by EmacsView on mouseMovement events. Passes on
2155 to emacs mainstream code if we moved off of a rect of interest
2156 known as last_mouse_glyph.
2157 ------------------------------------------------------------------------ */
2159 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
2162 // NSTRACE ("note_mouse_movement");
2164 dpyinfo->last_mouse_motion_frame = frame;
2165 r = &dpyinfo->last_mouse_glyph;
2167 /* Note, this doesn't get called for enter/leave, since we don't have a
2168 position. Those are taken care of in the corresponding NSView methods. */
2170 /* has movement gone beyond last rect we were tracking? */
2171 if (x < r->origin.x || x >= r->origin.x + r->size.width
2172 || y < r->origin.y || y >= r->origin.y + r->size.height)
2174 ns_update_begin (frame);
2175 frame->mouse_moved = 1;
2176 note_mouse_highlight (frame, x, y);
2177 remember_mouse_glyph (frame, x, y, r);
2178 ns_update_end (frame);
2187 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
2188 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
2190 /* --------------------------------------------------------------------------
2191 External (hook): inform emacs about mouse position and hit parts.
2192 If a scrollbar is being dragged, set bar_window, part, x, y, time.
2193 x & y should be position in the scrollbar (the whole bar, not the handle)
2194 and length of scrollbar respectively
2195 -------------------------------------------------------------------------- */
2199 Lisp_Object frame, tail;
2201 struct ns_display_info *dpyinfo;
2203 NSTRACE ("ns_mouse_position");
2207 fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
2211 dpyinfo = FRAME_DISPLAY_INFO (*fp);
2215 /* Clear the mouse-moved flag for every frame on this display. */
2216 FOR_EACH_FRAME (tail, frame)
2217 if (FRAME_NS_P (XFRAME (frame))
2218 && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
2219 XFRAME (frame)->mouse_moved = 0;
2221 dpyinfo->last_mouse_scroll_bar = nil;
2222 if (dpyinfo->last_mouse_frame
2223 && FRAME_LIVE_P (dpyinfo->last_mouse_frame))
2224 f = dpyinfo->last_mouse_frame;
2226 f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame : SELECTED_FRAME ();
2228 if (f && FRAME_NS_P (f))
2230 view = FRAME_NS_VIEW (*fp);
2232 position = [[view window] mouseLocationOutsideOfEventStream];
2233 position = [view convertPoint: position fromView: nil];
2234 remember_mouse_glyph (f, position.x, position.y,
2235 &dpyinfo->last_mouse_glyph);
2236 NSTRACE_POINT ("position", position);
2238 if (bar_window) *bar_window = Qnil;
2239 if (part) *part = scroll_bar_above_handle;
2241 if (x) XSETINT (*x, lrint (position.x));
2242 if (y) XSETINT (*y, lrint (position.y));
2244 *time = dpyinfo->last_mouse_movement_time;
2253 ns_frame_up_to_date (struct frame *f)
2254 /* --------------------------------------------------------------------------
2255 External (hook): Fix up mouse highlighting right after a full update.
2256 Can't use FRAME_MOUSE_UPDATE due to ns_frame_begin and ns_frame_end calls.
2257 -------------------------------------------------------------------------- */
2259 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_frame_up_to_date");
2263 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
2264 if (f == hlinfo->mouse_face_mouse_frame)
2268 note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
2269 hlinfo->mouse_face_mouse_x,
2270 hlinfo->mouse_face_mouse_y);
2279 ns_define_frame_cursor (struct frame *f, Cursor cursor)
2280 /* --------------------------------------------------------------------------
2281 External (RIF): set frame mouse pointer type.
2282 -------------------------------------------------------------------------- */
2284 NSTRACE ("ns_define_frame_cursor");
2285 if (FRAME_POINTER_TYPE (f) != cursor)
2287 EmacsView *view = FRAME_NS_VIEW (f);
2288 FRAME_POINTER_TYPE (f) = cursor;
2289 [[view window] invalidateCursorRectsForView: view];
2290 /* Redisplay assumes this function also draws the changed frame
2291 cursor, but this function doesn't, so do it explicitly. */
2292 x_update_cursor (f, 1);
2298 /* ==========================================================================
2302 ========================================================================== */
2306 ns_convert_key (unsigned code)
2307 /* --------------------------------------------------------------------------
2308 Internal call used by NSView-keyDown.
2309 -------------------------------------------------------------------------- */
2311 const unsigned last_keysym = ARRAYELTS (convert_ns_to_X_keysym);
2313 /* An array would be faster, but less easy to read. */
2314 for (keysym = 0; keysym < last_keysym; keysym += 2)
2315 if (code == convert_ns_to_X_keysym[keysym])
2316 return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
2318 /* if decide to use keyCode and Carbon table, use this line:
2319 return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
2324 x_get_keysym_name (int keysym)
2325 /* --------------------------------------------------------------------------
2326 Called by keyboard.c. Not sure if the return val is important, except
2328 -------------------------------------------------------------------------- */
2330 static char value[16];
2331 NSTRACE ("x_get_keysym_name");
2332 sprintf (value, "%d", keysym);
2338 /* ==========================================================================
2340 Block drawing operations
2342 ========================================================================== */
2346 ns_redraw_scroll_bars (struct frame *f)
2350 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
2351 NSTRACE ("ns_redraw_scroll_bars");
2352 for (i =[subviews count]-1; i >= 0; i--)
2354 view = [subviews objectAtIndex: i];
2355 if (![view isKindOfClass: [EmacsScroller class]]) continue;
2362 ns_clear_frame (struct frame *f)
2363 /* --------------------------------------------------------------------------
2364 External (hook): Erase the entire frame
2365 -------------------------------------------------------------------------- */
2367 NSView *view = FRAME_NS_VIEW (f);
2370 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_clear_frame");
2372 /* comes on initial frame because we have
2373 after-make-frame-functions = select-frame */
2374 if (!FRAME_DEFAULT_FACE (f))
2377 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2382 ns_focus (f, &r, 1);
2383 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
2387 /* as of 2006/11 or so this is now needed */
2388 ns_redraw_scroll_bars (f);
2394 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2395 /* --------------------------------------------------------------------------
2396 External (RIF): Clear section of frame
2397 -------------------------------------------------------------------------- */
2399 NSRect r = NSMakeRect (x, y, width, height);
2400 NSView *view = FRAME_NS_VIEW (f);
2401 struct face *face = FRAME_DEFAULT_FACE (f);
2406 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_clear_frame_area");
2408 r = NSIntersectionRect (r, [view frame]);
2409 ns_focus (f, &r, 1);
2410 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2419 ns_copy_bits (struct frame *f, NSRect src, NSRect dest)
2421 NSTRACE ("ns_copy_bits");
2423 if (FRAME_NS_VIEW (f))
2425 hide_bell(); // Ensure the bell image isn't scrolled.
2427 ns_focus (f, &dest, 1);
2428 [FRAME_NS_VIEW (f) scrollRect: src
2429 by: NSMakeSize (dest.origin.x - src.origin.x,
2430 dest.origin.y - src.origin.y)];
2436 ns_scroll_run (struct window *w, struct run *run)
2437 /* --------------------------------------------------------------------------
2438 External (RIF): Insert or delete n lines at line vpos
2439 -------------------------------------------------------------------------- */
2441 struct frame *f = XFRAME (w->frame);
2442 int x, y, width, height, from_y, to_y, bottom_y;
2444 NSTRACE ("ns_scroll_run");
2446 /* begin copy from other terms */
2447 /* Get frame-relative bounding box of the text display area of W,
2448 without mode lines. Include in this box the left and right
2450 window_box (w, ANY_AREA, &x, &y, &width, &height);
2452 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2453 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2454 bottom_y = y + height;
2458 /* Scrolling up. Make sure we don't copy part of the mode
2459 line at the bottom. */
2460 if (from_y + run->height > bottom_y)
2461 height = bottom_y - from_y;
2463 height = run->height;
2467 /* Scrolling down. Make sure we don't copy over the mode line.
2469 if (to_y + run->height > bottom_y)
2470 height = bottom_y - to_y;
2472 height = run->height;
2474 /* end copy from other terms */
2484 NSRect srcRect = NSMakeRect (x, from_y, width, height);
2485 NSRect dstRect = NSMakeRect (x, to_y, width, height);
2487 ns_copy_bits (f, srcRect , dstRect);
2495 ns_after_update_window_line (struct window *w, struct glyph_row *desired_row)
2496 /* --------------------------------------------------------------------------
2497 External (RIF): preparatory to fringe update after text was updated
2498 -------------------------------------------------------------------------- */
2503 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_after_update_window_line");
2505 /* begin copy from other terms */
2508 if (!desired_row->mode_line_p && !w->pseudo_window_p)
2509 desired_row->redraw_fringe_bitmaps_p = 1;
2511 /* When a window has disappeared, make sure that no rest of
2512 full-width rows stays visible in the internal border. */
2513 if (windows_or_buffers_changed
2514 && desired_row->full_width_p
2515 && (f = XFRAME (w->frame),
2516 width = FRAME_INTERNAL_BORDER_WIDTH (f),
2518 && (height = desired_row->visible_height,
2521 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2524 ns_clear_frame_area (f, 0, y, width, height);
2525 ns_clear_frame_area (f,
2526 FRAME_PIXEL_WIDTH (f) - width,
2534 ns_shift_glyphs_for_insert (struct frame *f,
2535 int x, int y, int width, int height,
2537 /* --------------------------------------------------------------------------
2538 External (RIF): copy an area horizontally, don't worry about clearing src
2539 -------------------------------------------------------------------------- */
2541 NSRect srcRect = NSMakeRect (x, y, width, height);
2542 NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2544 NSTRACE ("ns_shift_glyphs_for_insert");
2546 ns_copy_bits (f, srcRect, dstRect);
2551 /* ==========================================================================
2553 Character encoding and metrics
2555 ========================================================================== */
2559 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2560 /* --------------------------------------------------------------------------
2561 External (RIF); compute left/right overhang of whole string and set in s
2562 -------------------------------------------------------------------------- */
2564 struct font *font = s->font;
2568 struct font_metrics metrics;
2569 unsigned int codes[2];
2570 codes[0] = *(s->char2b);
2571 codes[1] = *(s->char2b + s->nchars - 1);
2573 font->driver->text_extents (font, codes, 2, &metrics);
2574 s->left_overhang = -metrics.lbearing;
2576 = metrics.rbearing > metrics.width
2577 ? metrics.rbearing - metrics.width : 0;
2581 s->left_overhang = 0;
2582 if (EQ (font->driver->type, Qns))
2583 s->right_overhang = ((struct nsfont_info *)font)->ital ?
2584 FONT_HEIGHT (font) * 0.2 : 0;
2586 s->right_overhang = 0;
2592 /* ==========================================================================
2594 Fringe and cursor drawing
2596 ========================================================================== */
2599 extern int max_used_fringe_bitmap;
2601 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2602 struct draw_fringe_bitmap_params *p)
2603 /* --------------------------------------------------------------------------
2604 External (RIF); fringe-related
2605 -------------------------------------------------------------------------- */
2607 /* Fringe bitmaps comes in two variants, normal and periodic. A
2608 periodic bitmap is used to create a continuous pattern. Since a
2609 bitmap is rendered one text line at a time, the start offset (dh)
2610 of the bitmap varies. Concretely, this is used for the empty
2613 For a bitmap, "h + dh" is the full height and is always
2614 invariant. For a normal bitmap "dh" is zero.
2616 For example, when the period is three and the full height is 72
2617 the following combinations exists:
2623 struct frame *f = XFRAME (WINDOW_FRAME (w));
2624 struct face *face = p->face;
2625 static EmacsImage **bimgs = NULL;
2626 static int nBimgs = 0;
2628 NSTRACE_WHEN (NSTRACE_GROUP_FRINGE, "ns_draw_fringe_bitmap");
2629 NSTRACE_MSG ("which:%d cursor:%d overlay:%d width:%d height:%d period:%d",
2630 p->which, p->cursor_p, p->overlay_p, p->wd, p->h, p->dh);
2632 /* grow bimgs if needed */
2633 if (nBimgs < max_used_fringe_bitmap)
2635 bimgs = xrealloc (bimgs, max_used_fringe_bitmap * sizeof *bimgs);
2636 memset (bimgs + nBimgs, 0,
2637 (max_used_fringe_bitmap - nBimgs) * sizeof *bimgs);
2638 nBimgs = max_used_fringe_bitmap;
2641 /* Must clip because of partially visible lines. */
2642 ns_clip_to_row (w, row, ANY_AREA, YES);
2646 int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
2648 if (bx >= 0 && nx > 0)
2650 NSRect r = NSMakeRect (bx, by, nx, ny);
2652 [ns_lookup_indexed_color (face->background, f) set];
2659 NSRect r = NSMakeRect (p->x, p->y, p->wd, p->h);
2660 EmacsImage *img = bimgs[p->which - 1];
2664 // Note: For "periodic" images, allocate one EmacsImage for
2665 // the base image, and use it for all dh:s.
2666 unsigned short *bits = p->bits;
2667 int full_height = p->h + p->dh;
2669 unsigned char *cbits = xmalloc (full_height);
2671 for (i = 0; i < full_height; i++)
2673 img = [[EmacsImage alloc] initFromXBM: cbits width: 8
2676 bimgs[p->which - 1] = img;
2680 NSTRACE_RECT ("r", r);
2683 /* Since we composite the bitmap instead of just blitting it, we need
2684 to erase the whole background. */
2685 [ns_lookup_indexed_color(face->background, f) set];
2691 bm_color = ns_lookup_indexed_color(face->foreground, f);
2692 else if (p->overlay_p)
2693 bm_color = ns_lookup_indexed_color(face->background, f);
2695 bm_color = f->output_data.ns->cursor_color;
2696 [img setXBMColor: bm_color];
2699 #ifdef NS_IMPL_COCOA
2700 // Note: For periodic images, the full image height is "h + hd".
2701 // By using the height h, a suitable part of the image is used.
2702 NSRect fromRect = NSMakeRect(0, 0, p->wd, p->h);
2704 NSTRACE_RECT ("fromRect", fromRect);
2708 operation: NSCompositeSourceOver
2714 NSPoint pt = r.origin;
2716 [img compositeToPoint: pt operation: NSCompositeSourceOver];
2725 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2726 int x, int y, enum text_cursor_kinds cursor_type,
2727 int cursor_width, bool on_p, bool active_p)
2728 /* --------------------------------------------------------------------------
2729 External call (RIF): draw cursor.
2730 Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2731 -------------------------------------------------------------------------- */
2734 int fx, fy, h, cursor_height;
2735 struct frame *f = WINDOW_XFRAME (w);
2736 struct glyph *phys_cursor_glyph;
2737 struct glyph *cursor_glyph;
2739 NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2741 /* If cursor is out of bounds, don't draw garbage. This can happen
2742 in mini-buffer windows when switching between echo area glyphs
2745 NSTRACE ("ns_draw_window_cursor");
2750 w->phys_cursor_type = cursor_type;
2751 w->phys_cursor_on_p = on_p;
2753 if (cursor_type == NO_CURSOR)
2755 w->phys_cursor_width = 0;
2759 if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2761 if (glyph_row->exact_window_width_line_p
2762 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2764 glyph_row->cursor_in_fringe_p = 1;
2765 draw_fringe_bitmap (w, glyph_row, 0);
2770 /* We draw the cursor (with NSRectFill), then draw the glyph on top
2771 (other terminals do it the other way round). We must set
2772 w->phys_cursor_width to the cursor width. For bar cursors, that
2773 is CURSOR_WIDTH; for box cursors, it is the glyph width. */
2774 get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2776 /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2777 to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2778 if (cursor_type == BAR_CURSOR)
2780 if (cursor_width < 1)
2781 cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2782 w->phys_cursor_width = cursor_width;
2784 /* If we have an HBAR, "cursor_width" MAY specify height. */
2785 else if (cursor_type == HBAR_CURSOR)
2787 cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2788 if (cursor_height > glyph_row->height)
2789 cursor_height = glyph_row->height;
2790 if (h > cursor_height) // Cursor smaller than line height, move down
2791 fy += h - cursor_height;
2795 r.origin.x = fx, r.origin.y = fy;
2797 r.size.width = w->phys_cursor_width;
2799 /* TODO: only needed in rare cases with last-resort font in HELLO..
2800 should we do this more efficiently? */
2801 ns_clip_to_row (w, glyph_row, ANY_AREA, NO); /* do ns_focus(f, &r, 1); if remove */
2804 face = FACE_FROM_ID (f, phys_cursor_glyph->face_id);
2805 if (face && NS_FACE_BACKGROUND (face)
2806 == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2808 [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2809 hollow_color = FRAME_CURSOR_COLOR (f);
2812 [FRAME_CURSOR_COLOR (f) set];
2814 #ifdef NS_IMPL_COCOA
2815 /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2816 atomic. Cleaner ways of doing this should be investigated.
2817 One way would be to set a global variable DRAWING_CURSOR
2818 when making the call to draw_phys..(), don't focus in that
2819 case, then move the ns_unfocus() here after that call. */
2820 NSDisableScreenUpdates ();
2823 switch (cursor_type)
2825 case DEFAULT_CURSOR:
2828 case FILLED_BOX_CURSOR:
2831 case HOLLOW_BOX_CURSOR:
2834 NSRectFill (NSInsetRect (r, 1, 1));
2835 [FRAME_CURSOR_COLOR (f) set];
2842 /* If the character under cursor is R2L, draw the bar cursor
2843 on the right of its glyph, rather than on the left. */
2844 cursor_glyph = get_phys_cursor_glyph (w);
2845 if ((cursor_glyph->resolved_level & 1) != 0)
2846 s.origin.x += cursor_glyph->pixel_width - s.size.width;
2853 /* draw the character under the cursor */
2854 if (cursor_type != NO_CURSOR)
2855 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2857 #ifdef NS_IMPL_COCOA
2858 NSEnableScreenUpdates ();
2865 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2866 /* --------------------------------------------------------------------------
2867 External (RIF): Draw a vertical line.
2868 -------------------------------------------------------------------------- */
2870 struct frame *f = XFRAME (WINDOW_FRAME (w));
2872 NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2874 NSTRACE ("ns_draw_vertical_window_border");
2876 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2878 [ns_lookup_indexed_color(face->foreground, f) set];
2880 ns_focus (f, &r, 1);
2887 ns_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
2888 /* --------------------------------------------------------------------------
2889 External (RIF): Draw a window divider.
2890 -------------------------------------------------------------------------- */
2892 struct frame *f = XFRAME (WINDOW_FRAME (w));
2894 NSRect r = NSMakeRect (x0, y0, x1-x0, y1-y0);
2896 NSTRACE ("ns_draw_window_divider");
2898 face = FACE_FROM_ID (f, WINDOW_DIVIDER_FACE_ID);
2900 [ns_lookup_indexed_color(face->foreground, f) set];
2902 ns_focus (f, &r, 1);
2908 ns_show_hourglass (struct frame *f)
2910 /* TODO: add NSProgressIndicator to all frames. */
2914 ns_hide_hourglass (struct frame *f)
2916 /* TODO: remove NSProgressIndicator from all frames. */
2919 /* ==========================================================================
2921 Glyph drawing operations
2923 ========================================================================== */
2926 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2927 /* --------------------------------------------------------------------------
2928 Wrapper utility to account for internal border width on full-width lines,
2929 and allow top full-width rows to hit the frame top. nr should be pointer
2930 to two successive NSRects. Number of rects actually used is returned.
2931 -------------------------------------------------------------------------- */
2933 int n = get_glyph_string_clip_rects (s, nr, 2);
2937 /* --------------------------------------------------------------------
2938 Draw a wavy line under glyph string s. The wave fills wave_height
2945 wave_height = 3 | * * * *
2946 --------------------------------------------------------------------- */
2949 ns_draw_underwave (struct glyph_string *s, EmacsCGFloat width, EmacsCGFloat x)
2951 int wave_height = 3, wave_length = 2;
2952 int y, dx, dy, odd, xmax;
2957 dy = wave_height - 1;
2958 y = s->ybase - wave_height + 3;
2961 /* Find and set clipping rectangle */
2962 waveClip = NSMakeRect (x, y, width, wave_height);
2963 [[NSGraphicsContext currentContext] saveGraphicsState];
2964 NSRectClip (waveClip);
2966 /* Draw the waves */
2967 a.x = x - ((int)(x) % dx) + (EmacsCGFloat) 0.5;
2969 odd = (int)(a.x/dx) % 2;
2970 a.y = b.y = y + 0.5;
2979 [NSBezierPath strokeLineFromPoint:a toPoint:b];
2980 a.x = b.x, a.y = b.y;
2981 b.x += dx, b.y = y + 0.5 + odd*dy;
2985 /* Restore previous clipping rectangle(s) */
2986 [[NSGraphicsContext currentContext] restoreGraphicsState];
2992 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
2993 NSColor *defaultCol, CGFloat width, CGFloat x)
2994 /* --------------------------------------------------------------------------
2995 Draw underline, overline, and strike-through on glyph string s.
2996 -------------------------------------------------------------------------- */
2998 if (s->for_overlaps)
3002 if (face->underline_p)
3004 if (s->face->underline_type == FACE_UNDER_WAVE)
3006 if (face->underline_defaulted_p)
3009 [ns_lookup_indexed_color (face->underline_color, s->f) set];
3011 ns_draw_underwave (s, width, x);
3013 else if (s->face->underline_type == FACE_UNDER_LINE)
3017 unsigned long thickness, position;
3019 /* If the prev was underlined, match its appearance. */
3020 if (s->prev && s->prev->face->underline_p
3021 && s->prev->face->underline_type == FACE_UNDER_LINE
3022 && s->prev->underline_thickness > 0)
3024 thickness = s->prev->underline_thickness;
3025 position = s->prev->underline_position;
3030 unsigned long descent;
3033 descent = s->y + s->height - s->ybase;
3035 /* Use underline thickness of font, defaulting to 1. */
3036 thickness = (font && font->underline_thickness > 0)
3037 ? font->underline_thickness : 1;
3039 /* Determine the offset of underlining from the baseline. */
3040 if (x_underline_at_descent_line)
3041 position = descent - thickness;
3042 else if (x_use_underline_position_properties
3043 && font && font->underline_position >= 0)
3044 position = font->underline_position;
3046 position = lround (font->descent / 2);
3048 position = underline_minimum_offset;
3050 position = max (position, underline_minimum_offset);
3052 /* Ensure underlining is not cropped. */
3053 if (descent <= position)
3055 position = descent - 1;
3058 else if (descent < position + thickness)
3062 s->underline_thickness = thickness;
3063 s->underline_position = position;
3065 r = NSMakeRect (x, s->ybase + position, width, thickness);
3067 if (face->underline_defaulted_p)
3070 [ns_lookup_indexed_color (face->underline_color, s->f) set];
3074 /* Do overline. We follow other terms in using a thickness of 1
3075 and ignoring overline_margin. */
3076 if (face->overline_p)
3079 r = NSMakeRect (x, s->y, width, 1);
3081 if (face->overline_color_defaulted_p)
3084 [ns_lookup_indexed_color (face->overline_color, s->f) set];
3088 /* Do strike-through. We follow other terms for thickness and
3089 vertical position.*/
3090 if (face->strike_through_p)
3095 dy = lrint ((s->height - 1) / 2);
3096 r = NSMakeRect (x, s->y + dy, width, 1);
3098 if (face->strike_through_color_defaulted_p)
3101 [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
3107 ns_draw_box (NSRect r, CGFloat thickness, NSColor *col,
3108 char left_p, char right_p)
3109 /* --------------------------------------------------------------------------
3110 Draw an unfilled rect inside r, optionally leaving left and/or right open.
3111 Note we can't just use an NSDrawRect command, because of the possibility
3112 of some sides not being drawn, and because the rect will be filled.
3113 -------------------------------------------------------------------------- */
3119 s.size.height = thickness;
3121 s.origin.y += r.size.height - thickness;
3124 s.size.height = r.size.height;
3125 s.origin.y = r.origin.y;
3127 /* left, right (optional) */
3128 s.size.width = thickness;
3133 s.origin.x += r.size.width - thickness;
3140 ns_draw_relief (NSRect r, int thickness, char raised_p,
3141 char top_p, char bottom_p, char left_p, char right_p,
3142 struct glyph_string *s)
3143 /* --------------------------------------------------------------------------
3144 Draw a relief rect inside r, optionally leaving some sides open.
3145 Note we can't just use an NSDrawBezel command, because of the possibility
3146 of some sides not being drawn, and because the rect will be filled.
3147 -------------------------------------------------------------------------- */
3149 static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
3150 NSColor *newBaseCol = nil;
3153 NSTRACE ("ns_draw_relief");
3157 if (s->face->use_box_color_for_shadows_p)
3159 newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
3161 /* else if (s->first_glyph->type == IMAGE_GLYPH
3163 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
3165 newBaseCol = IMAGE_BACKGROUND (s->img, s->f, 0);
3169 newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
3172 if (newBaseCol == nil)
3173 newBaseCol = [NSColor grayColor];
3175 if (newBaseCol != baseCol) /* TODO: better check */
3178 baseCol = [newBaseCol retain];
3180 lightCol = [[baseCol highlightWithLevel: 0.2] retain];
3182 darkCol = [[baseCol shadowWithLevel: 0.3] retain];
3185 [(raised_p ? lightCol : darkCol) set];
3187 /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
3190 sr.size.height = thickness;
3191 if (top_p) NSRectFill (sr);
3194 sr.size.height = r.size.height;
3195 sr.size.width = thickness;
3196 if (left_p) NSRectFill (sr);
3198 [(raised_p ? darkCol : lightCol) set];
3201 sr.size.width = r.size.width;
3202 sr.size.height = thickness;
3203 sr.origin.y += r.size.height - thickness;
3204 if (bottom_p) NSRectFill (sr);
3207 sr.size.height = r.size.height;
3208 sr.origin.y = r.origin.y;
3209 sr.size.width = thickness;
3210 sr.origin.x += r.size.width - thickness;
3211 if (right_p) NSRectFill (sr);
3216 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
3217 /* --------------------------------------------------------------------------
3218 Function modeled after x_draw_glyph_string_box ().
3219 Sets up parameters for drawing.
3220 -------------------------------------------------------------------------- */
3222 int right_x, last_x;
3223 char left_p, right_p;
3224 struct glyph *last_glyph;
3229 if (s->hl == DRAW_MOUSE_FACE)
3231 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3233 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3238 thickness = face->box_line_width;
3240 NSTRACE ("ns_dumpglyphs_box_or_relief");
3242 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
3243 ? WINDOW_RIGHT_EDGE_X (s->w)
3244 : window_box_right (s->w, s->area));
3245 last_glyph = (s->cmp || s->img
3246 ? s->first_glyph : s->first_glyph + s->nchars-1);
3248 right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
3249 ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
3251 left_p = (s->first_glyph->left_box_line_p
3252 || (s->hl == DRAW_MOUSE_FACE
3253 && (s->prev == NULL || s->prev->hl != s->hl)));
3254 right_p = (last_glyph->right_box_line_p
3255 || (s->hl == DRAW_MOUSE_FACE
3256 && (s->next == NULL || s->next->hl != s->hl)));
3258 r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
3260 /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
3261 if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
3263 ns_draw_box (r, abs (thickness),
3264 ns_lookup_indexed_color (face->box_color, s->f),
3269 ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
3270 1, 1, left_p, right_p, s);
3276 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
3277 /* --------------------------------------------------------------------------
3278 Modeled after x_draw_glyph_string_background, which draws BG in
3279 certain cases. Others are left to the text rendering routine.
3280 -------------------------------------------------------------------------- */
3282 NSTRACE ("ns_maybe_dumpglyphs_background");
3284 if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
3286 int box_line_width = max (s->face->box_line_width, 0);
3287 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
3288 /* When xdisp.c ignores FONT_HEIGHT, we cannot trust font
3289 dimensions, since the actual glyphs might be much
3290 smaller. So in that case we always clear the rectangle
3291 with background color. */
3292 || FONT_TOO_HIGH (s->font)
3293 || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
3296 if (s->hl == DRAW_MOUSE_FACE)
3298 face = FACE_FROM_ID (s->f,
3299 MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3301 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3304 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3306 [(NS_FACE_BACKGROUND (face) != 0
3307 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
3308 : FRAME_BACKGROUND_COLOR (s->f)) set];
3311 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (s->f);
3312 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
3315 if (s->hl != DRAW_CURSOR)
3317 NSRect r = NSMakeRect (s->x, s->y + box_line_width,
3318 s->background_width,
3319 s->height-2*box_line_width);
3323 s->background_filled_p = 1;
3330 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
3331 /* --------------------------------------------------------------------------
3332 Renders an image and associated borders.
3333 -------------------------------------------------------------------------- */
3335 EmacsImage *img = s->img->pixmap;
3336 int box_line_vwidth = max (s->face->box_line_width, 0);
3337 int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3338 int bg_x, bg_y, bg_height;
3345 NSTRACE ("ns_dumpglyphs_image");
3347 if (s->face->box != FACE_NO_BOX
3348 && s->first_glyph->left_box_line_p && s->slice.x == 0)
3349 x += abs (s->face->box_line_width);
3352 bg_y = s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
3353 bg_height = s->height;
3354 /* other terms have this, but was causing problems w/tabbar mode */
3355 /* - 2 * box_line_vwidth; */
3357 if (s->slice.x == 0) x += s->img->hmargin;
3358 if (s->slice.y == 0) y += s->img->vmargin;
3360 /* Draw BG: if we need larger area than image itself cleared, do that,
3361 otherwise, since we composite the image under NS (instead of mucking
3362 with its background color), we must clear just the image area. */
3363 if (s->hl == DRAW_MOUSE_FACE)
3365 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3367 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3370 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3372 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
3374 if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
3375 || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
3377 br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
3378 s->background_filled_p = 1;
3382 br = NSMakeRect (x, y, s->slice.width, s->slice.height);
3387 /* Draw the image.. do we need to draw placeholder if img ==nil? */
3390 #ifdef NS_IMPL_COCOA
3391 NSRect dr = NSMakeRect (x, y, s->slice.width, s->slice.height);
3392 NSRect ir = NSMakeRect (s->slice.x, s->slice.y,
3393 s->slice.width, s->slice.height);
3396 operation: NSCompositeSourceOver
3401 [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3402 operation: NSCompositeSourceOver];
3406 if (s->hl == DRAW_CURSOR)
3408 [FRAME_CURSOR_COLOR (s->f) set];
3409 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3410 tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3412 /* Currently on NS img->mask is always 0. Since
3413 get_window_cursor_type specifies a hollow box cursor when on
3414 a non-masked image we never reach this clause. But we put it
3415 in in anticipation of better support for image masks on
3417 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3421 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3424 /* Draw underline, overline, strike-through. */
3425 ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3427 /* Draw relief, if requested */
3428 if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3430 if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3432 th = tool_bar_button_relief >= 0 ?
3433 tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3434 raised_p = (s->hl == DRAW_IMAGE_RAISED);
3438 th = abs (s->img->relief);
3439 raised_p = (s->img->relief > 0);
3442 r.origin.x = x - th;
3443 r.origin.y = y - th;
3444 r.size.width = s->slice.width + 2*th-1;
3445 r.size.height = s->slice.height + 2*th-1;
3446 ns_draw_relief (r, th, raised_p,
3448 s->slice.y + s->slice.height == s->img->height,
3450 s->slice.x + s->slice.width == s->img->width, s);
3453 /* If there is no mask, the background won't be seen,
3454 so draw a rectangle on the image for the cursor.
3455 Do this for all images, getting transparency right is not reliable. */
3456 if (s->hl == DRAW_CURSOR)
3458 int thickness = abs (s->img->relief);
3459 if (thickness == 0) thickness = 1;
3460 ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3466 ns_dumpglyphs_stretch (struct glyph_string *s)
3471 NSColor *fgCol, *bgCol;
3473 if (!s->background_filled_p)
3475 n = ns_get_glyph_string_clip_rect (s, r);
3476 *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3478 ns_focus (s->f, r, n);
3480 if (s->hl == DRAW_MOUSE_FACE)
3482 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3484 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3487 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3489 bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3490 fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3492 for (i = 0; i < n; ++i)
3494 if (!s->row->full_width_p)
3496 int overrun, leftoverrun;
3498 /* truncate to avoid overwriting fringe and/or scrollbar */
3499 overrun = max (0, (s->x + s->background_width)
3500 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3501 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3502 r[i].size.width -= overrun;
3504 /* truncate to avoid overwriting to left of the window box */
3505 leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3506 + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3508 if (leftoverrun > 0)
3510 r[i].origin.x += leftoverrun;
3511 r[i].size.width -= leftoverrun;
3514 /* XXX: Try to work between problem where a stretch glyph on
3515 a partially-visible bottom row will clear part of the
3516 modeline, and another where list-buffers headers and similar
3517 rows erroneously have visible_height set to 0. Not sure
3518 where this is coming from as other terms seem not to show. */
3519 r[i].size.height = min (s->height, s->row->visible_height);
3524 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3525 overwriting cursor (usually when cursor on a tab) */
3526 if (s->hl == DRAW_CURSOR)
3531 width = s->w->phys_cursor_width;
3532 r[i].size.width -= width;
3533 r[i].origin.x += width;
3537 /* Draw overlining, etc. on the cursor. */
3538 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3539 ns_draw_text_decoration (s, face, bgCol, width, x);
3541 ns_draw_text_decoration (s, face, fgCol, width, x);
3548 /* Draw overlining, etc. on the stretch glyph (or the part
3549 of the stretch glyph after the cursor). */
3550 ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3554 s->background_filled_p = 1;
3560 ns_draw_composite_glyph_string_foreground (struct glyph_string *s)
3563 struct font *font = s->font;
3565 /* If first glyph of S has a left box line, start drawing the text
3566 of S to the right of that box line. */
3567 if (s->face && s->face->box != FACE_NO_BOX
3568 && s->first_glyph->left_box_line_p)
3569 x = s->x + eabs (s->face->box_line_width);
3573 /* S is a glyph string for a composition. S->cmp_from is the index
3574 of the first character drawn for glyphs of this composition.
3575 S->cmp_from == 0 means we are drawing the very first character of
3576 this composition. */
3578 /* Draw a rectangle for the composition if the font for the very
3579 first character of the composition could not be loaded. */
3580 if (s->font_not_found_p)
3582 if (s->cmp_from == 0)
3584 NSRect r = NSMakeRect (s->x, s->y, s->width-1, s->height -1);
3585 ns_draw_box (r, 1, FRAME_CURSOR_COLOR (s->f), 1, 1);
3588 else if (! s->first_glyph->u.cmp.automatic)
3592 for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
3593 /* TAB in a composition means display glyphs with padding
3594 space on the left or right. */
3595 if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
3597 int xx = x + s->cmp->offsets[j * 2];
3598 int yy = y - s->cmp->offsets[j * 2 + 1];
3600 font->driver->draw (s, j, j + 1, xx, yy, false);
3601 if (s->face->overstrike)
3602 font->driver->draw (s, j, j + 1, xx + 1, yy, false);
3607 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
3612 for (i = j = s->cmp_from; i < s->cmp_to; i++)
3614 glyph = LGSTRING_GLYPH (gstring, i);
3615 if (NILP (LGLYPH_ADJUSTMENT (glyph)))
3616 width += LGLYPH_WIDTH (glyph);
3619 int xoff, yoff, wadjust;
3623 font->driver->draw (s, j, i, x, y, false);
3624 if (s->face->overstrike)
3625 font->driver->draw (s, j, i, x + 1, y, false);
3628 xoff = LGLYPH_XOFF (glyph);
3629 yoff = LGLYPH_YOFF (glyph);
3630 wadjust = LGLYPH_WADJUST (glyph);
3631 font->driver->draw (s, i, i + 1, x + xoff, y + yoff, false);
3632 if (s->face->overstrike)
3633 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff,
3642 font->driver->draw (s, j, i, x, y, false);
3643 if (s->face->overstrike)
3644 font->driver->draw (s, j, i, x + 1, y, false);
3650 ns_draw_glyph_string (struct glyph_string *s)
3651 /* --------------------------------------------------------------------------
3652 External (RIF): Main draw-text call.
3653 -------------------------------------------------------------------------- */
3655 /* TODO (optimize): focus for box and contents draw */
3658 char box_drawn_p = 0;
3659 struct font *font = s->face->font;
3660 if (! font) font = FRAME_FONT (s->f);
3662 NSTRACE_WHEN (NSTRACE_GROUP_GLYPHS, "ns_draw_glyph_string");
3664 if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3667 struct glyph_string *next;
3669 for (width = 0, next = s->next;
3670 next && width < s->right_overhang;
3671 width += next->width, next = next->next)
3672 if (next->first_glyph->type != IMAGE_GLYPH)
3674 if (next->first_glyph->type != STRETCH_GLYPH)
3676 n = ns_get_glyph_string_clip_rect (s->next, r);
3677 ns_focus (s->f, r, n);
3678 ns_maybe_dumpglyphs_background (s->next, 1);
3683 ns_dumpglyphs_stretch (s->next);
3685 next->num_clips = 0;
3689 if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3690 && (s->first_glyph->type == CHAR_GLYPH
3691 || s->first_glyph->type == COMPOSITE_GLYPH))
3693 n = ns_get_glyph_string_clip_rect (s, r);
3694 ns_focus (s->f, r, n);
3695 ns_maybe_dumpglyphs_background (s, 1);
3696 ns_dumpglyphs_box_or_relief (s);
3701 switch (s->first_glyph->type)
3705 n = ns_get_glyph_string_clip_rect (s, r);
3706 ns_focus (s->f, r, n);
3707 ns_dumpglyphs_image (s, r[0]);
3712 ns_dumpglyphs_stretch (s);
3716 case COMPOSITE_GLYPH:
3717 n = ns_get_glyph_string_clip_rect (s, r);
3718 ns_focus (s->f, r, n);
3720 if (s->for_overlaps || (s->cmp_from > 0
3721 && ! s->first_glyph->u.cmp.automatic))
3722 s->background_filled_p = 1;
3724 ns_maybe_dumpglyphs_background
3725 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3727 flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3728 (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3729 (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3730 NS_DUMPGLYPH_NORMAL));
3732 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3734 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3735 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3736 NS_FACE_FOREGROUND (s->face) = tmp;
3740 BOOL isComposite = s->first_glyph->type == COMPOSITE_GLYPH;
3743 ns_draw_composite_glyph_string_foreground (s);
3746 (s, s->cmp_from, s->nchars, s->x, s->ybase,
3747 (flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3748 || flags == NS_DUMPGLYPH_MOUSEFACE);
3752 NSColor *col = (NS_FACE_FOREGROUND (s->face) != 0
3753 ? ns_lookup_indexed_color (NS_FACE_FOREGROUND (s->face),
3755 : FRAME_FOREGROUND_COLOR (s->f));
3758 /* Draw underline, overline, strike-through. */
3759 ns_draw_text_decoration (s, s->face, col, s->width, s->x);
3762 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3764 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3765 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3766 NS_FACE_FOREGROUND (s->face) = tmp;
3772 case GLYPHLESS_GLYPH:
3773 n = ns_get_glyph_string_clip_rect (s, r);
3774 ns_focus (s->f, r, n);
3776 if (s->for_overlaps || (s->cmp_from > 0
3777 && ! s->first_glyph->u.cmp.automatic))
3778 s->background_filled_p = 1;
3780 ns_maybe_dumpglyphs_background
3781 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3783 /* Not yet implemented. */
3792 /* Draw box if not done already. */
3793 if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3795 n = ns_get_glyph_string_clip_rect (s, r);
3796 ns_focus (s->f, r, n);
3797 ns_dumpglyphs_box_or_relief (s);
3806 /* ==========================================================================
3810 ========================================================================== */
3814 ns_send_appdefined (int value)
3815 /* --------------------------------------------------------------------------
3816 Internal: post an appdefined event which EmacsApp-sendEvent will
3817 recognize and take as a command to halt the event loop.
3818 -------------------------------------------------------------------------- */
3820 NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_send_appdefined(%d)", value);
3822 #ifdef NS_IMPL_GNUSTEP
3823 // GNUstep needs postEvent to happen on the main thread.
3824 if (! [[NSThread currentThread] isMainThread])
3826 EmacsApp *app = (EmacsApp *)NSApp;
3827 app->nextappdefined = value;
3828 [app performSelectorOnMainThread:@selector (sendFromMainThread:)
3835 /* Only post this event if we haven't already posted one. This will end
3836 the [NXApp run] main loop after having processed all events queued at
3839 #ifdef NS_IMPL_COCOA
3840 if (! send_appdefined)
3842 /* OSX 10.10.1 swallows the AppDefined event we are sending ourselves
3843 in certain situations (rapid incoming events).
3844 So check if we have one, if not add one. */
3845 NSEvent *appev = [NSApp nextEventMatchingMask:NSApplicationDefinedMask
3846 untilDate:[NSDate distantPast]
3847 inMode:NSDefaultRunLoopMode
3849 if (! appev) send_appdefined = YES;
3853 if (send_appdefined)
3857 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
3858 send_appdefined = NO;
3860 /* Don't need wakeup timer any more */
3863 [timed_entry invalidate];
3864 [timed_entry release];
3868 nxev = [NSEvent otherEventWithType: NSApplicationDefined
3869 location: NSMakePoint (0, 0)
3872 windowNumber: [[NSApp mainWindow] windowNumber]
3873 context: [NSApp context]
3878 /* Post an application defined event on the event queue. When this is
3879 received the [NXApp run] will return, thus having processed all
3880 events which are currently queued. */
3881 [NSApp postEvent: nxev atStart: NO];
3885 #ifdef HAVE_NATIVE_FS
3889 Lisp_Object frame, tail;
3891 if (ns_last_use_native_fullscreen == ns_use_native_fullscreen)
3894 ns_last_use_native_fullscreen = ns_use_native_fullscreen;
3896 FOR_EACH_FRAME (tail, frame)
3898 struct frame *f = XFRAME (frame);
3901 EmacsView *view = FRAME_NS_VIEW (f);
3902 [view updateCollectionBehavior];
3908 /* GNUstep does not have cancelTracking. */
3909 #ifdef NS_IMPL_COCOA
3910 /* Check if menu open should be canceled or continued as normal. */
3912 ns_check_menu_open (NSMenu *menu)
3914 /* Click in menu bar? */
3915 NSArray *a = [[NSApp mainMenu] itemArray];
3919 if (menu == nil) // Menu tracking ended.
3921 if (menu_will_open_state == MENU_OPENING)
3922 menu_will_open_state = MENU_NONE;
3926 for (i = 0; ! found && i < [a count]; i++)
3927 found = menu == [[a objectAtIndex:i] submenu];
3930 if (menu_will_open_state == MENU_NONE && emacs_event)
3932 NSEvent *theEvent = [NSApp currentEvent];
3933 struct frame *emacsframe = SELECTED_FRAME ();
3935 [menu cancelTracking];
3936 menu_will_open_state = MENU_PENDING;
3937 emacs_event->kind = MENU_BAR_ACTIVATE_EVENT;
3938 EV_TRAILER (theEvent);
3940 CGEventRef ourEvent = CGEventCreate (NULL);
3941 menu_mouse_point = CGEventGetLocation (ourEvent);
3942 CFRelease (ourEvent);
3944 else if (menu_will_open_state == MENU_OPENING)
3946 menu_will_open_state = MENU_NONE;
3951 /* Redo saved menu click if state is MENU_PENDING. */
3953 ns_check_pending_open_menu ()
3955 if (menu_will_open_state == MENU_PENDING)
3957 CGEventSourceRef source
3958 = CGEventSourceCreate (kCGEventSourceStateHIDSystemState);
3960 CGEventRef event = CGEventCreateMouseEvent (source,
3961 kCGEventLeftMouseDown,
3963 kCGMouseButtonLeft);
3964 CGEventSetType (event, kCGEventLeftMouseDown);
3965 CGEventPost (kCGHIDEventTap, event);
3969 menu_will_open_state = MENU_OPENING;
3972 #endif /* NS_IMPL_COCOA */
3975 unwind_apploopnr (Lisp_Object not_used)
3978 n_emacs_events_pending = 0;
3979 ns_finish_events ();
3984 ns_read_socket (struct terminal *terminal, struct input_event *hold_quit)
3985 /* --------------------------------------------------------------------------
3986 External (hook): Post an event to ourself and keep reading events until
3987 we read it back again. In effect process all events which were waiting.
3988 From 21+ we have to manage the event buffer ourselves.
3989 -------------------------------------------------------------------------- */
3991 struct input_event ev;
3994 NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_read_socket");
3996 #ifdef HAVE_NATIVE_FS
4000 if ([NSApp modalWindow] != nil)
4003 if (hold_event_q.nr > 0)
4006 for (i = 0; i < hold_event_q.nr; ++i)
4007 kbd_buffer_store_event_hold (&hold_event_q.q[i], hold_quit);
4008 hold_event_q.nr = 0;
4013 n_emacs_events_pending = 0;
4014 ns_init_events (&ev);
4015 q_event_ptr = hold_quit;
4017 /* we manage autorelease pools by allocate/reallocate each time around
4018 the loop; strict nesting is occasionally violated but seems not to
4019 matter.. earlier methods using full nesting caused major memory leaks */
4020 [outerpool release];
4021 outerpool = [[NSAutoreleasePool alloc] init];
4023 /* If have pending open-file requests, attend to the next one of those. */
4024 if (ns_pending_files && [ns_pending_files count] != 0
4025 && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
4027 [ns_pending_files removeObjectAtIndex: 0];
4029 /* Deal with pending service requests. */
4030 else if (ns_pending_service_names && [ns_pending_service_names count] != 0
4032 NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
4033 withArg: [ns_pending_service_args objectAtIndex: 0]])
4035 [ns_pending_service_names removeObjectAtIndex: 0];
4036 [ns_pending_service_args removeObjectAtIndex: 0];
4040 ptrdiff_t specpdl_count = SPECPDL_INDEX ();
4041 /* Run and wait for events. We must always send one NX_APPDEFINED event
4042 to ourself, otherwise [NXApp run] will never exit. */
4043 send_appdefined = YES;
4044 ns_send_appdefined (-1);
4046 if (++apploopnr != 1)
4050 record_unwind_protect (unwind_apploopnr, Qt);
4052 unbind_to (specpdl_count, Qnil); /* calls unwind_apploopnr */
4055 nevents = n_emacs_events_pending;
4056 n_emacs_events_pending = 0;
4057 ns_finish_events ();
4066 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
4067 fd_set *exceptfds, struct timespec const *timeout,
4068 sigset_t const *sigmask)
4069 /* --------------------------------------------------------------------------
4070 Replacement for select, checking for events
4071 -------------------------------------------------------------------------- */
4075 struct input_event event;
4078 NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_select");
4080 #ifdef HAVE_NATIVE_FS
4084 if (hold_event_q.nr > 0)
4086 /* We already have events pending. */
4092 for (k = 0; k < nfds+1; k++)
4094 if (readfds && FD_ISSET(k, readfds)) ++nr;
4095 if (writefds && FD_ISSET(k, writefds)) ++nr;
4099 || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0))
4100 return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
4102 [outerpool release];
4103 outerpool = [[NSAutoreleasePool alloc] init];
4106 send_appdefined = YES;
4109 pthread_mutex_lock (&select_mutex);
4114 select_readfds = *readfds;
4115 select_valid += SELECT_HAVE_READ;
4119 select_writefds = *writefds;
4120 select_valid += SELECT_HAVE_WRITE;
4125 select_timeout = *timeout;
4126 select_valid += SELECT_HAVE_TMO;
4129 pthread_mutex_unlock (&select_mutex);
4131 /* Inform fd_handler that select should be called */
4133 emacs_write_sig (selfds[1], &c, 1);
4135 else if (nr == 0 && timeout)
4137 /* No file descriptor, just a timeout, no need to wake fd_handler */
4138 double time = timespectod (*timeout);
4139 timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
4142 @selector (timeout_handler:)
4147 else /* No timeout and no file descriptors, can this happen? */
4149 /* Send appdefined so we exit from the loop */
4150 ns_send_appdefined (-1);
4154 ns_init_events (&event);
4155 if (++apploopnr != 1)
4161 ptrdiff_t specpdl_count = SPECPDL_INDEX ();
4162 record_unwind_protect (unwind_apploopnr, Qt);
4164 unbind_to (specpdl_count, Qnil); /* calls unwind_apploopnr */
4167 ns_finish_events ();
4168 if (nr > 0 && readfds)
4171 emacs_write_sig (selfds[1], &c, 1);
4175 t = last_appdefined_event_data;
4177 if (t != NO_APPDEFINED_DATA)
4179 last_appdefined_event_data = NO_APPDEFINED_DATA;
4183 /* The NX_APPDEFINED event we received was a timeout. */
4188 /* The NX_APPDEFINED event we received was the result of
4189 at least one real input event arriving. */
4195 /* Received back from select () in fd_handler; copy the results */
4196 pthread_mutex_lock (&select_mutex);
4197 if (readfds) *readfds = select_readfds;
4198 if (writefds) *writefds = select_writefds;
4199 pthread_mutex_unlock (&select_mutex);
4214 /* ==========================================================================
4218 ========================================================================== */
4222 ns_set_vertical_scroll_bar (struct window *window,
4223 int portion, int whole, int position)
4224 /* --------------------------------------------------------------------------
4225 External (hook): Update or add scrollbar
4226 -------------------------------------------------------------------------- */
4230 struct frame *f = XFRAME (WINDOW_FRAME (window));
4231 EmacsView *view = FRAME_NS_VIEW (f);
4233 int window_y, window_height;
4234 int top, left, height, width;
4235 BOOL update_p = YES;
4237 /* optimization; display engine sends WAY too many of these.. */
4238 if (!NILP (window->vertical_scroll_bar))
4240 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4241 if ([bar checkSamePosition: position portion: portion whole: whole])
4243 if (view->scrollbarsNeedingUpdate == 0)
4245 if (!windows_or_buffers_changed)
4249 view->scrollbarsNeedingUpdate--;
4254 NSTRACE ("ns_set_vertical_scroll_bar");
4256 /* Get dimensions. */
4257 window_box (window, ANY_AREA, 0, &window_y, 0, &window_height);
4259 height = window_height;
4260 width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
4261 left = WINDOW_SCROLL_BAR_AREA_X (window);
4263 r = NSMakeRect (left, top, width, height);
4264 /* the parent view is flipped, so we need to flip y value */
4266 r.origin.y = (v.size.height - r.size.height - r.origin.y);
4268 XSETWINDOW (win, window);
4271 /* we want at least 5 lines to display a scrollbar */
4272 if (WINDOW_TOTAL_LINES (window) < 5)
4274 if (!NILP (window->vertical_scroll_bar))
4276 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4277 [bar removeFromSuperview];
4278 wset_vertical_scroll_bar (window, Qnil);
4281 ns_clear_frame_area (f, left, top, width, height);
4286 if (NILP (window->vertical_scroll_bar))
4288 if (width > 0 && height > 0)
4289 ns_clear_frame_area (f, left, top, width, height);
4291 bar = [[EmacsScroller alloc] initFrame: r window: win];
4292 wset_vertical_scroll_bar (window, make_save_ptr (bar));
4298 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4299 oldRect = [bar frame];
4300 r.size.width = oldRect.size.width;
4301 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4303 if (oldRect.origin.x != r.origin.x)
4304 ns_clear_frame_area (f, left, top, width, height);
4310 [bar setPosition: position portion: portion whole: whole];
4316 ns_set_horizontal_scroll_bar (struct window *window,
4317 int portion, int whole, int position)
4318 /* --------------------------------------------------------------------------
4319 External (hook): Update or add scrollbar
4320 -------------------------------------------------------------------------- */
4324 struct frame *f = XFRAME (WINDOW_FRAME (window));
4325 EmacsView *view = FRAME_NS_VIEW (f);
4327 int top, height, left, width;
4328 int window_x, window_width;
4329 BOOL update_p = YES;
4331 /* optimization; display engine sends WAY too many of these.. */
4332 if (!NILP (window->horizontal_scroll_bar))
4334 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4335 if ([bar checkSamePosition: position portion: portion whole: whole])
4337 if (view->scrollbarsNeedingUpdate == 0)
4339 if (!windows_or_buffers_changed)
4343 view->scrollbarsNeedingUpdate--;
4348 NSTRACE ("ns_set_horizontal_scroll_bar");
4350 /* Get dimensions. */
4351 window_box (window, ANY_AREA, 0, &window_x, &window_width, 0);
4353 width = window_width;
4354 height = WINDOW_CONFIG_SCROLL_BAR_LINES (window) * FRAME_LINE_HEIGHT (f);
4355 top = WINDOW_SCROLL_BAR_AREA_Y (window);
4357 r = NSMakeRect (left, top, width, height);
4358 /* the parent view is flipped, so we need to flip y value */
4360 /* ??????? PXW/scrollbars !!!!!!!!!!!!!!!!!!!! */
4361 r.origin.y = (v.size.height - r.size.height - r.origin.y);
4363 XSETWINDOW (win, window);
4366 if (WINDOW_TOTAL_COLS (window) < 5)
4368 if (!NILP (window->horizontal_scroll_bar))
4370 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4371 [bar removeFromSuperview];
4372 wset_horizontal_scroll_bar (window, Qnil);
4374 ns_clear_frame_area (f, left, top, width, height);
4379 if (NILP (window->horizontal_scroll_bar))
4381 if (width > 0 && height > 0)
4382 ns_clear_frame_area (f, left, top, width, height);
4384 bar = [[EmacsScroller alloc] initFrame: r window: win];
4385 wset_horizontal_scroll_bar (window, make_save_ptr (bar));
4391 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4392 oldRect = [bar frame];
4393 r.size.width = oldRect.size.width;
4394 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4396 if (oldRect.origin.x != r.origin.x)
4397 ns_clear_frame_area (f, left, top, width, height);
4404 [bar setPosition: position portion: portion whole: whole];
4410 ns_condemn_scroll_bars (struct frame *f)
4411 /* --------------------------------------------------------------------------
4412 External (hook): arrange for all frame's scrollbars to be removed
4413 at next call to judge_scroll_bars, except for those redeemed.
4414 -------------------------------------------------------------------------- */
4418 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
4420 NSTRACE ("ns_condemn_scroll_bars");
4422 for (i =[subviews count]-1; i >= 0; i--)
4424 view = [subviews objectAtIndex: i];
4425 if ([view isKindOfClass: [EmacsScroller class]])
4432 ns_redeem_scroll_bar (struct window *window)
4433 /* --------------------------------------------------------------------------
4434 External (hook): arrange to spare this window's scrollbar
4435 at next call to judge_scroll_bars.
4436 -------------------------------------------------------------------------- */
4439 NSTRACE ("ns_redeem_scroll_bar");
4440 if (!NILP (window->vertical_scroll_bar))
4442 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4446 if (!NILP (window->horizontal_scroll_bar))
4448 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4455 ns_judge_scroll_bars (struct frame *f)
4456 /* --------------------------------------------------------------------------
4457 External (hook): destroy all scrollbars on frame that weren't
4458 redeemed after call to condemn_scroll_bars.
4459 -------------------------------------------------------------------------- */
4463 EmacsView *eview = FRAME_NS_VIEW (f);
4464 NSArray *subviews = [[eview superview] subviews];
4467 NSTRACE ("ns_judge_scroll_bars");
4468 for (i = [subviews count]-1; i >= 0; --i)
4470 view = [subviews objectAtIndex: i];
4471 if (![view isKindOfClass: [EmacsScroller class]]) continue;
4477 [eview updateFrameSize: NO];
4480 /* ==========================================================================
4484 ========================================================================== */
4487 x_display_pixel_height (struct ns_display_info *dpyinfo)
4489 NSArray *screens = [NSScreen screens];
4490 NSEnumerator *enumerator = [screens objectEnumerator];
4495 while ((screen = [enumerator nextObject]) != nil)
4496 frame = NSUnionRect (frame, [screen frame]);
4498 return NSHeight (frame);
4502 x_display_pixel_width (struct ns_display_info *dpyinfo)
4504 NSArray *screens = [NSScreen screens];
4505 NSEnumerator *enumerator = [screens objectEnumerator];
4510 while ((screen = [enumerator nextObject]) != nil)
4511 frame = NSUnionRect (frame, [screen frame]);
4513 return NSWidth (frame);
4517 static Lisp_Object ns_string_to_lispmod (const char *s)
4518 /* --------------------------------------------------------------------------
4519 Convert modifier name to lisp symbol
4520 -------------------------------------------------------------------------- */
4522 if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
4524 else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
4526 else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
4528 else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
4530 else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
4532 else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
4540 ns_default (const char *parameter, Lisp_Object *result,
4541 Lisp_Object yesval, Lisp_Object noval,
4542 BOOL is_float, BOOL is_modstring)
4543 /* --------------------------------------------------------------------------
4544 Check a parameter value in user's preferences
4545 -------------------------------------------------------------------------- */
4547 const char *value = ns_get_defaults_value (parameter);
4553 if (c_strcasecmp (value, "YES") == 0)
4555 else if (c_strcasecmp (value, "NO") == 0)
4557 else if (is_float && (f = strtod (value, &pos), pos != value))
4558 *result = make_float (f);
4559 else if (is_modstring && value)
4560 *result = ns_string_to_lispmod (value);
4561 else fprintf (stderr,
4562 "Bad value for default \"%s\": \"%s\"\n", parameter, value);
4568 ns_initialize_display_info (struct ns_display_info *dpyinfo)
4569 /* --------------------------------------------------------------------------
4570 Initialize global info and storage for display.
4571 -------------------------------------------------------------------------- */
4573 NSScreen *screen = [NSScreen mainScreen];
4574 NSWindowDepth depth = [screen depth];
4576 dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
4577 dpyinfo->resy = 72.27;
4578 dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
4579 NSColorSpaceFromDepth (depth)]
4580 && ![NSCalibratedWhiteColorSpace isEqualToString:
4581 NSColorSpaceFromDepth (depth)];
4582 dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
4583 dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
4584 dpyinfo->color_table->colors = NULL;
4585 dpyinfo->root_window = 42; /* a placeholder.. */
4586 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
4587 dpyinfo->n_fonts = 0;
4588 dpyinfo->smallest_font_height = 1;
4589 dpyinfo->smallest_char_width = 1;
4591 reset_mouse_highlight (&dpyinfo->mouse_highlight);
4595 /* This and next define (many of the) public functions in this file. */
4596 /* x_... are generic versions in xdisp.c that we, and other terms, get away
4597 with using despite presence in the "system dependent" redisplay
4598 interface. In addition, many of the ns_ methods have code that is
4599 shared with all terms, indicating need for further refactoring. */
4600 extern frame_parm_handler ns_frame_parm_handlers[];
4601 static struct redisplay_interface ns_redisplay_interface =
4603 ns_frame_parm_handlers,
4607 x_clear_end_of_line,
4609 ns_after_update_window_line,
4610 ns_update_window_begin,
4611 ns_update_window_end,
4612 0, /* flush_display */
4613 x_clear_window_mouse_face,
4614 x_get_glyph_overhangs,
4615 x_fix_overlapping_area,
4616 ns_draw_fringe_bitmap,
4617 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
4618 0, /* destroy_fringe_bitmap */
4619 ns_compute_glyph_string_overhangs,
4620 ns_draw_glyph_string,
4621 ns_define_frame_cursor,
4622 ns_clear_frame_area,
4623 ns_draw_window_cursor,
4624 ns_draw_vertical_window_border,
4625 ns_draw_window_divider,
4626 ns_shift_glyphs_for_insert,
4633 ns_delete_display (struct ns_display_info *dpyinfo)
4639 /* This function is called when the last frame on a display is deleted. */
4641 ns_delete_terminal (struct terminal *terminal)
4643 struct ns_display_info *dpyinfo = terminal->display_info.ns;
4645 NSTRACE ("ns_delete_terminal");
4647 /* Protect against recursive calls. delete_frame in
4648 delete_terminal calls us back when it deletes our last frame. */
4649 if (!terminal->name)
4654 x_destroy_all_bitmaps (dpyinfo);
4655 ns_delete_display (dpyinfo);
4660 static struct terminal *
4661 ns_create_terminal (struct ns_display_info *dpyinfo)
4662 /* --------------------------------------------------------------------------
4663 Set up use of NS before we make the first connection.
4664 -------------------------------------------------------------------------- */
4666 struct terminal *terminal;
4668 NSTRACE ("ns_create_terminal");
4670 terminal = create_terminal (output_ns, &ns_redisplay_interface);
4672 terminal->display_info.ns = dpyinfo;
4673 dpyinfo->terminal = terminal;
4675 terminal->clear_frame_hook = ns_clear_frame;
4676 terminal->ring_bell_hook = ns_ring_bell;
4677 terminal->update_begin_hook = ns_update_begin;
4678 terminal->update_end_hook = ns_update_end;
4679 terminal->read_socket_hook = ns_read_socket;
4680 terminal->frame_up_to_date_hook = ns_frame_up_to_date;
4681 terminal->mouse_position_hook = ns_mouse_position;
4682 terminal->frame_rehighlight_hook = ns_frame_rehighlight;
4683 terminal->frame_raise_lower_hook = ns_frame_raise_lower;
4684 terminal->fullscreen_hook = ns_fullscreen_hook;
4685 terminal->menu_show_hook = ns_menu_show;
4686 terminal->popup_dialog_hook = ns_popup_dialog;
4687 terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
4688 terminal->set_horizontal_scroll_bar_hook = ns_set_horizontal_scroll_bar;
4689 terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
4690 terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
4691 terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
4692 terminal->delete_frame_hook = x_destroy_window;
4693 terminal->delete_terminal_hook = ns_delete_terminal;
4694 /* Other hooks are NULL by default. */
4700 struct ns_display_info *
4701 ns_term_init (Lisp_Object display_name)
4702 /* --------------------------------------------------------------------------
4703 Start the Application and get things rolling.
4704 -------------------------------------------------------------------------- */
4706 struct terminal *terminal;
4707 struct ns_display_info *dpyinfo;
4708 static int ns_initialized = 0;
4711 if (ns_initialized) return x_display_list;
4716 NSTRACE ("ns_term_init");
4718 [outerpool release];
4719 outerpool = [[NSAutoreleasePool alloc] init];
4721 /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4722 /*GSDebugAllocationActive (YES); */
4726 Fset_input_interrupt_mode (Qnil);
4728 if (selfds[0] == -1)
4730 if (emacs_pipe (selfds) != 0)
4732 fprintf (stderr, "Failed to create pipe: %s\n",
4733 emacs_strerror (errno));
4737 fcntl (selfds[0], F_SETFL, O_NONBLOCK|fcntl (selfds[0], F_GETFL));
4738 FD_ZERO (&select_readfds);
4739 FD_ZERO (&select_writefds);
4740 pthread_mutex_init (&select_mutex, NULL);
4743 ns_pending_files = [[NSMutableArray alloc] init];
4744 ns_pending_service_names = [[NSMutableArray alloc] init];
4745 ns_pending_service_args = [[NSMutableArray alloc] init];
4747 /* Start app and create the main menu, window, view.
4748 Needs to be here because ns_initialize_display_info () uses AppKit classes.
4749 The view will then ask the NSApp to stop and return to Emacs. */
4750 [EmacsApp sharedApplication];
4753 [NSApp setDelegate: NSApp];
4755 /* Start the select thread. */
4756 [NSThread detachNewThreadSelector:@selector (fd_handler:)
4760 /* debugging: log all notifications */
4761 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
4762 selector: @selector (logNotification:)
4763 name: nil object: nil]; */
4765 dpyinfo = xzalloc (sizeof *dpyinfo);
4767 ns_initialize_display_info (dpyinfo);
4768 terminal = ns_create_terminal (dpyinfo);
4770 terminal->kboard = allocate_kboard (Qns);
4771 /* Don't let the initial kboard remain current longer than necessary.
4772 That would cause problems if a file loaded on startup tries to
4773 prompt in the mini-buffer. */
4774 if (current_kboard == initial_kboard)
4775 current_kboard = terminal->kboard;
4776 terminal->kboard->reference_count++;
4778 dpyinfo->next = x_display_list;
4779 x_display_list = dpyinfo;
4781 dpyinfo->name_list_element = Fcons (display_name, Qnil);
4783 terminal->name = xlispstrdup (display_name);
4787 if (!inhibit_x_resources)
4789 ns_default ("GSFontAntiAlias", &ns_antialias_text,
4792 /* this is a standard variable */
4793 ns_default ("AppleAntiAliasingThreshold", &tmp,
4794 make_float (10.0), make_float (6.0), YES, NO);
4795 ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4798 NSTRACE_MSG ("Colors");
4801 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4805 Lisp_Object color_file, color_map, color;
4809 color_file = Fexpand_file_name (build_string ("rgb.txt"),
4810 Fsymbol_value (intern ("data-directory")));
4812 color_map = Fx_load_color_file (color_file);
4813 if (NILP (color_map))
4814 fatal ("Could not read %s.\n", SDATA (color_file));
4816 cl = [[NSColorList alloc] initWithName: @"Emacs"];
4817 for ( ; CONSP (color_map); color_map = XCDR (color_map))
4819 color = XCAR (color_map);
4820 name = SSDATA (XCAR (color));
4821 c = XINT (XCDR (color));
4823 [NSColor colorForEmacsRed: RED_FROM_ULONG (c) / 255.0
4824 green: GREEN_FROM_ULONG (c) / 255.0
4825 blue: BLUE_FROM_ULONG (c) / 255.0
4827 forKey: [NSString stringWithUTF8String: name]];
4829 [cl writeToFile: nil];
4833 NSTRACE_MSG ("Versions");
4836 #ifdef NS_IMPL_GNUSTEP
4837 Vwindow_system_version = build_string (gnustep_base_version);
4839 /*PSnextrelease (128, c); */
4840 char c[DBL_BUFSIZE_BOUND];
4841 int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4842 Vwindow_system_version = make_unibyte_string (c, len);
4846 delete_keyboard_wait_descriptor (0);
4848 ns_app_name = [[NSProcessInfo processInfo] processName];
4850 /* Set up OS X app menu */
4852 NSTRACE_MSG ("Menu init");
4854 #ifdef NS_IMPL_COCOA
4858 /* set up the application menu */
4859 svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4860 [svcsMenu setAutoenablesItems: NO];
4861 appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4862 [appMenu setAutoenablesItems: NO];
4863 mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4864 dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4866 [appMenu insertItemWithTitle: @"About Emacs"
4867 action: @selector (orderFrontStandardAboutPanel:)
4870 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4871 [appMenu insertItemWithTitle: @"Preferences..."
4872 action: @selector (showPreferencesWindow:)
4875 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4876 item = [appMenu insertItemWithTitle: @"Services"
4877 action: @selector (menuDown:)
4880 [appMenu setSubmenu: svcsMenu forItem: item];
4881 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4882 [appMenu insertItemWithTitle: @"Hide Emacs"
4883 action: @selector (hide:)
4886 item = [appMenu insertItemWithTitle: @"Hide Others"
4887 action: @selector (hideOtherApplications:)
4890 [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4891 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4892 [appMenu insertItemWithTitle: @"Quit Emacs"
4893 action: @selector (terminate:)
4897 item = [mainMenu insertItemWithTitle: ns_app_name
4898 action: @selector (menuDown:)
4901 [mainMenu setSubmenu: appMenu forItem: item];
4902 [dockMenu insertItemWithTitle: @"New Frame"
4903 action: @selector (newFrame:)
4907 [NSApp setMainMenu: mainMenu];
4908 [NSApp setAppleMenu: appMenu];
4909 [NSApp setServicesMenu: svcsMenu];
4910 /* Needed at least on Cocoa, to get dock menu to show windows */
4911 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4913 [[NSNotificationCenter defaultCenter]
4914 addObserver: mainMenu
4915 selector: @selector (trackingNotification:)
4916 name: NSMenuDidBeginTrackingNotification object: mainMenu];
4917 [[NSNotificationCenter defaultCenter]
4918 addObserver: mainMenu
4919 selector: @selector (trackingNotification:)
4920 name: NSMenuDidEndTrackingNotification object: mainMenu];
4922 #endif /* MAC OS X menu setup */
4924 /* Register our external input/output types, used for determining
4925 applicable services and also drag/drop eligibility. */
4927 NSTRACE_MSG ("Input/output types");
4929 ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
4930 ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
4932 ns_drag_types = [[NSArray arrayWithObjects:
4934 NSTabularTextPboardType,
4935 NSFilenamesPboardType,
4936 NSURLPboardType, nil] retain];
4938 /* If fullscreen is in init/default-frame-alist, focus isn't set
4939 right for fullscreen windows, so set this. */
4940 [NSApp activateIgnoringOtherApps:YES];
4942 NSTRACE_MSG ("Call NSApp run");
4945 ns_do_open_file = YES;
4947 #ifdef NS_IMPL_GNUSTEP
4948 /* GNUstep steals SIGCHLD for use in NSTask, but we don't use NSTask.
4949 We must re-catch it so subprocess works. */
4950 catch_child_signal ();
4953 NSTRACE_MSG ("ns_term_init done");
4962 ns_term_shutdown (int sig)
4964 [[NSUserDefaults standardUserDefaults] synchronize];
4966 /* code not reached in emacs.c after this is called by shut_down_emacs: */
4967 if (STRINGP (Vauto_save_list_file_name))
4968 unlink (SSDATA (Vauto_save_list_file_name));
4970 if (sig == 0 || sig == SIGTERM)
4972 [NSApp terminate: NSApp];
4974 else // force a stack trace to happen
4981 /* ==========================================================================
4983 EmacsApp implementation
4985 ========================================================================== */
4988 @implementation EmacsApp
4992 NSTRACE ("[EmacsApp init]");
4994 if ((self = [super init]))
4996 #ifdef NS_IMPL_COCOA
4997 self->isFirst = YES;
4999 #ifdef NS_IMPL_GNUSTEP
5000 self->applicationDidFinishLaunchingCalled = NO;
5007 #ifdef NS_IMPL_COCOA
5010 NSTRACE ("[EmacsApp run]");
5012 #ifndef NSAppKitVersionNumber10_9
5013 #define NSAppKitVersionNumber10_9 1265
5016 if ((int)NSAppKitVersionNumber != NSAppKitVersionNumber10_9)
5022 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
5024 if (isFirst) [self finishLaunching];
5027 shouldKeepRunning = YES;
5031 pool = [[NSAutoreleasePool alloc] init];
5034 [self nextEventMatchingMask:NSAnyEventMask
5035 untilDate:[NSDate distantFuture]
5036 inMode:NSDefaultRunLoopMode
5039 [self sendEvent:event];
5040 [self updateWindows];
5041 } while (shouldKeepRunning);
5046 - (void)stop: (id)sender
5048 NSTRACE ("[EmacsApp stop:]");
5050 shouldKeepRunning = NO;
5051 // Stop possible dialog also. Noop if no dialog present.
5052 // The file dialog still leaks 7k - 10k on 10.9 though.
5053 [super stop:sender];
5055 #endif /* NS_IMPL_COCOA */
5057 - (void)logNotification: (NSNotification *)notification
5059 NSTRACE ("[EmacsApp logNotification:]");
5061 const char *name = [[notification name] UTF8String];
5062 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
5063 && !strstr (name, "WindowNumber"))
5064 NSLog (@"notification: '%@'", [notification name]);
5068 - (void)sendEvent: (NSEvent *)theEvent
5069 /* --------------------------------------------------------------------------
5070 Called when NSApp is running for each event received. Used to stop
5071 the loop when we choose, since there's no way to just run one iteration.
5072 -------------------------------------------------------------------------- */
5074 int type = [theEvent type];
5075 NSWindow *window = [theEvent window];
5077 NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "[EmacsApp sendEvent:]");
5078 NSTRACE_MSG ("Type: %d", type);
5080 #ifdef NS_IMPL_GNUSTEP
5081 // Keyboard events aren't propagated to file dialogs for some reason.
5082 if ([NSApp modalWindow] != nil &&
5083 (type == NSKeyDown || type == NSKeyUp || type == NSFlagsChanged))
5085 [[NSApp modalWindow] sendEvent: theEvent];
5090 if (represented_filename != nil && represented_frame)
5092 NSString *fstr = represented_filename;
5093 NSView *view = FRAME_NS_VIEW (represented_frame);
5094 #ifdef NS_IMPL_COCOA
5095 /* work around a bug observed on 10.3 and later where
5096 setTitleWithRepresentedFilename does not clear out previous state
5097 if given filename does not exist */
5098 if (! [[NSFileManager defaultManager] fileExistsAtPath: fstr])
5099 [[view window] setRepresentedFilename: @""];
5101 [[view window] setRepresentedFilename: fstr];
5102 [represented_filename release];
5103 represented_filename = nil;
5104 represented_frame = NULL;
5107 if (type == NSApplicationDefined)
5109 switch ([theEvent data2])
5111 #ifdef NS_IMPL_COCOA
5112 case NSAPP_DATA2_RUNASSCRIPT:
5117 case NSAPP_DATA2_RUNFILEDIALOG:
5118 ns_run_file_dialog ();
5124 if (type == NSCursorUpdate && window == nil)
5126 fprintf (stderr, "Dropping external cursor update event.\n");
5130 if (type == NSApplicationDefined)
5132 /* Events posted by ns_send_appdefined interrupt the run loop here.
5133 But, if a modal window is up, an appdefined can still come through,
5134 (e.g., from a makeKeyWindow event) but stopping self also stops the
5135 modal loop. Just defer it until later. */
5136 if ([NSApp modalWindow] == nil)
5138 last_appdefined_event_data = [theEvent data1];
5143 send_appdefined = YES;
5148 #ifdef NS_IMPL_COCOA
5149 /* If no dialog and none of our frames have focus and it is a move, skip it.
5150 It is a mouse move in an auxiliary menu, i.e. on the top right on OSX,
5151 such as Wifi, sound, date or similar.
5152 This prevents "spooky" highlighting in the frame under the menu. */
5153 if (type == NSMouseMoved && [NSApp modalWindow] == nil)
5155 struct ns_display_info *di;
5156 BOOL has_focus = NO;
5157 for (di = x_display_list; ! has_focus && di; di = di->next)
5158 has_focus = di->x_focus_frame != 0;
5164 NSTRACE_UNSILENCE();
5166 [super sendEvent: theEvent];
5170 - (void)showPreferencesWindow: (id)sender
5172 struct frame *emacsframe = SELECTED_FRAME ();
5173 NSEvent *theEvent = [NSApp currentEvent];
5177 emacs_event->kind = NS_NONKEY_EVENT;
5178 emacs_event->code = KEY_NS_SHOW_PREFS;
5179 emacs_event->modifiers = 0;
5180 EV_TRAILER (theEvent);
5184 - (void)newFrame: (id)sender
5186 NSTRACE ("[EmacsApp newFrame:]");
5188 struct frame *emacsframe = SELECTED_FRAME ();
5189 NSEvent *theEvent = [NSApp currentEvent];
5193 emacs_event->kind = NS_NONKEY_EVENT;
5194 emacs_event->code = KEY_NS_NEW_FRAME;
5195 emacs_event->modifiers = 0;
5196 EV_TRAILER (theEvent);
5200 /* Open a file (used by below, after going into queue read by ns_read_socket) */
5201 - (BOOL) openFile: (NSString *)fileName
5203 NSTRACE ("[EmacsApp openFile:]");
5205 struct frame *emacsframe = SELECTED_FRAME ();
5206 NSEvent *theEvent = [NSApp currentEvent];
5211 emacs_event->kind = NS_NONKEY_EVENT;
5212 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
5213 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
5214 ns_input_line = Qnil; /* can be start or cons start,end */
5215 emacs_event->modifiers =0;
5216 EV_TRAILER (theEvent);
5222 /* **************************************************************************
5224 EmacsApp delegate implementation
5226 ************************************************************************** */
5228 - (void)applicationDidFinishLaunching: (NSNotification *)notification
5229 /* --------------------------------------------------------------------------
5230 When application is loaded, terminate event loop in ns_term_init
5231 -------------------------------------------------------------------------- */
5233 NSTRACE ("[EmacsApp applicationDidFinishLaunching:]");
5235 #ifdef NS_IMPL_GNUSTEP
5236 ((EmacsApp *)self)->applicationDidFinishLaunchingCalled = YES;
5238 [NSApp setServicesProvider: NSApp];
5240 [self antialiasThresholdDidChange:nil];
5241 #ifdef NS_IMPL_COCOA
5242 [[NSNotificationCenter defaultCenter]
5244 selector:@selector(antialiasThresholdDidChange:)
5245 name:NSAntialiasThresholdChangedNotification
5249 ns_send_appdefined (-2);
5252 - (void)antialiasThresholdDidChange:(NSNotification *)notification
5254 #ifdef NS_IMPL_COCOA
5255 macfont_update_antialias_threshold ();
5260 /* Termination sequences:
5263 MenuBar | File | Exit:
5264 Select Quit from App menubar:
5266 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5269 Select Quit from Dock menu:
5272 Cancel -> Nothing else
5276 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5281 - (void) terminate: (id)sender
5283 NSTRACE ("[EmacsApp terminate:]");
5285 struct frame *emacsframe = SELECTED_FRAME ();
5290 emacs_event->kind = NS_NONKEY_EVENT;
5291 emacs_event->code = KEY_NS_POWER_OFF;
5292 emacs_event->arg = Qt; /* mark as non-key event */
5293 EV_TRAILER ((id)nil);
5297 runAlertPanel(NSString *title,
5298 NSString *msgFormat,
5299 NSString *defaultButton,
5300 NSString *alternateButton)
5302 #if !defined (NS_IMPL_COCOA) || \
5303 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
5304 return NSRunAlertPanel(title, msgFormat, defaultButton, alternateButton, nil)
5305 == NSAlertDefaultReturn;
5307 NSAlert *alert = [[NSAlert alloc] init];
5308 [alert setAlertStyle: NSCriticalAlertStyle];
5309 [alert setMessageText: msgFormat];
5310 [alert addButtonWithTitle: defaultButton];
5311 [alert addButtonWithTitle: alternateButton];
5312 NSInteger ret = [alert runModal];
5314 return ret == NSAlertFirstButtonReturn;
5319 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
5321 NSTRACE ("[EmacsApp applicationShouldTerminate:]");
5325 if (NILP (ns_confirm_quit)) // || ns_shutdown_properly --> TO DO
5326 return NSTerminateNow;
5328 ret = runAlertPanel(ns_app_name,
5329 @"Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?",
5330 @"Save Buffers and Exit", @"Cancel");
5333 return NSTerminateNow;
5335 return NSTerminateCancel;
5336 return NSTerminateNow; /* just in case */
5340 not_in_argv (NSString *arg)
5343 const char *a = [arg UTF8String];
5344 for (k = 1; k < initial_argc; ++k)
5345 if (strcmp (a, initial_argv[k]) == 0) return 0;
5349 /* Notification from the Workspace to open a file */
5350 - (BOOL)application: sender openFile: (NSString *)file
5352 if (ns_do_open_file || not_in_argv (file))
5353 [ns_pending_files addObject: file];
5358 /* Open a file as a temporary file */
5359 - (BOOL)application: sender openTempFile: (NSString *)file
5361 if (ns_do_open_file || not_in_argv (file))
5362 [ns_pending_files addObject: file];
5367 /* Notification from the Workspace to open a file noninteractively (?) */
5368 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
5370 if (ns_do_open_file || not_in_argv (file))
5371 [ns_pending_files addObject: file];
5375 /* Notification from the Workspace to open multiple files */
5376 - (void)application: sender openFiles: (NSArray *)fileList
5378 NSEnumerator *files = [fileList objectEnumerator];
5380 /* Don't open files from the command line unconditionally,
5381 Cocoa parses the command line wrong, --option value tries to open value
5382 if --option is the last option. */
5383 while ((file = [files nextObject]) != nil)
5384 if (ns_do_open_file || not_in_argv (file))
5385 [ns_pending_files addObject: file];
5387 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
5392 /* Handle dock menu requests. */
5393 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
5399 /* TODO: these may help w/IO switching btwn terminal and NSApp */
5400 - (void)applicationWillBecomeActive: (NSNotification *)notification
5402 NSTRACE ("[EmacsApp applicationWillBecomeActive:]");
5403 //ns_app_active=YES;
5406 - (void)applicationDidBecomeActive: (NSNotification *)notification
5408 NSTRACE ("[EmacsApp applicationDidBecomeActive:]");
5410 #ifdef NS_IMPL_GNUSTEP
5411 if (! applicationDidFinishLaunchingCalled)
5412 [self applicationDidFinishLaunching:notification];
5414 //ns_app_active=YES;
5416 ns_update_auto_hide_menu_bar ();
5417 // No constraining takes place when the application is not active.
5418 ns_constrain_all_frames ();
5420 - (void)applicationDidResignActive: (NSNotification *)notification
5422 NSTRACE ("[EmacsApp applicationDidResignActive:]");
5425 ns_send_appdefined (-1);
5430 /* ==========================================================================
5432 EmacsApp aux handlers for managing event loop
5434 ========================================================================== */
5437 - (void)timeout_handler: (NSTimer *)timedEntry
5438 /* --------------------------------------------------------------------------
5439 The timeout specified to ns_select has passed.
5440 -------------------------------------------------------------------------- */
5442 /*NSTRACE ("timeout_handler"); */
5443 ns_send_appdefined (-2);
5446 #ifdef NS_IMPL_GNUSTEP
5447 - (void)sendFromMainThread:(id)unused
5449 ns_send_appdefined (nextappdefined);
5453 - (void)fd_handler:(id)unused
5454 /* --------------------------------------------------------------------------
5455 Check data waiting on file descriptors and terminate if so
5456 -------------------------------------------------------------------------- */
5459 int waiting = 1, nfds;
5462 fd_set readfds, writefds, *wfds;
5463 struct timespec timeout, *tmo;
5464 NSAutoreleasePool *pool = nil;
5466 /* NSTRACE ("fd_handler"); */
5471 pool = [[NSAutoreleasePool alloc] init];
5477 FD_SET (selfds[0], &fds);
5478 result = select (selfds[0]+1, &fds, NULL, NULL, NULL);
5479 if (result > 0 && read (selfds[0], &c, 1) == 1 && c == 'g')
5484 pthread_mutex_lock (&select_mutex);
5487 if (select_valid & SELECT_HAVE_READ)
5488 readfds = select_readfds;
5492 if (select_valid & SELECT_HAVE_WRITE)
5494 writefds = select_writefds;
5499 if (select_valid & SELECT_HAVE_TMO)
5501 timeout = select_timeout;
5507 pthread_mutex_unlock (&select_mutex);
5509 FD_SET (selfds[0], &readfds);
5510 if (selfds[0] >= nfds) nfds = selfds[0]+1;
5512 result = pselect (nfds, &readfds, wfds, NULL, tmo, NULL);
5515 ns_send_appdefined (-2);
5516 else if (result > 0)
5518 if (FD_ISSET (selfds[0], &readfds))
5520 if (read (selfds[0], &c, 1) == 1 && c == 's')
5525 pthread_mutex_lock (&select_mutex);
5526 if (select_valid & SELECT_HAVE_READ)
5527 select_readfds = readfds;
5528 if (select_valid & SELECT_HAVE_WRITE)
5529 select_writefds = writefds;
5530 if (select_valid & SELECT_HAVE_TMO)
5531 select_timeout = timeout;
5532 pthread_mutex_unlock (&select_mutex);
5534 ns_send_appdefined (result);
5544 /* ==========================================================================
5548 ========================================================================== */
5550 /* called from system: queue for next pass through event loop */
5551 - (void)requestService: (NSPasteboard *)pboard
5552 userData: (NSString *)userData
5553 error: (NSString **)error
5555 [ns_pending_service_names addObject: userData];
5556 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
5557 SSDATA (ns_string_from_pasteboard (pboard))]];
5561 /* called from ns_read_socket to clear queue */
5562 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
5564 struct frame *emacsframe = SELECTED_FRAME ();
5565 NSEvent *theEvent = [NSApp currentEvent];
5567 NSTRACE ("[EmacsApp fulfillService:withArg:]");
5572 emacs_event->kind = NS_NONKEY_EVENT;
5573 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
5574 ns_input_spi_name = build_string ([name UTF8String]);
5575 ns_input_spi_arg = build_string ([arg UTF8String]);
5576 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5577 EV_TRAILER (theEvent);
5587 /* ==========================================================================
5589 EmacsView implementation
5591 ========================================================================== */
5594 @implementation EmacsView
5596 /* needed to inform when window closed from LISP */
5597 - (void) setWindowClosing: (BOOL)closing
5599 NSTRACE ("[EmacsView setWindowClosing:%d]", closing);
5601 windowClosing = closing;
5607 NSTRACE ("[EmacsView dealloc]");
5609 if (fs_state == FULLSCREEN_BOTH)
5610 [nonfs_window release];
5615 /* called on font panel selection */
5616 - (void)changeFont: (id)sender
5618 NSEvent *e = [[self window] currentEvent];
5619 struct face *face = FRAME_DEFAULT_FACE (emacsframe);
5620 struct font *font = face->font;
5625 NSTRACE ("[EmacsView changeFont:]");
5630 #ifdef NS_IMPL_GNUSTEP
5631 nsfont = ((struct nsfont_info *)font)->nsfont;
5633 #ifdef NS_IMPL_COCOA
5634 nsfont = (NSFont *) macfont_get_nsctfont (font);
5637 if ((newFont = [sender convertFont: nsfont]))
5639 SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
5641 emacs_event->kind = NS_NONKEY_EVENT;
5642 emacs_event->modifiers = 0;
5643 emacs_event->code = KEY_NS_CHANGE_FONT;
5645 size = [newFont pointSize];
5646 ns_input_fontsize = make_number (lrint (size));
5647 ns_input_font = build_string ([[newFont familyName] UTF8String]);
5653 - (BOOL)acceptsFirstResponder
5655 NSTRACE ("[EmacsView acceptsFirstResponder]");
5660 - (void)resetCursorRects
5662 NSRect visible = [self visibleRect];
5663 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
5664 NSTRACE ("[EmacsView resetCursorRects]");
5666 if (currentCursor == nil)
5667 currentCursor = [NSCursor arrowCursor];
5669 if (!NSIsEmptyRect (visible))
5670 [self addCursorRect: visible cursor: currentCursor];
5671 [currentCursor setOnMouseEntered: YES];
5676 /*****************************************************************************/
5677 /* Keyboard handling. */
5680 - (void)keyDown: (NSEvent *)theEvent
5682 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5684 unsigned fnKeysym = 0;
5685 static NSMutableArray *nsEvArray;
5687 unsigned int flags = [theEvent modifierFlags];
5689 NSTRACE ("[EmacsView keyDown:]");
5691 /* Rhapsody and OS X give up and down events for the arrow keys */
5692 if (ns_fake_keydown == YES)
5693 ns_fake_keydown = NO;
5694 else if ([theEvent type] != NSKeyDown)
5700 if (![[self window] isKeyWindow]
5701 && [[theEvent window] isKindOfClass: [EmacsWindow class]]
5702 /* we must avoid an infinite loop here. */
5703 && (EmacsView *)[[theEvent window] delegate] != self)
5705 /* XXX: There is an occasional condition in which, when Emacs display
5706 updates a different frame from the current one, and temporarily
5707 selects it, then processes some interrupt-driven input
5708 (dispnew.c:3878), OS will send the event to the correct NSWindow, but
5709 for some reason that window has its first responder set to the NSView
5710 most recently updated (I guess), which is not the correct one. */
5711 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
5715 if (nsEvArray == nil)
5716 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
5718 [NSCursor setHiddenUntilMouseMoves: YES];
5720 if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
5722 clear_mouse_face (hlinfo);
5723 hlinfo->mouse_face_hidden = 1;
5726 if (!processingCompose)
5728 /* When using screen sharing, no left or right information is sent,
5729 so use Left key in those cases. */
5730 int is_left_key, is_right_key;
5732 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
5733 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
5735 /* (Carbon way: [theEvent keyCode]) */
5737 /* is it a "function key"? */
5738 /* Note: Sometimes a plain key will have the NSNumericPadKeyMask
5739 flag set (this is probably a bug in the OS).
5741 if (code < 0x00ff && (flags&NSNumericPadKeyMask))
5743 fnKeysym = ns_convert_key ([theEvent keyCode] | NSNumericPadKeyMask);
5747 fnKeysym = ns_convert_key (code);
5752 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
5753 because Emacs treats Delete and KP-Delete same (in simple.el). */
5754 if ((fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
5755 #ifdef NS_IMPL_GNUSTEP
5756 /* GNUstep uses incompatible keycodes, even for those that are
5757 supposed to be hardware independent. Just check for delete.
5758 Keypad delete does not have keysym 0xFFFF.
5759 See http://savannah.gnu.org/bugs/?25395
5761 || (fnKeysym == 0xFFFF && code == 127)
5764 code = 0xFF08; /* backspace */
5769 /* are there modifiers? */
5770 emacs_event->modifiers = 0;
5772 if (flags & NSHelpKeyMask)
5773 emacs_event->modifiers |= hyper_modifier;
5775 if (flags & NSShiftKeyMask)
5776 emacs_event->modifiers |= shift_modifier;
5778 is_right_key = (flags & NSRightCommandKeyMask) == NSRightCommandKeyMask;
5779 is_left_key = (flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask
5780 || (! is_right_key && (flags & NSCommandKeyMask) == NSCommandKeyMask);
5783 emacs_event->modifiers |= parse_solitary_modifier
5784 (EQ (ns_right_command_modifier, Qleft)
5785 ? ns_command_modifier
5786 : ns_right_command_modifier);
5790 emacs_event->modifiers |= parse_solitary_modifier
5791 (ns_command_modifier);
5793 /* if super (default), take input manager's word so things like
5794 dvorak / qwerty layout work */
5795 if (EQ (ns_command_modifier, Qsuper)
5797 && [[theEvent characters] length] != 0)
5799 /* XXX: the code we get will be unshifted, so if we have
5800 a shift modifier, must convert ourselves */
5801 if (!(flags & NSShiftKeyMask))
5802 code = [[theEvent characters] characterAtIndex: 0];
5804 /* this is ugly and also requires linking w/Carbon framework
5805 (for LMGetKbdType) so for now leave this rare (?) case
5806 undealt with.. in future look into CGEvent methods */
5809 long smv = GetScriptManagerVariable (smKeyScript);
5810 Handle uchrHandle = GetResource
5811 ('uchr', GetScriptVariable (smv, smScriptKeys));
5813 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
5814 [[theEvent characters] characterAtIndex: 0],
5815 kUCKeyActionDisplay,
5816 (flags & ~NSCommandKeyMask) >> 8,
5817 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
5818 &dummy, 1, &dummy, &code);
5825 is_right_key = (flags & NSRightControlKeyMask) == NSRightControlKeyMask;
5826 is_left_key = (flags & NSLeftControlKeyMask) == NSLeftControlKeyMask
5827 || (! is_right_key && (flags & NSControlKeyMask) == NSControlKeyMask);
5830 emacs_event->modifiers |= parse_solitary_modifier
5831 (EQ (ns_right_control_modifier, Qleft)
5832 ? ns_control_modifier
5833 : ns_right_control_modifier);
5836 emacs_event->modifiers |= parse_solitary_modifier
5837 (ns_control_modifier);
5839 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
5840 emacs_event->modifiers |=
5841 parse_solitary_modifier (ns_function_modifier);
5843 left_is_none = NILP (ns_alternate_modifier)
5844 || EQ (ns_alternate_modifier, Qnone);
5846 is_right_key = (flags & NSRightAlternateKeyMask)
5847 == NSRightAlternateKeyMask;
5848 is_left_key = (flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask
5850 && (flags & NSAlternateKeyMask) == NSAlternateKeyMask);
5854 if ((NILP (ns_right_alternate_modifier)
5855 || EQ (ns_right_alternate_modifier, Qnone)
5856 || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
5858 { /* accept pre-interp alt comb */
5859 if ([[theEvent characters] length] > 0)
5860 code = [[theEvent characters] characterAtIndex: 0];
5861 /*HACK: clear lone shift modifier to stop next if from firing */
5862 if (emacs_event->modifiers == shift_modifier)
5863 emacs_event->modifiers = 0;
5866 emacs_event->modifiers |= parse_solitary_modifier
5867 (EQ (ns_right_alternate_modifier, Qleft)
5868 ? ns_alternate_modifier
5869 : ns_right_alternate_modifier);
5872 if (is_left_key) /* default = meta */
5874 if (left_is_none && !fnKeysym)
5875 { /* accept pre-interp alt comb */
5876 if ([[theEvent characters] length] > 0)
5877 code = [[theEvent characters] characterAtIndex: 0];
5878 /*HACK: clear lone shift modifier to stop next if from firing */
5879 if (emacs_event->modifiers == shift_modifier)
5880 emacs_event->modifiers = 0;
5883 emacs_event->modifiers |=
5884 parse_solitary_modifier (ns_alternate_modifier);
5888 fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
5889 code, fnKeysym, flags, emacs_event->modifiers);
5891 /* if it was a function key or had modifiers, pass it directly to emacs */
5892 if (fnKeysym || (emacs_event->modifiers
5893 && (emacs_event->modifiers != shift_modifier)
5894 && [[theEvent charactersIgnoringModifiers] length] > 0))
5895 /*[[theEvent characters] length] */
5897 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5899 code |= (1<<28)|(3<<16);
5900 else if (code == 0x7f)
5901 code |= (1<<28)|(3<<16);
5903 emacs_event->kind = code > 0xFF
5904 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5906 emacs_event->code = code;
5907 EV_TRAILER (theEvent);
5908 processingCompose = NO;
5914 if (NS_KEYLOG && !processingCompose)
5915 fprintf (stderr, "keyDown: Begin compose sequence.\n");
5917 processingCompose = YES;
5918 [nsEvArray addObject: theEvent];
5919 [self interpretKeyEvents: nsEvArray];
5920 [nsEvArray removeObject: theEvent];
5924 #ifdef NS_IMPL_COCOA
5925 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
5926 decided not to send key-down for.
5927 See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
5928 This only applies on Tiger and earlier.
5929 If it matches one of these, send it on to keyDown. */
5930 -(void)keyUp: (NSEvent *)theEvent
5932 int flags = [theEvent modifierFlags];
5933 int code = [theEvent keyCode];
5935 NSTRACE ("[EmacsView keyUp:]");
5937 if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
5938 code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
5941 fprintf (stderr, "keyUp: passed test");
5942 ns_fake_keydown = YES;
5943 [self keyDown: theEvent];
5949 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
5952 /* <NSTextInput>: called when done composing;
5953 NOTE: also called when we delete over working text, followed immed.
5954 by doCommandBySelector: deleteBackward: */
5955 - (void)insertText: (id)aString
5958 int len = [(NSString *)aString length];
5961 NSTRACE ("[EmacsView insertText:]");
5964 NSLog (@"insertText '%@'\tlen = %d", aString, len);
5965 processingCompose = NO;
5970 /* first, clear any working text */
5971 if (workingText != nil)
5972 [self deleteWorkingText];
5974 /* now insert the string as keystrokes */
5975 for (i =0; i<len; i++)
5977 code = [aString characterAtIndex: i];
5978 /* TODO: still need this? */
5980 code = '~'; /* 0x7E */
5981 if (code != 32) /* Space */
5982 emacs_event->modifiers = 0;
5984 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5985 emacs_event->code = code;
5986 EV_TRAILER ((id)nil);
5991 /* <NSTextInput>: inserts display of composing characters */
5992 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
5994 NSString *str = [aString respondsToSelector: @selector (string)] ?
5995 [aString string] : aString;
5997 NSTRACE ("[EmacsView setMarkedText:selectedRange:]");
6000 NSLog (@"setMarkedText '%@' len =%lu range %lu from %lu",
6001 str, (unsigned long)[str length],
6002 (unsigned long)selRange.length,
6003 (unsigned long)selRange.location);
6005 if (workingText != nil)
6006 [self deleteWorkingText];
6007 if ([str length] == 0)
6013 processingCompose = YES;
6014 workingText = [str copy];
6015 ns_working_text = build_string ([workingText UTF8String]);
6017 emacs_event->kind = NS_TEXT_EVENT;
6018 emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
6019 EV_TRAILER ((id)nil);
6023 /* delete display of composing characters [not in <NSTextInput>] */
6024 - (void)deleteWorkingText
6026 NSTRACE ("[EmacsView deleteWorkingText]");
6028 if (workingText == nil)
6031 NSLog(@"deleteWorkingText len =%lu\n", (unsigned long)[workingText length]);
6032 [workingText release];
6034 processingCompose = NO;
6039 emacs_event->kind = NS_TEXT_EVENT;
6040 emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
6041 EV_TRAILER ((id)nil);
6045 - (BOOL)hasMarkedText
6047 NSTRACE ("[EmacsView hasMarkedText]");
6049 return workingText != nil;
6053 - (NSRange)markedRange
6055 NSTRACE ("[EmacsView markedRange]");
6057 NSRange rng = workingText != nil
6058 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
6060 NSLog (@"markedRange request");
6067 NSTRACE ("[EmacsView unmarkText]");
6070 NSLog (@"unmark (accept) text");
6071 [self deleteWorkingText];
6072 processingCompose = NO;
6076 /* used to position char selection windows, etc. */
6077 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
6081 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
6083 NSTRACE ("[EmacsView firstRectForCharacterRange:]");
6086 NSLog (@"firstRectForCharRange request");
6088 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
6089 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
6090 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
6091 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
6092 +FRAME_LINE_HEIGHT (emacsframe));
6094 pt = [self convertPoint: pt toView: nil];
6095 pt = [[self window] convertBaseToScreen: pt];
6101 - (NSInteger)conversationIdentifier
6103 return (NSInteger)self;
6107 - (void)doCommandBySelector: (SEL)aSelector
6109 NSTRACE ("[EmacsView doCommandBySelector:]");
6112 NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
6114 processingCompose = NO;
6115 if (aSelector == @selector (deleteBackward:))
6117 /* happens when user backspaces over an ongoing composition:
6118 throw a 'delete' into the event queue */
6121 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
6122 emacs_event->code = 0xFF08;
6123 EV_TRAILER ((id)nil);
6127 - (NSArray *)validAttributesForMarkedText
6129 static NSArray *arr = nil;
6130 if (arr == nil) arr = [NSArray new];
6131 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
6135 - (NSRange)selectedRange
6138 NSLog (@"selectedRange request");
6139 return NSMakeRange (NSNotFound, 0);
6142 #if defined (NS_IMPL_COCOA) || GNUSTEP_GUI_MAJOR_VERSION > 0 || \
6143 GNUSTEP_GUI_MINOR_VERSION > 22
6144 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
6146 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
6150 NSLog (@"characterIndexForPoint request");
6154 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
6156 static NSAttributedString *str = nil;
6157 if (str == nil) str = [NSAttributedString new];
6159 NSLog (@"attributedSubstringFromRange request");
6163 /* End <NSTextInput> impl. */
6164 /*****************************************************************************/
6167 /* This is what happens when the user presses a mouse button. */
6168 - (void)mouseDown: (NSEvent *)theEvent
6170 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6171 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
6173 NSTRACE ("[EmacsView mouseDown:]");
6175 [self deleteWorkingText];
6180 dpyinfo->last_mouse_frame = emacsframe;
6181 /* appears to be needed to prevent spurious movement events generated on
6183 emacsframe->mouse_moved = 0;
6185 if ([theEvent type] == NSScrollWheel)
6187 CGFloat delta = [theEvent deltaY];
6188 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
6191 delta = [theEvent deltaX];
6194 NSTRACE_MSG ("deltaIsZero");
6197 emacs_event->kind = HORIZ_WHEEL_EVENT;
6200 emacs_event->kind = WHEEL_EVENT;
6202 emacs_event->code = 0;
6203 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
6204 ((delta > 0) ? up_modifier : down_modifier);
6208 emacs_event->kind = MOUSE_CLICK_EVENT;
6209 emacs_event->code = EV_BUTTON (theEvent);
6210 emacs_event->modifiers = EV_MODIFIERS (theEvent)
6211 | EV_UDMODIFIERS (theEvent);
6213 XSETINT (emacs_event->x, lrint (p.x));
6214 XSETINT (emacs_event->y, lrint (p.y));
6215 EV_TRAILER (theEvent);
6219 - (void)rightMouseDown: (NSEvent *)theEvent
6221 NSTRACE ("[EmacsView rightMouseDown:]");
6222 [self mouseDown: theEvent];
6226 - (void)otherMouseDown: (NSEvent *)theEvent
6228 NSTRACE ("[EmacsView otherMouseDown:]");
6229 [self mouseDown: theEvent];
6233 - (void)mouseUp: (NSEvent *)theEvent
6235 NSTRACE ("[EmacsView mouseUp:]");
6236 [self mouseDown: theEvent];
6240 - (void)rightMouseUp: (NSEvent *)theEvent
6242 NSTRACE ("[EmacsView rightMouseUp:]");
6243 [self mouseDown: theEvent];
6247 - (void)otherMouseUp: (NSEvent *)theEvent
6249 NSTRACE ("[EmacsView otherMouseUp:]");
6250 [self mouseDown: theEvent];
6254 - (void) scrollWheel: (NSEvent *)theEvent
6256 NSTRACE ("[EmacsView scrollWheel:]");
6257 [self mouseDown: theEvent];
6261 /* Tell emacs the mouse has moved. */
6262 - (void)mouseMoved: (NSEvent *)e
6264 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
6265 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6269 NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "[EmacsView mouseMoved:]");
6271 dpyinfo->last_mouse_movement_time = EV_TIMESTAMP (e);
6272 pt = [self convertPoint: [e locationInWindow] fromView: nil];
6273 dpyinfo->last_mouse_motion_x = pt.x;
6274 dpyinfo->last_mouse_motion_y = pt.y;
6276 /* update any mouse face */
6277 if (hlinfo->mouse_face_hidden)
6279 hlinfo->mouse_face_hidden = 0;
6280 clear_mouse_face (hlinfo);
6283 /* tooltip handling */
6284 previous_help_echo_string = help_echo_string;
6285 help_echo_string = Qnil;
6287 if (!NILP (Vmouse_autoselect_window))
6289 NSTRACE_MSG ("mouse_autoselect_window");
6290 static Lisp_Object last_mouse_window;
6292 = window_from_coordinates (emacsframe, pt.x, pt.y, 0, 0);
6294 if (WINDOWP (window)
6295 && !EQ (window, last_mouse_window)
6296 && !EQ (window, selected_window)
6297 && (focus_follows_mouse
6298 || (EQ (XWINDOW (window)->frame,
6299 XWINDOW (selected_window)->frame))))
6301 NSTRACE_MSG ("in_window");
6302 emacs_event->kind = SELECT_WINDOW_EVENT;
6303 emacs_event->frame_or_window = window;
6306 /* Remember the last window where we saw the mouse. */
6307 last_mouse_window = window;
6310 if (!note_mouse_movement (emacsframe, pt.x, pt.y))
6311 help_echo_string = previous_help_echo_string;
6313 XSETFRAME (frame, emacsframe);
6314 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
6316 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
6317 (note_mouse_highlight), which is called through the
6318 note_mouse_movement () call above */
6319 any_help_event_p = YES;
6320 gen_help_event (help_echo_string, frame, help_echo_window,
6321 help_echo_object, help_echo_pos);
6324 if (emacsframe->mouse_moved && send_appdefined)
6325 ns_send_appdefined (-1);
6329 - (void)mouseDragged: (NSEvent *)e
6331 NSTRACE ("[EmacsView mouseDragged:]");
6332 [self mouseMoved: e];
6336 - (void)rightMouseDragged: (NSEvent *)e
6338 NSTRACE ("[EmacsView rightMouseDragged:]");
6339 [self mouseMoved: e];
6343 - (void)otherMouseDragged: (NSEvent *)e
6345 NSTRACE ("[EmacsView otherMouseDragged:]");
6346 [self mouseMoved: e];
6350 - (BOOL)windowShouldClose: (id)sender
6352 NSEvent *e =[[self window] currentEvent];
6354 NSTRACE ("[EmacsView windowShouldClose:]");
6355 windowClosing = YES;
6358 emacs_event->kind = DELETE_WINDOW_EVENT;
6359 emacs_event->modifiers = 0;
6360 emacs_event->code = 0;
6362 /* Don't close this window, let this be done from lisp code. */
6366 - (void) updateFrameSize: (BOOL) delay;
6368 NSWindow *window = [self window];
6369 NSRect wr = [window frame];
6371 int oldc = cols, oldr = rows;
6372 int oldw = FRAME_PIXEL_WIDTH (emacsframe);
6373 int oldh = FRAME_PIXEL_HEIGHT (emacsframe);
6376 NSTRACE ("[EmacsView updateFrameSize:]");
6377 NSTRACE_SIZE ("Original size", NSMakeSize (oldw, oldh));
6378 NSTRACE_RECT ("Original frame", wr);
6379 NSTRACE_MSG ("Original columns: %d", cols);
6380 NSTRACE_MSG ("Original rows: %d", rows);
6382 if (! [self isFullscreen])
6384 #ifdef NS_IMPL_GNUSTEP
6385 // GNUstep does not always update the tool bar height. Force it.
6386 if (toolbar && [toolbar isVisible])
6387 update_frame_tool_bar (emacsframe);
6390 extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6391 + FRAME_TOOLBAR_HEIGHT (emacsframe);
6394 if (wait_for_tool_bar)
6396 if (FRAME_TOOLBAR_HEIGHT (emacsframe) == 0)
6398 NSTRACE_MSG ("Waiting for toolbar");
6401 wait_for_tool_bar = NO;
6404 neww = (int)wr.size.width - emacsframe->border_width;
6405 newh = (int)wr.size.height - extra;
6407 NSTRACE_SIZE ("New size", NSMakeSize (neww, newh));
6408 NSTRACE_MSG ("tool_bar_height: %d", emacsframe->tool_bar_height);
6410 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, neww);
6411 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, newh);
6413 if (cols < MINWIDTH)
6416 if (rows < MINHEIGHT)
6419 NSTRACE_MSG ("New columns: %d", cols);
6420 NSTRACE_MSG ("New rows: %d", rows);
6422 if (oldr != rows || oldc != cols || neww != oldw || newh != oldh)
6424 NSView *view = FRAME_NS_VIEW (emacsframe);
6426 change_frame_size (emacsframe,
6427 FRAME_PIXEL_TO_TEXT_WIDTH (emacsframe, neww),
6428 FRAME_PIXEL_TO_TEXT_HEIGHT (emacsframe, newh),
6430 SET_FRAME_GARBAGED (emacsframe);
6431 cancel_mouse_face (emacsframe);
6433 wr = NSMakeRect (0, 0, neww, newh);
6435 [view setFrame: wr];
6437 // to do: consider using [NSNotificationCenter postNotificationName:].
6438 [self windowDidMove: // Update top/left.
6439 [NSNotification notificationWithName:NSWindowDidMoveNotification
6440 object:[view window]]];
6444 NSTRACE_MSG ("No change");
6448 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
6449 /* normalize frame to gridded text size */
6453 NSTRACE ("[EmacsView windowWillResize:toSize: " NSTRACE_FMT_SIZE "]",
6454 NSTRACE_ARG_SIZE (frameSize));
6455 NSTRACE_RECT ("[sender frame]", [sender frame]);
6456 NSTRACE_FSTYPE ("fs_state", fs_state);
6458 if (fs_state == FULLSCREEN_MAXIMIZED
6459 && (maximized_width != (int)frameSize.width
6460 || maximized_height != (int)frameSize.height))
6461 [self setFSValue: FULLSCREEN_NONE];
6462 else if (fs_state == FULLSCREEN_WIDTH
6463 && maximized_width != (int)frameSize.width)
6464 [self setFSValue: FULLSCREEN_NONE];
6465 else if (fs_state == FULLSCREEN_HEIGHT
6466 && maximized_height != (int)frameSize.height)
6467 [self setFSValue: FULLSCREEN_NONE];
6469 if (fs_state == FULLSCREEN_NONE)
6470 maximized_width = maximized_height = -1;
6472 if (! [self isFullscreen])
6474 extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6475 + FRAME_TOOLBAR_HEIGHT (emacsframe);
6478 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, frameSize.width);
6479 if (cols < MINWIDTH)
6482 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe,
6483 frameSize.height - extra);
6484 if (rows < MINHEIGHT)
6486 #ifdef NS_IMPL_COCOA
6488 /* this sets window title to have size in it; the wm does this under GS */
6489 NSRect r = [[self window] frame];
6490 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
6498 else if (fs_state == FULLSCREEN_NONE && ! maximizing_resize)
6501 NSWindow *window = [self window];
6504 char *t = strdup ([[[self window] title] UTF8String]);
6505 char *pos = strstr (t, " — ");
6510 size_title = xmalloc (strlen (old_title) + 40);
6511 esprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
6512 [window setTitle: [NSString stringWithUTF8String: size_title]];
6517 #endif /* NS_IMPL_COCOA */
6519 NSTRACE_MSG ("cols: %d rows: %d", cols, rows);
6521 /* Restrict the new size to the text gird.
6523 Don't restrict the width if the user only adjusted the height, and
6524 vice versa. (Without this, the frame would shrink, and move
6525 slightly, if the window was resized by dragging one of its
6527 if (!frame_resize_pixelwise)
6529 NSRect r = [[self window] frame];
6531 if (r.size.width != frameSize.width)
6534 FRAME_TEXT_COLS_TO_PIXEL_WIDTH (emacsframe, cols);
6537 if (r.size.height != frameSize.height)
6540 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows) + extra;
6544 NSTRACE_RETURN_SIZE (frameSize);
6550 - (void)windowDidResize: (NSNotification *)notification
6552 NSTRACE ("[EmacsView windowDidResize:]");
6553 if (!FRAME_LIVE_P (emacsframe))
6555 NSTRACE_MSG ("Ignored (frame dead)");
6558 if (emacsframe->output_data.ns->in_animation)
6560 NSTRACE_MSG ("Ignored (in animation)");
6564 if (! [self fsIsNative])
6566 NSWindow *theWindow = [notification object];
6567 /* We can get notification on the non-FS window when in
6569 if ([self window] != theWindow) return;
6572 NSTRACE_RECT ("frame", [[notification object] frame]);
6574 #ifdef NS_IMPL_GNUSTEP
6575 NSWindow *theWindow = [notification object];
6577 /* In GNUstep, at least currently, it's possible to get a didResize
6578 without getting a willResize.. therefore we need to act as if we got
6579 the willResize now */
6580 NSSize sz = [theWindow frame].size;
6581 sz = [self windowWillResize: theWindow toSize: sz];
6582 #endif /* NS_IMPL_GNUSTEP */
6584 if (cols > 0 && rows > 0)
6586 [self updateFrameSize: YES];
6589 ns_send_appdefined (-1);
6592 #ifdef NS_IMPL_COCOA
6593 - (void)viewDidEndLiveResize
6595 NSTRACE ("[EmacsView viewDidEndLiveResize]");
6597 [super viewDidEndLiveResize];
6600 [[self window] setTitle: [NSString stringWithUTF8String: old_title]];
6604 maximizing_resize = NO;
6606 #endif /* NS_IMPL_COCOA */
6609 - (void)windowDidBecomeKey: (NSNotification *)notification
6610 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6612 [self windowDidBecomeKey];
6616 - (void)windowDidBecomeKey /* for direct calls */
6618 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6619 struct frame *old_focus = dpyinfo->x_focus_frame;
6621 NSTRACE ("[EmacsView windowDidBecomeKey]");
6623 if (emacsframe != old_focus)
6624 dpyinfo->x_focus_frame = emacsframe;
6626 ns_frame_rehighlight (emacsframe);
6630 emacs_event->kind = FOCUS_IN_EVENT;
6631 EV_TRAILER ((id)nil);
6636 - (void)windowDidResignKey: (NSNotification *)notification
6637 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6639 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6640 BOOL is_focus_frame = dpyinfo->x_focus_frame == emacsframe;
6641 NSTRACE ("[EmacsView windowDidResignKey:]");
6644 dpyinfo->x_focus_frame = 0;
6646 emacsframe->mouse_moved = 0;
6647 ns_frame_rehighlight (emacsframe);
6649 /* FIXME: for some reason needed on second and subsequent clicks away
6650 from sole-frame Emacs to get hollow box to show */
6651 if (!windowClosing && [[self window] isVisible] == YES)
6653 x_update_cursor (emacsframe, 1);
6654 x_set_frame_alpha (emacsframe);
6657 if (any_help_event_p)
6660 XSETFRAME (frame, emacsframe);
6661 help_echo_string = Qnil;
6662 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
6665 if (emacs_event && is_focus_frame)
6667 [self deleteWorkingText];
6668 emacs_event->kind = FOCUS_OUT_EVENT;
6669 EV_TRAILER ((id)nil);
6674 - (void)windowWillMiniaturize: sender
6676 NSTRACE ("[EmacsView windowWillMiniaturize:]");
6680 - (void)setFrame:(NSRect)frameRect;
6682 NSTRACE ("[EmacsView setFrame:" NSTRACE_FMT_RECT "]",
6683 NSTRACE_ARG_RECT (frameRect));
6685 [super setFrame:(NSRect)frameRect];
6701 - initFrameFromEmacs: (struct frame *)f
6709 NSTRACE ("[EmacsView initFrameFromEmacs:]");
6710 NSTRACE_MSG ("cols:%d lines:%d", f->text_cols, f->text_lines);
6713 processingCompose = NO;
6714 scrollbarsNeedingUpdate = 0;
6715 fs_state = FULLSCREEN_NONE;
6716 fs_before_fs = next_maximized = -1;
6717 #ifdef HAVE_NATIVE_FS
6718 fs_is_native = ns_use_native_fullscreen;
6722 maximized_width = maximized_height = -1;
6725 ns_userRect = NSMakeRect (0, 0, 0, 0);
6726 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
6727 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
6728 [self initWithFrame: r];
6729 [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
6731 FRAME_NS_VIEW (f) = self;
6733 #ifdef NS_IMPL_COCOA
6735 maximizing_resize = NO;
6738 win = [[EmacsWindow alloc]
6739 initWithContentRect: r
6740 styleMask: (NSResizableWindowMask |
6741 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6742 NSTitledWindowMask |
6744 NSMiniaturizableWindowMask |
6745 NSClosableWindowMask)
6746 backing: NSBackingStoreBuffered
6749 #ifdef HAVE_NATIVE_FS
6750 [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
6754 bwidth = f->border_width = wr.size.width - r.size.width;
6755 tibar_height = FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
6757 [win setAcceptsMouseMovedEvents: YES];
6758 [win setDelegate: self];
6759 #if !defined (NS_IMPL_COCOA) || \
6760 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6761 [win useOptimizedDrawing: YES];
6764 [[win contentView] addSubview: self];
6767 [self registerForDraggedTypes: ns_drag_types];
6770 name = [NSString stringWithUTF8String:
6771 NILP (tem) ? "Emacs" : SSDATA (tem)];
6772 [win setTitle: name];
6774 /* toolbar support */
6775 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
6776 [NSString stringWithFormat: @"Emacs Frame %d",
6778 [win setToolbar: toolbar];
6779 [toolbar setVisible: NO];
6781 /* Don't set frame garbaged until tool bar is up to date?
6782 This avoids an extra clear and redraw (flicker) at frame creation. */
6783 if (FRAME_EXTERNAL_TOOL_BAR (f)) wait_for_tool_bar = YES;
6784 else wait_for_tool_bar = NO;
6787 #ifdef NS_IMPL_COCOA
6789 NSButton *toggleButton;
6790 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
6791 [toggleButton setTarget: self];
6792 [toggleButton setAction: @selector (toggleToolbar: )];
6795 FRAME_TOOLBAR_HEIGHT (f) = 0;
6799 [win setMiniwindowTitle:
6800 [NSString stringWithUTF8String: SSDATA (tem)]];
6803 NSScreen *screen = [win screen];
6807 NSPoint pt = NSMakePoint
6808 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
6809 IN_BOUND (-SCREENMAX,
6810 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX));
6812 [win setFrameTopLeftPoint: pt];
6814 NSTRACE_RECT ("new frame", [win frame]);
6818 [win makeFirstResponder: self];
6820 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6821 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
6822 [win setBackgroundColor: col];
6823 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6824 [win setOpaque: NO];
6826 #if !defined (NS_IMPL_COCOA) || \
6827 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6828 [self allocateGState];
6830 [NSApp registerServicesMenuSendTypes: ns_send_types
6838 - (void)windowDidMove: sender
6840 NSWindow *win = [self window];
6841 NSRect r = [win frame];
6842 NSArray *screens = [NSScreen screens];
6843 NSScreen *screen = [screens objectAtIndex: 0];
6845 NSTRACE ("[EmacsView windowDidMove:]");
6847 if (!emacsframe->output_data.ns)
6851 emacsframe->left_pos = r.origin.x;
6852 emacsframe->top_pos =
6853 [screen frame].size.height - (r.origin.y + r.size.height);
6858 /* Called AFTER method below, but before our windowWillResize call there leads
6859 to windowDidResize -> x_set_window_size. Update emacs' notion of frame
6860 location so set_window_size moves the frame. */
6861 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
6863 NSTRACE (("[EmacsView windowShouldZoom:toFrame:" NSTRACE_FMT_RECT "]"
6864 NSTRACE_FMT_RETURN "YES"),
6865 NSTRACE_ARG_RECT (newFrame));
6867 emacsframe->output_data.ns->zooming = 1;
6872 /* Override to do something slightly nonstandard, but nice. First click on
6873 zoom button will zoom vertically. Second will zoom completely. Third
6874 returns to original. */
6875 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
6876 defaultFrame:(NSRect)defaultFrame
6878 // TODO: Rename to "currentFrame" and assign "result" properly in
6880 NSRect result = [sender frame];
6882 NSTRACE (("[EmacsView windowWillUseStandardFrame:defaultFrame:"
6883 NSTRACE_FMT_RECT "]"),
6884 NSTRACE_ARG_RECT (defaultFrame));
6885 NSTRACE_FSTYPE ("fs_state", fs_state);
6886 NSTRACE_FSTYPE ("fs_before_fs", fs_before_fs);
6887 NSTRACE_FSTYPE ("next_maximized", next_maximized);
6888 NSTRACE_RECT ("ns_userRect", ns_userRect);
6889 NSTRACE_RECT ("[sender frame]", [sender frame]);
6891 if (fs_before_fs != -1) /* Entering fullscreen */
6893 NSTRACE_MSG ("Entering fullscreen");
6894 result = defaultFrame;
6898 // Save the window size and position (frame) before the resize.
6899 if (fs_state != FULLSCREEN_MAXIMIZED
6900 && fs_state != FULLSCREEN_WIDTH)
6902 ns_userRect.size.width = result.size.width;
6903 ns_userRect.origin.x = result.origin.x;
6906 if (fs_state != FULLSCREEN_MAXIMIZED
6907 && fs_state != FULLSCREEN_HEIGHT)
6909 ns_userRect.size.height = result.size.height;
6910 ns_userRect.origin.y = result.origin.y;
6913 NSTRACE_RECT ("ns_userRect (2)", ns_userRect);
6915 if (next_maximized == FULLSCREEN_HEIGHT
6916 || (next_maximized == -1
6917 && abs ((int)(defaultFrame.size.height - result.size.height))
6918 > FRAME_LINE_HEIGHT (emacsframe)))
6921 NSTRACE_MSG ("FULLSCREEN_HEIGHT");
6922 maximized_height = result.size.height = defaultFrame.size.height;
6923 maximized_width = -1;
6924 result.origin.y = defaultFrame.origin.y;
6925 if (ns_userRect.size.height != 0)
6927 result.origin.x = ns_userRect.origin.x;
6928 result.size.width = ns_userRect.size.width;
6930 [self setFSValue: FULLSCREEN_HEIGHT];
6931 #ifdef NS_IMPL_COCOA
6932 maximizing_resize = YES;
6935 else if (next_maximized == FULLSCREEN_WIDTH)
6937 NSTRACE_MSG ("FULLSCREEN_WIDTH");
6938 maximized_width = result.size.width = defaultFrame.size.width;
6939 maximized_height = -1;
6940 result.origin.x = defaultFrame.origin.x;
6941 if (ns_userRect.size.width != 0)
6943 result.origin.y = ns_userRect.origin.y;
6944 result.size.height = ns_userRect.size.height;
6946 [self setFSValue: FULLSCREEN_WIDTH];
6948 else if (next_maximized == FULLSCREEN_MAXIMIZED
6949 || (next_maximized == -1
6950 && abs ((int)(defaultFrame.size.width - result.size.width))
6951 > FRAME_COLUMN_WIDTH (emacsframe)))
6953 NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
6955 result = defaultFrame; /* second click */
6956 maximized_width = result.size.width;
6957 maximized_height = result.size.height;
6958 [self setFSValue: FULLSCREEN_MAXIMIZED];
6959 #ifdef NS_IMPL_COCOA
6960 maximizing_resize = YES;
6966 NSTRACE_MSG ("Restore");
6967 result = ns_userRect.size.height ? ns_userRect : result;
6968 NSTRACE_RECT ("restore (2)", result);
6969 ns_userRect = NSMakeRect (0, 0, 0, 0);
6970 #ifdef NS_IMPL_COCOA
6971 maximizing_resize = fs_state != FULLSCREEN_NONE;
6973 [self setFSValue: FULLSCREEN_NONE];
6974 maximized_width = maximized_height = -1;
6978 if (fs_before_fs == -1) next_maximized = -1;
6980 NSTRACE_RECT ("Final ns_userRect", ns_userRect);
6981 NSTRACE_MSG ("Final maximized_width: %d", maximized_width);
6982 NSTRACE_MSG ("Final maximized_height: %d", maximized_height);
6983 NSTRACE_FSTYPE ("Final next_maximized", next_maximized);
6985 [self windowWillResize: sender toSize: result.size];
6987 NSTRACE_RETURN_RECT (result);
6993 - (void)windowDidDeminiaturize: sender
6995 NSTRACE ("[EmacsView windowDidDeminiaturize:]");
6996 if (!emacsframe->output_data.ns)
6999 SET_FRAME_ICONIFIED (emacsframe, 0);
7000 SET_FRAME_VISIBLE (emacsframe, 1);
7001 windows_or_buffers_changed = 63;
7005 emacs_event->kind = DEICONIFY_EVENT;
7006 EV_TRAILER ((id)nil);
7011 - (void)windowDidExpose: sender
7013 NSTRACE ("[EmacsView windowDidExpose:]");
7014 if (!emacsframe->output_data.ns)
7017 SET_FRAME_VISIBLE (emacsframe, 1);
7018 SET_FRAME_GARBAGED (emacsframe);
7020 if (send_appdefined)
7021 ns_send_appdefined (-1);
7025 - (void)windowDidMiniaturize: sender
7027 NSTRACE ("[EmacsView windowDidMiniaturize:]");
7028 if (!emacsframe->output_data.ns)
7031 SET_FRAME_ICONIFIED (emacsframe, 1);
7032 SET_FRAME_VISIBLE (emacsframe, 0);
7036 emacs_event->kind = ICONIFY_EVENT;
7037 EV_TRAILER ((id)nil);
7041 #ifdef HAVE_NATIVE_FS
7042 - (NSApplicationPresentationOptions)window:(NSWindow *)window
7043 willUseFullScreenPresentationOptions:
7044 (NSApplicationPresentationOptions)proposedOptions
7046 return proposedOptions|NSApplicationPresentationAutoHideToolbar;
7050 - (void)windowWillEnterFullScreen:(NSNotification *)notification
7052 NSTRACE ("[EmacsView windowWillEnterFullScreen:]");
7053 [self windowWillEnterFullScreen];
7055 - (void)windowWillEnterFullScreen /* provided for direct calls */
7057 NSTRACE ("[EmacsView windowWillEnterFullScreen]");
7058 fs_before_fs = fs_state;
7061 - (void)windowDidEnterFullScreen:(NSNotification *)notification
7063 NSTRACE ("[EmacsView windowDidEnterFullScreen:]");
7064 [self windowDidEnterFullScreen];
7067 - (void)windowDidEnterFullScreen /* provided for direct calls */
7069 NSTRACE ("[EmacsView windowDidEnterFullScreen]");
7070 [self setFSValue: FULLSCREEN_BOTH];
7071 if (! [self fsIsNative])
7073 [self windowDidBecomeKey];
7074 [nonfs_window orderOut:self];
7078 BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (emacsframe) ? YES : NO;
7079 #ifdef NS_IMPL_COCOA
7080 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
7081 unsigned val = (unsigned)[NSApp presentationOptions];
7083 // OSX 10.7 bug fix, the menu won't appear without this.
7084 // val is non-zero on other OSX versions.
7087 NSApplicationPresentationOptions options
7088 = NSApplicationPresentationAutoHideDock
7089 | NSApplicationPresentationAutoHideMenuBar
7090 | NSApplicationPresentationFullScreen
7091 | NSApplicationPresentationAutoHideToolbar;
7093 [NSApp setPresentationOptions: options];
7097 [toolbar setVisible:tbar_visible];
7101 - (void)windowWillExitFullScreen:(NSNotification *)notification
7103 NSTRACE ("[EmacsView windowWillExitFullScreen:]");
7104 [self windowWillExitFullScreen];
7107 - (void)windowWillExitFullScreen /* provided for direct calls */
7109 NSTRACE ("[EmacsView windowWillExitFullScreen]");
7110 if (!FRAME_LIVE_P (emacsframe))
7112 NSTRACE_MSG ("Ignored (frame dead)");
7115 if (next_maximized != -1)
7116 fs_before_fs = next_maximized;
7119 - (void)windowDidExitFullScreen:(NSNotification *)notification
7121 NSTRACE ("[EmacsView windowDidExitFullScreen:]");
7122 [self windowDidExitFullScreen];
7125 - (void)windowDidExitFullScreen /* provided for direct calls */
7127 NSTRACE ("[EmacsView windowDidExitFullScreen]");
7128 if (!FRAME_LIVE_P (emacsframe))
7130 NSTRACE_MSG ("Ignored (frame dead)");
7133 [self setFSValue: fs_before_fs];
7135 #ifdef HAVE_NATIVE_FS
7136 [self updateCollectionBehavior];
7138 if (FRAME_EXTERNAL_TOOL_BAR (emacsframe))
7140 [toolbar setVisible:YES];
7141 update_frame_tool_bar (emacsframe);
7142 [self updateFrameSize:YES];
7143 [[self window] display];
7146 [toolbar setVisible:NO];
7148 if (next_maximized != -1)
7149 [[self window] performZoom:self];
7154 return fs_is_native;
7157 - (BOOL)isFullscreen
7163 res = (nonfs_window != nil);
7167 #ifdef HAVE_NATIVE_FS
7168 res = (([[self window] styleMask] & NSFullScreenWindowMask) != 0);
7174 NSTRACE ("[EmacsView isFullscreen] " NSTRACE_FMT_RETURN " %d",
7180 #ifdef HAVE_NATIVE_FS
7181 - (void)updateCollectionBehavior
7183 NSTRACE ("[EmacsView updateCollectionBehavior]");
7185 if (! [self isFullscreen])
7187 NSWindow *win = [self window];
7188 NSWindowCollectionBehavior b = [win collectionBehavior];
7189 if (ns_use_native_fullscreen)
7190 b |= NSWindowCollectionBehaviorFullScreenPrimary;
7192 b &= ~NSWindowCollectionBehaviorFullScreenPrimary;
7194 [win setCollectionBehavior: b];
7195 fs_is_native = ns_use_native_fullscreen;
7200 - (void)toggleFullScreen: (id)sender
7208 NSTRACE ("[EmacsView toggleFullScreen:]");
7212 #ifdef HAVE_NATIVE_FS
7213 [[self window] toggleFullScreen:sender];
7219 onFirstScreen = [[w screen] isEqual:[[NSScreen screens] objectAtIndex:0]];
7222 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
7223 (FRAME_DEFAULT_FACE (f)),
7226 if (fs_state != FULLSCREEN_BOTH)
7228 NSScreen *screen = [w screen];
7230 #if defined (NS_IMPL_COCOA) && \
7231 MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7232 /* Hide ghost menu bar on secondary monitor? */
7233 if (! onFirstScreen)
7234 onFirstScreen = [NSScreen screensHaveSeparateSpaces];
7236 /* Hide dock and menubar if we are on the primary screen. */
7239 #ifdef NS_IMPL_COCOA
7240 NSApplicationPresentationOptions options
7241 = NSApplicationPresentationAutoHideDock
7242 | NSApplicationPresentationAutoHideMenuBar;
7244 [NSApp setPresentationOptions: options];
7246 [NSMenu setMenuBarVisible:NO];
7250 fw = [[EmacsFSWindow alloc]
7251 initWithContentRect:[w contentRectForFrameRect:wr]
7252 styleMask:NSBorderlessWindowMask
7253 backing:NSBackingStoreBuffered
7257 [fw setContentView:[w contentView]];
7258 [fw setTitle:[w title]];
7259 [fw setDelegate:self];
7260 [fw setAcceptsMouseMovedEvents: YES];
7261 #if !defined (NS_IMPL_COCOA) || \
7262 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
7263 [fw useOptimizedDrawing: YES];
7265 [fw setBackgroundColor: col];
7266 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
7269 f->border_width = 0;
7270 FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
7271 tobar_height = FRAME_TOOLBAR_HEIGHT (f);
7272 FRAME_TOOLBAR_HEIGHT (f) = 0;
7276 [self windowWillEnterFullScreen];
7277 [fw makeKeyAndOrderFront:NSApp];
7278 [fw makeFirstResponder:self];
7280 r = [fw frameRectForContentRect:[screen frame]];
7281 [fw setFrame: r display:YES animate:ns_use_fullscreen_animation];
7282 [self windowDidEnterFullScreen];
7293 #ifdef NS_IMPL_COCOA
7294 [NSApp setPresentationOptions: NSApplicationPresentationDefault];
7296 [NSMenu setMenuBarVisible:YES];
7300 [w setContentView:[fw contentView]];
7301 [w setBackgroundColor: col];
7302 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
7305 f->border_width = bwidth;
7306 FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
7307 if (FRAME_EXTERNAL_TOOL_BAR (f))
7308 FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
7310 // to do: consider using [NSNotificationCenter postNotificationName:] to send notifications.
7312 [self windowWillExitFullScreen];
7313 [fw setFrame: [w frame] display:YES animate:ns_use_fullscreen_animation];
7315 [w makeKeyAndOrderFront:NSApp];
7316 [self windowDidExitFullScreen];
7317 [self updateFrameSize:YES];
7323 NSTRACE ("[EmacsView handleFS]");
7325 if (fs_state != emacsframe->want_fullscreen)
7327 if (fs_state == FULLSCREEN_BOTH)
7329 NSTRACE_MSG ("fs_state == FULLSCREEN_BOTH");
7330 [self toggleFullScreen:self];
7333 switch (emacsframe->want_fullscreen)
7335 case FULLSCREEN_BOTH:
7336 NSTRACE_MSG ("FULLSCREEN_BOTH");
7337 [self toggleFullScreen:self];
7339 case FULLSCREEN_WIDTH:
7340 NSTRACE_MSG ("FULLSCREEN_WIDTH");
7341 next_maximized = FULLSCREEN_WIDTH;
7342 if (fs_state != FULLSCREEN_BOTH)
7343 [[self window] performZoom:self];
7345 case FULLSCREEN_HEIGHT:
7346 NSTRACE_MSG ("FULLSCREEN_HEIGHT");
7347 next_maximized = FULLSCREEN_HEIGHT;
7348 if (fs_state != FULLSCREEN_BOTH)
7349 [[self window] performZoom:self];
7351 case FULLSCREEN_MAXIMIZED:
7352 NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
7353 next_maximized = FULLSCREEN_MAXIMIZED;
7354 if (fs_state != FULLSCREEN_BOTH)
7355 [[self window] performZoom:self];
7357 case FULLSCREEN_NONE:
7358 NSTRACE_MSG ("FULLSCREEN_NONE");
7359 if (fs_state != FULLSCREEN_BOTH)
7361 next_maximized = FULLSCREEN_NONE;
7362 [[self window] performZoom:self];
7367 emacsframe->want_fullscreen = FULLSCREEN_NONE;
7372 - (void) setFSValue: (int)value
7374 NSTRACE ("[EmacsView setFSValue:" NSTRACE_FMT_FSTYPE "]",
7375 NSTRACE_ARG_FSTYPE(value));
7377 Lisp_Object lval = Qnil;
7380 case FULLSCREEN_BOTH:
7383 case FULLSCREEN_WIDTH:
7386 case FULLSCREEN_HEIGHT:
7389 case FULLSCREEN_MAXIMIZED:
7393 store_frame_param (emacsframe, Qfullscreen, lval);
7397 - (void)mouseEntered: (NSEvent *)theEvent
7399 NSTRACE ("[EmacsView mouseEntered:]");
7401 FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7402 = EV_TIMESTAMP (theEvent);
7406 - (void)mouseExited: (NSEvent *)theEvent
7408 Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
7410 NSTRACE ("[EmacsView mouseExited:]");
7415 FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7416 = EV_TIMESTAMP (theEvent);
7418 if (emacsframe == hlinfo->mouse_face_mouse_frame)
7420 clear_mouse_face (hlinfo);
7421 hlinfo->mouse_face_mouse_frame = 0;
7428 NSTRACE ("[EmacsView menuDown:]");
7429 if (context_menu_value == -1)
7430 context_menu_value = [sender tag];
7433 NSInteger tag = [sender tag];
7434 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
7435 emacsframe->menu_bar_vector,
7439 ns_send_appdefined (-1);
7444 - (EmacsToolbar *)toolbar
7450 /* this gets called on toolbar button click */
7451 - toolbarClicked: (id)item
7454 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
7456 NSTRACE ("[EmacsView toolbarClicked:]");
7461 /* send first event (for some reason two needed) */
7462 theEvent = [[self window] currentEvent];
7463 emacs_event->kind = TOOL_BAR_EVENT;
7464 XSETFRAME (emacs_event->arg, emacsframe);
7465 EV_TRAILER (theEvent);
7467 emacs_event->kind = TOOL_BAR_EVENT;
7468 /* XSETINT (emacs_event->code, 0); */
7469 emacs_event->arg = AREF (emacsframe->tool_bar_items,
7470 idx + TOOL_BAR_ITEM_KEY);
7471 emacs_event->modifiers = EV_MODIFIERS (theEvent);
7472 EV_TRAILER (theEvent);
7477 - toggleToolbar: (id)sender
7479 NSTRACE ("[EmacsView toggleToolbar:]");
7484 emacs_event->kind = NS_NONKEY_EVENT;
7485 emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
7486 EV_TRAILER ((id)nil);
7491 - (void)drawRect: (NSRect)rect
7493 int x = NSMinX (rect), y = NSMinY (rect);
7494 int width = NSWidth (rect), height = NSHeight (rect);
7496 NSTRACE ("[EmacsView drawRect:" NSTRACE_FMT_RECT "]",
7497 NSTRACE_ARG_RECT(rect));
7499 if (!emacsframe || !emacsframe->output_data.ns)
7502 ns_clear_frame_area (emacsframe, x, y, width, height);
7504 expose_frame (emacsframe, x, y, width, height);
7508 drawRect: may be called (at least in OS X 10.5) for invisible
7509 views as well for some reason. Thus, do not infer visibility
7512 emacsframe->async_visible = 1;
7513 emacsframe->async_iconified = 0;
7518 /* NSDraggingDestination protocol methods. Actually this is not really a
7519 protocol, but a category of Object. O well... */
7521 -(NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
7523 NSTRACE ("[EmacsView draggingEntered:]");
7524 return NSDragOperationGeneric;
7528 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
7534 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
7539 NSEvent *theEvent = [[self window] currentEvent];
7541 NSDragOperation op = [sender draggingSourceOperationMask];
7544 NSTRACE ("[EmacsView performDragOperation:]");
7549 position = [self convertPoint: [sender draggingLocation] fromView: nil];
7550 x = lrint (position.x); y = lrint (position.y);
7552 pb = [sender draggingPasteboard];
7553 type = [pb availableTypeFromArray: ns_drag_types];
7555 if (! (op & (NSDragOperationMove|NSDragOperationDelete)) &&
7556 // URL drags contain all operations (0xf), don't allow all to be set.
7559 if (op & NSDragOperationLink)
7560 modifiers |= NSControlKeyMask;
7561 if (op & NSDragOperationCopy)
7562 modifiers |= NSAlternateKeyMask;
7563 if (op & NSDragOperationGeneric)
7564 modifiers |= NSCommandKeyMask;
7567 modifiers = EV_MODIFIERS2 (modifiers);
7572 else if ([type isEqualToString: NSFilenamesPboardType])
7575 NSEnumerator *fenum;
7578 if (!(files = [pb propertyListForType: type]))
7581 fenum = [files objectEnumerator];
7582 while ( (file = [fenum nextObject]) )
7584 emacs_event->kind = DRAG_N_DROP_EVENT;
7585 XSETINT (emacs_event->x, x);
7586 XSETINT (emacs_event->y, y);
7587 ns_input_file = append2 (ns_input_file,
7588 build_string ([file UTF8String]));
7589 emacs_event->modifiers = modifiers;
7590 emacs_event->arg = list2 (Qfile, build_string ([file UTF8String]));
7591 EV_TRAILER (theEvent);
7595 else if ([type isEqualToString: NSURLPboardType])
7597 NSURL *url = [NSURL URLFromPasteboard: pb];
7598 if (url == nil) return NO;
7600 emacs_event->kind = DRAG_N_DROP_EVENT;
7601 XSETINT (emacs_event->x, x);
7602 XSETINT (emacs_event->y, y);
7603 emacs_event->modifiers = modifiers;
7604 emacs_event->arg = list2 (Qurl,
7605 build_string ([[url absoluteString]
7607 EV_TRAILER (theEvent);
7609 if ([url isFileURL] != NO)
7611 NSString *file = [url path];
7612 ns_input_file = append2 (ns_input_file,
7613 build_string ([file UTF8String]));
7617 else if ([type isEqualToString: NSStringPboardType]
7618 || [type isEqualToString: NSTabularTextPboardType])
7622 if (! (data = [pb stringForType: type]))
7625 emacs_event->kind = DRAG_N_DROP_EVENT;
7626 XSETINT (emacs_event->x, x);
7627 XSETINT (emacs_event->y, y);
7628 emacs_event->modifiers = modifiers;
7629 emacs_event->arg = list2 (Qnil, build_string ([data UTF8String]));
7630 EV_TRAILER (theEvent);
7635 fprintf (stderr, "Invalid data type in dragging pasteboard");
7641 - (id) validRequestorForSendType: (NSString *)typeSent
7642 returnType: (NSString *)typeReturned
7644 NSTRACE ("[EmacsView validRequestorForSendType:returnType:]");
7645 if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
7646 && typeReturned == nil)
7648 if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
7652 return [super validRequestorForSendType: typeSent
7653 returnType: typeReturned];
7657 /* The next two methods are part of NSServicesRequests informal protocol,
7658 supposedly called when a services menu item is chosen from this app.
7659 But this should not happen because we override the services menu with our
7660 own entries which call ns-perform-service.
7661 Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
7662 So let's at least stub them out until further investigation can be done. */
7664 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
7666 /* we could call ns_string_from_pasteboard(pboard) here but then it should
7667 be written into the buffer in place of the existing selection..
7668 ordinary service calls go through functions defined in ns-win.el */
7672 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
7674 NSArray *typesDeclared;
7677 NSTRACE ("[EmacsView writeSelectionToPasteboard:types:]");
7679 /* We only support NSStringPboardType */
7680 if ([types containsObject:NSStringPboardType] == NO) {
7684 val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7685 if (CONSP (val) && SYMBOLP (XCAR (val)))
7688 if (CONSP (val) && NILP (XCDR (val)))
7691 if (! STRINGP (val))
7694 typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
7695 [pb declareTypes:typesDeclared owner:nil];
7696 ns_string_to_pasteboard (pb, val);
7701 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
7702 (gives a miniaturized version of the window); currently we use the latter for
7703 frames whose active buffer doesn't correspond to any file
7704 (e.g., '*scratch*') */
7705 - setMiniwindowImage: (BOOL) setMini
7707 id image = [[self window] miniwindowImage];
7708 NSTRACE ("[EmacsView setMiniwindowImage:%d]", setMini);
7710 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
7711 about "AppleDockIconEnabled" notwithstanding, however the set message
7712 below has its effect nonetheless. */
7713 if (image != emacsframe->output_data.ns->miniimage)
7715 if (image && [image isKindOfClass: [EmacsImage class]])
7717 [[self window] setMiniwindowImage:
7718 setMini ? emacsframe->output_data.ns->miniimage : nil];
7725 - (void) setRows: (int) r andColumns: (int) c
7727 NSTRACE ("[EmacsView setRows:%d andColumns:%d]", r, c);
7732 - (int) fullscreenState
7737 @end /* EmacsView */
7741 /* ==========================================================================
7743 EmacsWindow implementation
7745 ========================================================================== */
7747 @implementation EmacsWindow
7749 #ifdef NS_IMPL_COCOA
7750 - (id)accessibilityAttributeValue:(NSString *)attribute
7752 Lisp_Object str = Qnil;
7753 struct frame *f = SELECTED_FRAME ();
7754 struct buffer *curbuf = XBUFFER (XWINDOW (f->selected_window)->contents);
7756 NSTRACE ("[EmacsWindow accessibilityAttributeValue:]");
7758 if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
7759 return NSAccessibilityTextFieldRole;
7761 if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]
7762 && curbuf && ! NILP (BVAR (curbuf, mark_active)))
7764 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7766 else if (curbuf && [attribute isEqualToString:NSAccessibilityValueAttribute])
7768 if (! NILP (BVAR (curbuf, mark_active)))
7769 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7773 ptrdiff_t start_byte = BUF_BEGV_BYTE (curbuf);
7774 ptrdiff_t byte_range = BUF_ZV_BYTE (curbuf) - start_byte;
7775 ptrdiff_t range = BUF_ZV (curbuf) - BUF_BEGV (curbuf);
7777 if (! NILP (BVAR (curbuf, enable_multibyte_characters)))
7778 str = make_uninit_multibyte_string (range, byte_range);
7780 str = make_uninit_string (range);
7781 /* To check: This returns emacs-utf-8, which is a superset of utf-8.
7782 Is this a problem? */
7783 memcpy (SDATA (str), BYTE_POS_ADDR (start_byte), byte_range);
7790 if (CONSP (str) && SYMBOLP (XCAR (str)))
7793 if (CONSP (str) && NILP (XCDR (str)))
7798 const char *utfStr = SSDATA (str);
7799 NSString *nsStr = [NSString stringWithUTF8String: utfStr];
7804 return [super accessibilityAttributeValue:attribute];
7806 #endif /* NS_IMPL_COCOA */
7808 /* Constrain size and placement of a frame.
7810 By returning the original "frameRect", the frame is not
7811 constrained. This can lead to unwanted situations where, for
7812 example, the menu bar covers the frame.
7814 The default implementation (accessed using "super") constrains the
7815 frame to the visible area of SCREEN, minus the menu bar (if
7816 present) and the Dock. Note that default implementation also calls
7817 windowWillResize, with the frame it thinks should have. (This can
7818 make the frame exit maximized mode.)
7820 Note that this should work in situations where multiple monitors
7821 are present. Common configurations are side-by-side monitors and a
7822 monitor on top of another (e.g. when a laptop is placed under a
7824 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
7826 NSTRACE ("[EmacsWindow constrainFrameRect:" NSTRACE_FMT_RECT " toScreen:]",
7827 NSTRACE_ARG_RECT (frameRect));
7829 #ifdef NS_IMPL_COCOA
7830 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7831 // If separate spaces is on, it is like each screen is independent. There is
7832 // no spanning of frames across screens.
7833 if ([NSScreen screensHaveSeparateSpaces])
7835 NSTRACE_MSG ("Screens have separate spaces");
7836 frameRect = [super constrainFrameRect:frameRect toScreen:screen];
7837 NSTRACE_RETURN_RECT (frameRect);
7843 return constrain_frame_rect(frameRect,
7844 [(EmacsView *)[self delegate] isFullscreen]);
7848 - (void)performZoom:(id)sender
7850 NSTRACE ("[EmacsWindow performZoom:]");
7852 return [super performZoom:sender];
7855 - (void)zoom:(id)sender
7857 NSTRACE ("[EmacsWindow zoom:]");
7859 ns_update_auto_hide_menu_bar();
7861 // Below are three zoom implementations. In the final commit, the
7862 // idea is that the last should be included.
7865 // Native zoom done using the standard zoom animation. Size of the
7866 // resulting frame reduced to accommodate the Dock and, if present,
7868 [super zoom:sender];
7871 // Native zoom done using the standard zoom animation, plus an
7872 // explicit resize to cover the full screen.
7873 [super zoom:sender];
7875 // After the native zoom, resize the resulting frame to fill the
7876 // entire screen, except the menu-bar.
7878 // This works for all practical purposes. (The only minor oddity is
7879 // when transiting from full-height frame to a maximized, the
7880 // animation reduces the height of the frame slightly (to the 4
7881 // pixels needed to accommodate the Doc) before it snaps back into
7882 // full height. The user would need a very trained eye to spot
7884 NSScreen * screen = [self screen];
7887 int fs_state = [(EmacsView *)[self delegate] fullscreenState];
7889 NSTRACE_FSTYPE ("fullscreenState", fs_state);
7891 NSRect sr = [screen frame];
7892 NSRect wr = [self frame];
7893 NSTRACE_RECT ("Rect after zoom", wr);
7897 if (fs_state == FULLSCREEN_MAXIMIZED
7898 || fs_state == FULLSCREEN_HEIGHT)
7901 newWr.size.height = sr.size.height - ns_menu_bar_height(screen);
7904 if (fs_state == FULLSCREEN_MAXIMIZED
7905 || fs_state == FULLSCREEN_WIDTH)
7908 newWr.size.width = sr.size.width;
7911 if (newWr.size.width != wr.size.width
7912 || newWr.size.height != wr.size.height
7913 || newWr.origin.x != wr.origin.x
7914 || newWr.origin.y != wr.origin.y)
7916 NSTRACE_MSG ("New frame different");
7917 [self setFrame: newWr display: NO];
7921 // Non-native zoom which is done instantaneously. The resulting frame
7922 // covers the entire screen, except the menu-bar, if present.
7923 NSScreen * screen = [self screen];
7926 NSRect sr = [screen frame];
7927 sr.size.height -= ns_menu_bar_height (screen);
7929 sr = [[self delegate] windowWillUseStandardFrame:self
7931 [self setFrame: sr display: NO];
7936 - (void)setFrame:(NSRect)windowFrame
7937 display:(BOOL)displayViews
7939 NSTRACE ("[EmacsWindow setFrame:" NSTRACE_FMT_RECT " display:%d]",
7940 NSTRACE_ARG_RECT (windowFrame), displayViews);
7942 [super setFrame:windowFrame display:displayViews];
7945 - (void)setFrame:(NSRect)windowFrame
7946 display:(BOOL)displayViews
7947 animate:(BOOL)performAnimation
7949 NSTRACE ("[EmacsWindow setFrame:" NSTRACE_FMT_RECT
7950 " display:%d performAnimation:%d]",
7951 NSTRACE_ARG_RECT (windowFrame), displayViews, performAnimation);
7953 [super setFrame:windowFrame display:displayViews animate:performAnimation];
7956 - (void)setFrameTopLeftPoint:(NSPoint)point
7958 NSTRACE ("[EmacsWindow setFrameTopLeftPoint:" NSTRACE_FMT_POINT "]",
7959 NSTRACE_ARG_POINT (point));
7961 [super setFrameTopLeftPoint:point];
7963 @end /* EmacsWindow */
7966 @implementation EmacsFSWindow
7968 - (BOOL)canBecomeKeyWindow
7973 - (BOOL)canBecomeMainWindow
7980 /* ==========================================================================
7982 EmacsScroller implementation
7984 ========================================================================== */
7987 @implementation EmacsScroller
7989 /* for repeat button push */
7990 #define SCROLL_BAR_FIRST_DELAY 0.5
7991 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
7993 + (CGFloat) scrollerWidth
7995 /* TODO: if we want to allow variable widths, this is the place to do it,
7996 however neither GNUstep nor Cocoa support it very well */
7998 #if !defined (NS_IMPL_COCOA) || \
7999 MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
8000 r = [NSScroller scrollerWidth];
8002 r = [NSScroller scrollerWidthForControlSize: NSRegularControlSize
8003 scrollerStyle: NSScrollerStyleLegacy];
8009 - initFrame: (NSRect )r window: (Lisp_Object)nwin
8011 NSTRACE ("[EmacsScroller initFrame: window:]");
8013 r.size.width = [EmacsScroller scrollerWidth];
8014 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
8015 [self setContinuous: YES];
8016 [self setEnabled: YES];
8018 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
8019 locked against the top and bottom edges, and right edge on OS X, where
8020 scrollers are on right. */
8021 #ifdef NS_IMPL_GNUSTEP
8022 [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
8024 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
8027 window = XWINDOW (nwin);
8029 pixel_height = NSHeight (r);
8030 if (pixel_height == 0) pixel_height = 1;
8031 min_portion = 20 / pixel_height;
8033 frame = XFRAME (window->frame);
8034 if (FRAME_LIVE_P (frame))
8037 EmacsView *view = FRAME_NS_VIEW (frame);
8038 NSView *sview = [[view window] contentView];
8039 NSArray *subs = [sview subviews];
8041 /* disable optimization stopping redraw of other scrollbars */
8042 view->scrollbarsNeedingUpdate = 0;
8043 for (i =[subs count]-1; i >= 0; i--)
8044 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
8045 view->scrollbarsNeedingUpdate++;
8046 [sview addSubview: self];
8049 /* [self setFrame: r]; */
8055 - (void)setFrame: (NSRect)newRect
8057 NSTRACE ("[EmacsScroller setFrame:]");
8059 /* block_input (); */
8060 pixel_height = NSHeight (newRect);
8061 if (pixel_height == 0) pixel_height = 1;
8062 min_portion = 20 / pixel_height;
8063 [super setFrame: newRect];
8064 /* unblock_input (); */
8070 NSTRACE ("[EmacsScroller dealloc]");
8072 wset_vertical_scroll_bar (window, Qnil);
8080 NSTRACE ("[EmacsScroller condemn]");
8088 NSTRACE ("[EmacsScroller reprieve]");
8096 NSTRACE ("[EmacsScroller judge]");
8097 bool ret = condemned;
8102 /* ensure other scrollbar updates after deletion */
8103 view = (EmacsView *)FRAME_NS_VIEW (frame);
8105 view->scrollbarsNeedingUpdate++;
8107 wset_vertical_scroll_bar (window, Qnil);
8109 [self removeFromSuperview];
8117 - (void)resetCursorRects
8119 NSRect visible = [self visibleRect];
8120 NSTRACE ("[EmacsScroller resetCursorRects]");
8122 if (!NSIsEmptyRect (visible))
8123 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
8124 [[NSCursor arrowCursor] setOnMouseEntered: YES];
8128 - (int) checkSamePosition: (int) position portion: (int) portion
8131 return em_position ==position && em_portion ==portion && em_whole ==whole
8132 && portion != whole; /* needed for resize empty buf */
8136 - setPosition: (int)position portion: (int)portion whole: (int)whole
8138 NSTRACE ("[EmacsScroller setPosition:portion:whole:]");
8140 em_position = position;
8141 em_portion = portion;
8144 if (portion >= whole)
8146 #ifdef NS_IMPL_COCOA
8147 [self setKnobProportion: 1.0];
8148 [self setDoubleValue: 1.0];
8150 [self setFloatValue: 0.0 knobProportion: 1.0];
8157 portion = max ((float)whole*min_portion/pixel_height, portion);
8158 pos = (float)position / (whole - portion);
8159 por = (CGFloat)portion/whole;
8160 #ifdef NS_IMPL_COCOA
8161 [self setKnobProportion: por];
8162 [self setDoubleValue: pos];
8164 [self setFloatValue: pos knobProportion: por];
8171 /* set up emacs_event */
8172 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
8176 NSTRACE ("[EmacsScroller sendScrollEventAtLoc:fromEvent:]");
8181 emacs_event->part = last_hit_part;
8182 emacs_event->code = 0;
8183 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
8184 XSETWINDOW (win, window);
8185 emacs_event->frame_or_window = win;
8186 emacs_event->timestamp = EV_TIMESTAMP (e);
8187 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
8188 emacs_event->arg = Qnil;
8189 XSETINT (emacs_event->x, loc * pixel_height);
8190 XSETINT (emacs_event->y, pixel_height-20);
8194 n_emacs_events_pending++;
8195 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
8198 hold_event (emacs_event);
8199 EVENT_INIT (*emacs_event);
8200 ns_send_appdefined (-1);
8204 /* called manually thru timer to implement repeated button action w/hold-down */
8205 - repeatScroll: (NSTimer *)scrollEntry
8207 NSEvent *e = [[self window] currentEvent];
8208 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
8209 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
8211 NSTRACE ("[EmacsScroller repeatScroll:]");
8213 /* clear timer if need be */
8214 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
8216 [scroll_repeat_entry invalidate];
8217 [scroll_repeat_entry release];
8218 scroll_repeat_entry = nil;
8224 = [[NSTimer scheduledTimerWithTimeInterval:
8225 SCROLL_BAR_CONTINUOUS_DELAY
8227 selector: @selector (repeatScroll:)
8233 [self sendScrollEventAtLoc: 0 fromEvent: e];
8238 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
8239 mouseDragged events without going into a modal loop. */
8240 - (void)mouseDown: (NSEvent *)e
8243 /* hitPart is only updated AFTER event is passed on */
8244 NSScrollerPart part = [self testPart: [e locationInWindow]];
8245 CGFloat inc = 0.0, loc, kloc, pos;
8248 NSTRACE ("[EmacsScroller mouseDown:]");
8252 case NSScrollerDecrementPage:
8253 last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
8254 case NSScrollerIncrementPage:
8255 last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
8256 case NSScrollerDecrementLine:
8257 last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
8258 case NSScrollerIncrementLine:
8259 last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
8260 case NSScrollerKnob:
8261 last_hit_part = scroll_bar_handle; break;
8262 case NSScrollerKnobSlot: /* GNUstep-only */
8263 last_hit_part = scroll_bar_move_ratio; break;
8264 default: /* NSScrollerNoPart? */
8265 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
8272 pos = 0; /* ignored */
8274 /* set a timer to repeat, as we can't let superclass do this modally */
8276 = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
8278 selector: @selector (repeatScroll:)
8285 /* handle, or on GNUstep possibly slot */
8286 NSEvent *fake_event;
8288 /* compute float loc in slot and mouse offset on knob */
8289 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
8291 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
8297 else if (loc >= NSHeight (sr))
8299 loc = NSHeight (sr);
8307 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
8309 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
8311 last_mouse_offset = kloc;
8313 /* if knob, tell emacs a location offset by knob pos
8314 (to indicate top of handle) */
8315 if (part == NSScrollerKnob)
8316 pos = (loc - last_mouse_offset) / NSHeight (sr);
8318 /* else this is a slot click on GNUstep: go straight there */
8319 pos = loc / NSHeight (sr);
8321 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
8322 fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
8323 location: [e locationInWindow]
8324 modifierFlags: [e modifierFlags]
8325 timestamp: [e timestamp]
8326 windowNumber: [e windowNumber]
8327 context: [e context]
8328 eventNumber: [e eventNumber]
8329 clickCount: [e clickCount]
8330 pressure: [e pressure]];
8331 [super mouseUp: fake_event];
8334 if (part != NSScrollerKnob)
8335 [self sendScrollEventAtLoc: pos fromEvent: e];
8339 /* Called as we manually track scroller drags, rather than superclass. */
8340 - (void)mouseDragged: (NSEvent *)e
8345 NSTRACE ("[EmacsScroller mouseDragged:]");
8347 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
8349 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
8355 else if (loc >= NSHeight (sr) + last_mouse_offset)
8357 loc = NSHeight (sr) + last_mouse_offset;
8360 pos = (loc - last_mouse_offset) / NSHeight (sr);
8361 [self sendScrollEventAtLoc: pos fromEvent: e];
8365 - (void)mouseUp: (NSEvent *)e
8367 NSTRACE ("[EmacsScroller mouseUp:]");
8369 if (scroll_repeat_entry)
8371 [scroll_repeat_entry invalidate];
8372 [scroll_repeat_entry release];
8373 scroll_repeat_entry = nil;
8375 last_hit_part = scroll_bar_above_handle;
8379 /* treat scrollwheel events in the bar as though they were in the main window */
8380 - (void) scrollWheel: (NSEvent *)theEvent
8382 NSTRACE ("[EmacsScroller scrollWheel:]");
8384 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
8385 [view mouseDown: theEvent];
8388 @end /* EmacsScroller */
8391 #ifdef NS_IMPL_GNUSTEP
8392 /* Dummy class to get rid of startup warnings. */
8393 @implementation EmacsDocument
8399 /* ==========================================================================
8401 Font-related functions; these used to be in nsfaces.m
8403 ========================================================================== */
8407 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
8409 struct font *font = XFONT_OBJECT (font_object);
8410 EmacsView *view = FRAME_NS_VIEW (f);
8411 int font_ascent, font_descent;
8414 fontset = fontset_from_font (font_object);
8415 FRAME_FONTSET (f) = fontset;
8417 if (FRAME_FONT (f) == font)
8418 /* This font is already set in frame F. There's nothing more to
8422 FRAME_FONT (f) = font;
8424 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
8425 FRAME_COLUMN_WIDTH (f) = font->average_width;
8426 get_font_ascent_descent (font, &font_ascent, &font_descent);
8427 FRAME_LINE_HEIGHT (f) = font_ascent + font_descent;
8429 /* Compute the scroll bar width in character columns. */
8430 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
8432 int wid = FRAME_COLUMN_WIDTH (f);
8433 FRAME_CONFIG_SCROLL_BAR_COLS (f)
8434 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
8438 int wid = FRAME_COLUMN_WIDTH (f);
8439 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
8442 /* Compute the scroll bar height in character lines. */
8443 if (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) > 0)
8445 int height = FRAME_LINE_HEIGHT (f);
8446 FRAME_CONFIG_SCROLL_BAR_LINES (f)
8447 = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + height - 1) / height;
8451 int height = FRAME_LINE_HEIGHT (f);
8452 FRAME_CONFIG_SCROLL_BAR_LINES (f) = (14 + height - 1) / height;
8455 /* Now make the frame display the given font. */
8456 if (FRAME_NS_WINDOW (f) != 0 && ! [view isFullscreen])
8457 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
8458 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 3,
8465 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
8466 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
8470 ns_xlfd_to_fontname (const char *xlfd)
8471 /* --------------------------------------------------------------------------
8472 Convert an X font name (XLFD) to an NS font name.
8473 Only family is used.
8474 The string returned is temporarily allocated.
8475 -------------------------------------------------------------------------- */
8477 char *name = xmalloc (180);
8481 if (!strncmp (xlfd, "--", 2))
8482 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
8484 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
8486 /* stopgap for malformed XLFD input */
8487 if (strlen (name) == 0)
8488 strcpy (name, "Monaco");
8490 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
8491 also uppercase after '-' or ' ' */
8492 name[0] = c_toupper (name[0]);
8493 for (len =strlen (name), i =0; i<len; i++)
8499 name[i+1] = c_toupper (name[i+1]);
8501 else if (name[i] == '_')
8505 name[i+1] = c_toupper (name[i+1]);
8508 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
8509 ret = [[NSString stringWithUTF8String: name] UTF8String];
8516 syms_of_nsterm (void)
8518 NSTRACE ("syms_of_nsterm");
8520 ns_antialias_threshold = 10.0;
8522 /* from 23+ we need to tell emacs what modifiers there are.. */
8523 DEFSYM (Qmodifier_value, "modifier-value");
8524 DEFSYM (Qalt, "alt");
8525 DEFSYM (Qhyper, "hyper");
8526 DEFSYM (Qmeta, "meta");
8527 DEFSYM (Qsuper, "super");
8528 DEFSYM (Qcontrol, "control");
8529 DEFSYM (QUTF8_STRING, "UTF8_STRING");
8531 DEFSYM (Qfile, "file");
8532 DEFSYM (Qurl, "url");
8534 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
8535 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
8536 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
8537 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
8538 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
8540 DEFVAR_LISP ("ns-input-file", ns_input_file,
8541 "The file specified in the last NS event.");
8542 ns_input_file =Qnil;
8544 DEFVAR_LISP ("ns-working-text", ns_working_text,
8545 "String for visualizing working composition sequence.");
8546 ns_working_text =Qnil;
8548 DEFVAR_LISP ("ns-input-font", ns_input_font,
8549 "The font specified in the last NS event.");
8550 ns_input_font =Qnil;
8552 DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
8553 "The fontsize specified in the last NS event.");
8554 ns_input_fontsize =Qnil;
8556 DEFVAR_LISP ("ns-input-line", ns_input_line,
8557 "The line specified in the last NS event.");
8558 ns_input_line =Qnil;
8560 DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
8561 "The service name specified in the last NS event.");
8562 ns_input_spi_name =Qnil;
8564 DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
8565 "The service argument specified in the last NS event.");
8566 ns_input_spi_arg =Qnil;
8568 DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
8569 "This variable describes the behavior of the alternate or option key.\n\
8570 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8571 Set to none means that the alternate / option key is not interpreted by Emacs\n\
8572 at all, allowing it to be used at a lower level for accented character entry.");
8573 ns_alternate_modifier = Qmeta;
8575 DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
8576 "This variable describes the behavior of the right alternate or option key.\n\
8577 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8578 Set to left means be the same key as `ns-alternate-modifier'.\n\
8579 Set to none means that the alternate / option key is not interpreted by Emacs\n\
8580 at all, allowing it to be used at a lower level for accented character entry.");
8581 ns_right_alternate_modifier = Qleft;
8583 DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
8584 "This variable describes the behavior of the command key.\n\
8585 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
8586 ns_command_modifier = Qsuper;
8588 DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
8589 "This variable describes the behavior of the right command key.\n\
8590 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8591 Set to left means be the same key as `ns-command-modifier'.\n\
8592 Set to none means that the command / option key is not interpreted by Emacs\n\
8593 at all, allowing it to be used at a lower level for accented character entry.");
8594 ns_right_command_modifier = Qleft;
8596 DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
8597 "This variable describes the behavior of the control key.\n\
8598 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
8599 ns_control_modifier = Qcontrol;
8601 DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
8602 "This variable describes the behavior of the right control key.\n\
8603 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8604 Set to left means be the same key as `ns-control-modifier'.\n\
8605 Set to none means that the control / option key is not interpreted by Emacs\n\
8606 at all, allowing it to be used at a lower level for accented character entry.");
8607 ns_right_control_modifier = Qleft;
8609 DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
8610 "This variable describes the behavior of the function key (on laptops).\n\
8611 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8612 Set to none means that the function key is not interpreted by Emacs at all,\n\
8613 allowing it to be used at a lower level for accented character entry.");
8614 ns_function_modifier = Qnone;
8616 DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
8617 "Non-nil (the default) means to render text antialiased.");
8618 ns_antialias_text = Qt;
8620 DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
8621 "Whether to confirm application quit using dialog.");
8622 ns_confirm_quit = Qnil;
8624 DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
8625 doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
8626 Only works on OSX 10.6 or later. */);
8627 ns_auto_hide_menu_bar = Qnil;
8629 DEFVAR_BOOL ("ns-use-native-fullscreen", ns_use_native_fullscreen,
8630 doc: /*Non-nil means to use native fullscreen on OSX >= 10.7.
8631 Nil means use fullscreen the old (< 10.7) way. The old way works better with
8632 multiple monitors, but lacks tool bar. This variable is ignored on OSX < 10.7.
8633 Default is t for OSX >= 10.7, nil otherwise. */);
8634 #ifdef HAVE_NATIVE_FS
8635 ns_use_native_fullscreen = YES;
8637 ns_use_native_fullscreen = NO;
8639 ns_last_use_native_fullscreen = ns_use_native_fullscreen;
8641 DEFVAR_BOOL ("ns-use-fullscreen-animation", ns_use_fullscreen_animation,
8642 doc: /*Non-nil means use animation on non-native fullscreen.
8643 For native fullscreen, this does nothing.
8644 Default is nil. */);
8645 ns_use_fullscreen_animation = NO;
8647 DEFVAR_BOOL ("ns-use-srgb-colorspace", ns_use_srgb_colorspace,
8648 doc: /*Non-nil means to use sRGB colorspace on OSX >= 10.7.
8649 Note that this does not apply to images.
8650 This variable is ignored on OSX < 10.7 and GNUstep. */);
8651 ns_use_srgb_colorspace = YES;
8653 /* TODO: move to common code */
8654 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
8655 doc: /* Which toolkit scroll bars Emacs uses, if any.
8656 A value of nil means Emacs doesn't use toolkit scroll bars.
8657 With the X Window system, the value is a symbol describing the
8658 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
8659 With MS Windows or Nextstep, the value is t. */);
8660 Vx_toolkit_scroll_bars = Qt;
8662 DEFVAR_BOOL ("x-use-underline-position-properties",
8663 x_use_underline_position_properties,
8664 doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
8665 A value of nil means ignore them. If you encounter fonts with bogus
8666 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
8667 to 4.1, set this to nil. */);
8668 x_use_underline_position_properties = 0;
8670 DEFVAR_BOOL ("x-underline-at-descent-line",
8671 x_underline_at_descent_line,
8672 doc: /* Non-nil means to draw the underline at the same place as the descent line.
8673 A value of nil means to draw the underline according to the value of the
8674 variable `x-use-underline-position-properties', which is usually at the
8675 baseline level. The default value is nil. */);
8676 x_underline_at_descent_line = 0;
8678 /* Tell Emacs about this window system. */
8679 Fprovide (Qns, Qnil);
8681 DEFSYM (Qcocoa, "cocoa");
8682 DEFSYM (Qgnustep, "gnustep");
8684 #ifdef NS_IMPL_COCOA
8685 Fprovide (Qcocoa, Qnil);
8688 Fprovide (Qgnustep, Qnil);