1 /* NeXT/Open/GNUstep / MacOSX communication module. -*- coding: utf-8 -*-
3 Copyright (C) 1989, 1993-1994, 2005-2006, 2008-2015 Free Software
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 Originally by Carl Edman
23 Updated by Christian Limpach (chris@nice.ch)
24 OpenStep/Rhapsody port by Scott Bender (sbender@harmony-ds.com)
25 MacOSX/Aqua port by Christophe de Dinechin (descubes@earthlink.net)
26 GNUstep port and post-20 update by Adrian Robert (arobert@cogsci.ucsd.edu)
29 /* This should be the first include, as it may set up #defines affecting
30 interpretation of even the system includes. */
36 #include <sys/types.h>
42 #include <c-strcase.h>
46 #include "blockinput.h"
47 #include "sysselect.h"
50 #include "character.h"
52 #include "composite.h"
55 #include "termhooks.h"
63 #ifdef NS_IMPL_GNUSTEP
72 extern NSString *NSMenuDidBeginTrackingNotification;
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];
588 ns_timeout (int usecs)
589 /* --------------------------------------------------------------------------
590 Blocking timer utility used by ns_ring_bell
591 -------------------------------------------------------------------------- */
593 struct timespec wakeup = timespec_add (current_timespec (),
594 make_timespec (0, usecs * 1000));
596 /* Keep waiting until past the time wakeup. */
599 struct timespec timeout, now = current_timespec ();
600 if (timespec_cmp (wakeup, now) <= 0)
602 timeout = timespec_sub (wakeup, now);
604 /* Try to wait that long--but we might wake up sooner. */
605 pselect (0, NULL, NULL, NULL, &timeout, NULL);
611 ns_release_object (void *obj)
612 /* --------------------------------------------------------------------------
613 Release an object (callable from C)
614 -------------------------------------------------------------------------- */
621 ns_retain_object (void *obj)
622 /* --------------------------------------------------------------------------
623 Retain an object (callable from C)
624 -------------------------------------------------------------------------- */
631 ns_alloc_autorelease_pool (void)
632 /* --------------------------------------------------------------------------
633 Allocate a pool for temporary objects (callable from C)
634 -------------------------------------------------------------------------- */
636 return [[NSAutoreleasePool alloc] init];
641 ns_release_autorelease_pool (void *pool)
642 /* --------------------------------------------------------------------------
643 Free a pool and temporary objects it refers to (callable from C)
644 -------------------------------------------------------------------------- */
646 ns_release_object (pool);
650 /* True, if the menu bar should be hidden. */
653 ns_menu_bar_should_be_hidden (void)
655 return !NILP (ns_auto_hide_menu_bar)
656 && [NSApp respondsToSelector:@selector(setPresentationOptions:)];
661 ns_menu_bar_height (NSScreen *screen)
662 /* The height of the menu bar, if visible. */
664 // NSTRACE ("ns_menu_bar_height");
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_MSG (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)
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);
771 menu_bar_height = max(menu_bar_height, ns_menu_bar_height (s));
775 NSTRACE_RECT ("multiscreenRect", multiscreenRect);
777 NSTRACE_MSG ("menu_bar_height: %d", menu_bar_height);
779 if (multiscreenRect.size.width == 0
780 || multiscreenRect.size.height == 0)
782 // Failed to find any monitor, give up.
783 NSTRACE_MSG ("multiscreenRect empty");
784 NSTRACE_RETURN_RECT (frameRect);
789 // --------------------
790 // Find a suitable placement.
793 if (ns_menu_bar_should_be_hidden())
795 // When the menu bar is hidden, the user may place part of the
796 // frame above the top of the screen, for example to hide the
799 // Hence, keep the original position.
803 // Ensure that the frame is below the menu bar, or below the top
806 // This assume that the menu bar is placed at the top in the
807 // rectangle that covers the monitors. (It doesn't have to be,
808 // but if it's not it's hard to do anything useful.)
809 CGFloat topOfWorkArea = (multiscreenRect.origin.y
810 + multiscreenRect.size.height
813 CGFloat topOfFrame = frameRect.origin.y + frameRect.size.height;
814 if (topOfFrame > topOfWorkArea)
816 frameRect.origin.y -= topOfFrame - topOfWorkArea;
817 NSTRACE_RECT ("After placement adjust", frameRect);
821 // Include the following section to restrict frame to the screens.
822 // (If so, update it to allow the frame to stretch down below the
825 // --------------------
826 // Ensure frame doesn't stretch below the screens.
829 CGFloat diff = multiscreenRect.origin.y - frameRect.origin.y;
833 frameRect.origin.y = multiscreenRect.origin.y;
834 frameRect.size.height -= diff;
838 NSTRACE_RETURN_RECT (frameRect);
844 ns_constrain_all_frames (void)
845 /* --------------------------------------------------------------------------
846 Ensure that the menu bar doesn't cover any frames.
847 -------------------------------------------------------------------------- */
849 Lisp_Object tail, frame;
851 NSTRACE ("ns_constrain_all_frames");
855 FOR_EACH_FRAME (tail, frame)
857 struct frame *f = XFRAME (frame);
860 EmacsView *view = FRAME_NS_VIEW (f);
862 if (![view isFullscreen])
865 setFrame:constrain_frame_rect([[view window] frame])
876 ns_update_auto_hide_menu_bar (void)
877 /* --------------------------------------------------------------------------
878 Show or hide the menu bar, based on user setting.
879 -------------------------------------------------------------------------- */
882 NSTRACE ("ns_update_auto_hide_menu_bar");
886 if (NSApp != nil && [NSApp isActive])
888 // Note, "setPresentationOptions" triggers an error unless the
889 // application is active.
890 BOOL menu_bar_should_be_hidden = ns_menu_bar_should_be_hidden ();
892 if (menu_bar_should_be_hidden != ns_menu_bar_is_hidden)
894 NSApplicationPresentationOptions options
895 = NSApplicationPresentationDefault;
897 if (menu_bar_should_be_hidden)
898 options |= NSApplicationPresentationAutoHideMenuBar
899 | NSApplicationPresentationAutoHideDock;
901 [NSApp setPresentationOptions: options];
903 ns_menu_bar_is_hidden = menu_bar_should_be_hidden;
905 if (!ns_menu_bar_is_hidden)
907 ns_constrain_all_frames ();
918 ns_update_begin (struct frame *f)
919 /* --------------------------------------------------------------------------
920 Prepare for a grouped sequence of drawing calls
921 external (RIF) call; whole frame, called before update_window_begin
922 -------------------------------------------------------------------------- */
924 EmacsView *view = FRAME_NS_VIEW (f);
925 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_begin");
927 ns_update_auto_hide_menu_bar ();
930 if ([view isFullscreen] && [view fsIsNative])
932 // Fix reappearing tool bar in fullscreen for OSX 10.7
933 BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (f) ? YES : NO;
934 NSToolbar *toolbar = [FRAME_NS_VIEW (f) toolbar];
935 if (! tbar_visible != ! [toolbar isVisible])
936 [toolbar setVisible: tbar_visible];
940 ns_updating_frame = f;
943 /* drawRect may have been called for say the minibuffer, and then clip path
944 is for the minibuffer. But the display engine may draw more because
945 we have set the frame as garbaged. So reset clip path to the whole
950 NSRect r = [view frame];
951 NSRect cr = [[view window] frame];
952 /* If a large frame size is set, r may be larger than the window frame
953 before constrained. In that case don't change the clip path, as we
954 will clear in to the tool bar and title bar. */
956 + FRAME_NS_TITLEBAR_HEIGHT (f)
957 + FRAME_TOOLBAR_HEIGHT (f) <= cr.size.height)
959 bp = [[NSBezierPath bezierPathWithRect: r] retain];
966 #ifdef NS_IMPL_GNUSTEP
967 uRect = NSMakeRect (0, 0, 0, 0);
973 ns_update_window_begin (struct window *w)
974 /* --------------------------------------------------------------------------
975 Prepare for a grouped sequence of drawing calls
976 external (RIF) call; for one window, called after update_begin
977 -------------------------------------------------------------------------- */
979 struct frame *f = XFRAME (WINDOW_FRAME (w));
980 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
982 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_window_begin");
983 w->output_cursor = w->cursor;
987 if (f == hlinfo->mouse_face_mouse_frame)
989 /* Don't do highlighting for mouse motion during the update. */
990 hlinfo->mouse_face_defer = 1;
992 /* If the frame needs to be redrawn,
993 simply forget about any prior mouse highlighting. */
994 if (FRAME_GARBAGED_P (f))
995 hlinfo->mouse_face_window = Qnil;
997 /* (further code for mouse faces ifdef'd out in other terms elided) */
1005 ns_update_window_end (struct window *w, bool cursor_on_p,
1006 bool mouse_face_overwritten_p)
1007 /* --------------------------------------------------------------------------
1008 Finished a grouped sequence of drawing calls
1009 external (RIF) call; for one window called before update_end
1010 -------------------------------------------------------------------------- */
1012 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_window_end");
1014 /* note: this fn is nearly identical in all terms */
1015 if (!w->pseudo_window_p)
1020 display_and_set_cursor (w, 1,
1021 w->output_cursor.hpos, w->output_cursor.vpos,
1022 w->output_cursor.x, w->output_cursor.y);
1024 if (draw_window_fringes (w, 1))
1026 if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
1027 x_draw_right_divider (w);
1029 x_draw_vertical_border (w);
1035 /* If a row with mouse-face was overwritten, arrange for
1036 frame_up_to_date to redisplay the mouse highlight. */
1037 if (mouse_face_overwritten_p)
1038 reset_mouse_highlight (MOUSE_HL_INFO (XFRAME (w->frame)));
1043 ns_update_end (struct frame *f)
1044 /* --------------------------------------------------------------------------
1045 Finished a grouped sequence of drawing calls
1046 external (RIF) call; for whole frame, called after update_window_end
1047 -------------------------------------------------------------------------- */
1049 EmacsView *view = FRAME_NS_VIEW (f);
1051 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_end");
1053 /* if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
1054 MOUSE_HL_INFO (f)->mouse_face_defer = 0;
1059 [[view window] flushWindow];
1062 ns_updating_frame = NULL;
1066 ns_focus (struct frame *f, NSRect *r, int n)
1067 /* --------------------------------------------------------------------------
1068 Internal: Focus on given frame. During small local updates this is used to
1069 draw, however during large updates, ns_update_begin and ns_update_end are
1070 called to wrap the whole thing, in which case these calls are stubbed out.
1071 Except, on GNUstep, we accumulate the rectangle being drawn into, because
1072 the back end won't do this automatically, and will just end up flushing
1074 -------------------------------------------------------------------------- */
1076 NSTRACE_WHEN (NSTRACE_GROUP_FOCUS, "ns_focus");
1079 NSTRACE_RECT ("r", *r);
1082 if (f != ns_updating_frame)
1084 NSView *view = FRAME_NS_VIEW (f);
1085 if (view != focus_view)
1087 if (focus_view != NULL)
1089 [focus_view unlockFocus];
1090 [[focus_view window] flushWindow];
1097 /*if (view) debug_lock++; */
1104 [[NSGraphicsContext currentContext] saveGraphicsState];
1106 NSRectClipList (r, 2);
1115 ns_unfocus (struct frame *f)
1116 /* --------------------------------------------------------------------------
1117 Internal: Remove focus on given frame
1118 -------------------------------------------------------------------------- */
1120 NSTRACE_WHEN (NSTRACE_GROUP_FOCUS, "ns_unfocus");
1124 [[NSGraphicsContext currentContext] restoreGraphicsState];
1128 if (f != ns_updating_frame)
1130 if (focus_view != NULL)
1132 [focus_view unlockFocus];
1133 [[focus_view window] flushWindow];
1142 ns_clip_to_row (struct window *w, struct glyph_row *row,
1143 enum glyph_row_area area, BOOL gc)
1144 /* --------------------------------------------------------------------------
1145 Internal (but parallels other terms): Focus drawing on given row
1146 -------------------------------------------------------------------------- */
1148 struct frame *f = XFRAME (WINDOW_FRAME (w));
1150 int window_x, window_y, window_width;
1152 window_box (w, area, &window_x, &window_y, &window_width, 0);
1154 clip_rect.origin.x = window_x;
1155 clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
1156 clip_rect.origin.y = max (clip_rect.origin.y, window_y);
1157 clip_rect.size.width = window_width;
1158 clip_rect.size.height = row->visible_height;
1160 ns_focus (f, &clip_rect, 1);
1165 ns_ring_bell (struct frame *f)
1166 /* --------------------------------------------------------------------------
1168 -------------------------------------------------------------------------- */
1170 NSTRACE ("ns_ring_bell");
1173 NSAutoreleasePool *pool;
1174 struct frame *frame = SELECTED_FRAME ();
1178 pool = [[NSAutoreleasePool alloc] init];
1180 view = FRAME_NS_VIEW (frame);
1184 NSPoint dim = NSMakePoint (128, 128);
1187 r.origin.x += (r.size.width - dim.x) / 2;
1188 r.origin.y += (r.size.height - dim.y) / 2;
1189 r.size.width = dim.x;
1190 r.size.height = dim.y;
1191 surr = NSInsetRect (r, -2, -2);
1192 ns_focus (frame, &surr, 1);
1193 [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
1194 [ns_lookup_indexed_color (NS_FACE_FOREGROUND
1195 (FRAME_DEFAULT_FACE (frame)), frame) set];
1197 [[view window] flushWindow];
1198 ns_timeout (150000);
1199 [[view window] restoreCachedImage];
1200 [[view window] flushWindow];
1212 /* ==========================================================================
1214 Frame / window manager related functions
1216 ========================================================================== */
1220 ns_raise_frame (struct frame *f)
1221 /* --------------------------------------------------------------------------
1222 Bring window to foreground and make it active
1223 -------------------------------------------------------------------------- */
1227 check_window_system (f);
1228 view = FRAME_NS_VIEW (f);
1230 if (FRAME_VISIBLE_P (f))
1231 [[view window] makeKeyAndOrderFront: NSApp];
1237 ns_lower_frame (struct frame *f)
1238 /* --------------------------------------------------------------------------
1240 -------------------------------------------------------------------------- */
1244 check_window_system (f);
1245 view = FRAME_NS_VIEW (f);
1247 [[view window] orderBack: NSApp];
1253 ns_frame_raise_lower (struct frame *f, bool raise)
1254 /* --------------------------------------------------------------------------
1256 -------------------------------------------------------------------------- */
1258 NSTRACE ("ns_frame_raise_lower");
1268 ns_frame_rehighlight (struct frame *frame)
1269 /* --------------------------------------------------------------------------
1270 External (hook): called on things like window switching within frame
1271 -------------------------------------------------------------------------- */
1273 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
1274 struct frame *old_highlight = dpyinfo->x_highlight_frame;
1276 NSTRACE ("ns_frame_rehighlight");
1277 if (dpyinfo->x_focus_frame)
1279 dpyinfo->x_highlight_frame
1280 = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1281 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1282 : dpyinfo->x_focus_frame);
1283 if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
1285 fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
1286 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
1290 dpyinfo->x_highlight_frame = 0;
1292 if (dpyinfo->x_highlight_frame &&
1293 dpyinfo->x_highlight_frame != old_highlight)
1297 x_update_cursor (old_highlight, 1);
1298 x_set_frame_alpha (old_highlight);
1300 if (dpyinfo->x_highlight_frame)
1302 x_update_cursor (dpyinfo->x_highlight_frame, 1);
1303 x_set_frame_alpha (dpyinfo->x_highlight_frame);
1310 x_make_frame_visible (struct frame *f)
1311 /* --------------------------------------------------------------------------
1312 External: Show the window (X11 semantics)
1313 -------------------------------------------------------------------------- */
1315 NSTRACE ("x_make_frame_visible");
1316 /* XXX: at some points in past this was not needed, as the only place that
1317 called this (frame.c:Fraise_frame ()) also called raise_lower;
1318 if this ends up the case again, comment this out again. */
1319 if (!FRAME_VISIBLE_P (f))
1321 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1323 SET_FRAME_VISIBLE (f, 1);
1326 /* Making a new frame from a fullscreen frame will make the new frame
1327 fullscreen also. So skip handleFS as this will print an error. */
1328 if ([view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH
1329 && [view isFullscreen])
1332 if (f->want_fullscreen != FULLSCREEN_NONE)
1343 x_make_frame_invisible (struct frame *f)
1344 /* --------------------------------------------------------------------------
1345 External: Hide the window (X11 semantics)
1346 -------------------------------------------------------------------------- */
1349 NSTRACE ("x_make_frame_invisible");
1350 check_window_system (f);
1351 view = FRAME_NS_VIEW (f);
1352 [[view window] orderOut: NSApp];
1353 SET_FRAME_VISIBLE (f, 0);
1354 SET_FRAME_ICONIFIED (f, 0);
1359 x_iconify_frame (struct frame *f)
1360 /* --------------------------------------------------------------------------
1361 External: Iconify window
1362 -------------------------------------------------------------------------- */
1365 struct ns_display_info *dpyinfo;
1367 NSTRACE ("x_iconify_frame");
1368 check_window_system (f);
1369 view = FRAME_NS_VIEW (f);
1370 dpyinfo = FRAME_DISPLAY_INFO (f);
1372 if (dpyinfo->x_highlight_frame == f)
1373 dpyinfo->x_highlight_frame = 0;
1375 if ([[view window] windowNumber] <= 0)
1377 /* the window is still deferred. Make it very small, bring it
1378 on screen and order it out. */
1379 NSRect s = { { 100, 100}, {0, 0} };
1381 t = [[view window] frame];
1382 [[view window] setFrame: s display: NO];
1383 [[view window] orderBack: NSApp];
1384 [[view window] orderOut: NSApp];
1385 [[view window] setFrame: t display: NO];
1387 [[view window] miniaturize: NSApp];
1390 /* Free X resources of frame F. */
1393 x_free_frame_resources (struct frame *f)
1396 struct ns_display_info *dpyinfo;
1397 Mouse_HLInfo *hlinfo;
1399 NSTRACE ("x_free_frame_resources");
1400 check_window_system (f);
1401 view = FRAME_NS_VIEW (f);
1402 dpyinfo = FRAME_DISPLAY_INFO (f);
1403 hlinfo = MOUSE_HL_INFO (f);
1405 [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1409 free_frame_menubar (f);
1410 free_frame_faces (f);
1412 if (f == dpyinfo->x_focus_frame)
1413 dpyinfo->x_focus_frame = 0;
1414 if (f == dpyinfo->x_highlight_frame)
1415 dpyinfo->x_highlight_frame = 0;
1416 if (f == hlinfo->mouse_face_mouse_frame)
1417 reset_mouse_highlight (hlinfo);
1419 if (f->output_data.ns->miniimage != nil)
1420 [f->output_data.ns->miniimage release];
1422 [[view window] close];
1425 xfree (f->output_data.ns);
1431 x_destroy_window (struct frame *f)
1432 /* --------------------------------------------------------------------------
1433 External: Delete the window
1434 -------------------------------------------------------------------------- */
1436 NSTRACE ("x_destroy_window");
1437 check_window_system (f);
1438 x_free_frame_resources (f);
1444 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1445 /* --------------------------------------------------------------------------
1446 External: Position the window
1447 -------------------------------------------------------------------------- */
1449 NSView *view = FRAME_NS_VIEW (f);
1450 NSArray *screens = [NSScreen screens];
1451 NSScreen *fscreen = [screens objectAtIndex: 0];
1452 NSScreen *screen = [[view window] screen];
1454 NSTRACE ("x_set_offset");
1461 if (view != nil && screen && fscreen)
1463 f->left_pos = f->size_hint_flags & XNegative
1464 ? [screen visibleFrame].size.width + f->left_pos - FRAME_PIXEL_WIDTH (f)
1466 /* We use visibleFrame here to take menu bar into account.
1467 Ideally we should also adjust left/top with visibleFrame.origin. */
1469 f->top_pos = f->size_hint_flags & YNegative
1470 ? ([screen visibleFrame].size.height + f->top_pos
1471 - FRAME_PIXEL_HEIGHT (f) - FRAME_NS_TITLEBAR_HEIGHT (f)
1472 - FRAME_TOOLBAR_HEIGHT (f))
1474 #ifdef NS_IMPL_GNUSTEP
1475 if (f->left_pos < 100)
1476 f->left_pos = 100; /* don't overlap menu */
1478 /* Constrain the setFrameTopLeftPoint so we don't move behind the
1480 NSPoint pt = NSMakePoint (SCREENMAXBOUND (f->left_pos),
1481 SCREENMAXBOUND ([fscreen frame].size.height
1483 NSTRACE_POINT ("setFrameTopLeftPoint", pt);
1484 [[view window] setFrameTopLeftPoint: pt];
1485 f->size_hint_flags &= ~(XNegative|YNegative);
1493 x_set_window_size (struct frame *f,
1494 bool change_gravity,
1498 /* --------------------------------------------------------------------------
1499 Adjust window pixel size based on given character grid size
1500 Impl is a bit more complex than other terms, need to do some
1502 -------------------------------------------------------------------------- */
1504 EmacsView *view = FRAME_NS_VIEW (f);
1505 NSWindow *window = [view window];
1506 NSRect wr = [window frame];
1507 int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1508 int pixelwidth, pixelheight;
1510 int orig_height = wr.size.height;
1512 NSTRACE ("x_set_window_size");
1517 NSTRACE_RECT ("current", wr);
1518 NSTRACE_MSG ("Width:%d Height:%d Pixelwise:%d", width, height, pixelwise);
1519 NSTRACE_MSG ("Font %d x %d", FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f));
1525 pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
1526 pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
1527 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, pixelwidth);
1528 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, pixelheight);
1532 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, width);
1533 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, height);
1538 /* If we have a toolbar, take its height into account. */
1539 if (tb && ! [view isFullscreen])
1541 /* NOTE: previously this would generate wrong result if toolbar not
1542 yet displayed and fixing toolbar_height=32 helped, but
1543 now (200903) seems no longer needed */
1544 FRAME_TOOLBAR_HEIGHT (f) =
1545 NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1546 - FRAME_NS_TITLEBAR_HEIGHT (f);
1548 /* Only breaks things here, removed by martin 2015-09-30. */
1549 #ifdef NS_IMPL_GNUSTEP
1550 FRAME_TOOLBAR_HEIGHT (f) -= 3;
1555 FRAME_TOOLBAR_HEIGHT (f) = 0;
1557 wr.size.width = pixelwidth + f->border_width;
1558 wr.size.height = pixelheight;
1559 if (! [view isFullscreen])
1560 wr.size.height += FRAME_NS_TITLEBAR_HEIGHT (f)
1561 + FRAME_TOOLBAR_HEIGHT (f);
1563 /* Do not try to constrain to this screen. We may have multiple
1564 screens, and want Emacs to span those. Constraining to screen
1565 prevents that, and that is not nice to the user. */
1566 if (f->output_data.ns->zooming)
1567 f->output_data.ns->zooming = 0;
1569 wr.origin.y += orig_height - wr.size.height;
1571 frame_size_history_add
1572 (f, Qx_set_window_size_1, width, height,
1573 list5 (Fcons (make_number (pixelwidth), make_number (pixelheight)),
1574 Fcons (make_number (wr.size.width), make_number (wr.size.height)),
1575 make_number (f->border_width),
1576 make_number (FRAME_NS_TITLEBAR_HEIGHT (f)),
1577 make_number (FRAME_TOOLBAR_HEIGHT (f))));
1579 [window setFrame: wr display: YES];
1581 /* This is a trick to compensate for Emacs' managing the scrollbar area
1582 as a fixed number of standard character columns. Instead of leaving
1583 blank space for the extra, we chopped it off above. Now for
1584 left-hand scrollbars, we shift all rendering to the left by the
1585 difference between the real width and Emacs' imagined one. For
1586 right-hand bars, don't worry about it since the extra is never used.
1587 (Obviously doesn't work for vertically split windows tho..) */
1589 NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1590 ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1591 - NS_SCROLL_BAR_WIDTH (f), 0)
1592 : NSMakePoint (0, 0);
1594 [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1595 [view setBoundsOrigin: origin];
1598 [view updateFrameSize: NO];
1604 ns_fullscreen_hook (struct frame *f)
1606 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1608 NSTRACE ("ns_fullscreen_hook");
1610 if (!FRAME_VISIBLE_P (f))
1613 if (! [view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH)
1615 /* Old style fs don't initiate correctly if created from
1616 init/default-frame alist, so use a timer (not nice...).
1618 [NSTimer scheduledTimerWithTimeInterval: 0.5 target: view
1619 selector: @selector (handleFS)
1620 userInfo: nil repeats: NO];
1629 /* ==========================================================================
1633 ========================================================================== */
1637 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1639 struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1640 if (idx < 1 || idx >= color_table->avail)
1642 return color_table->colors[idx];
1647 ns_index_color (NSColor *color, struct frame *f)
1649 struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1653 if (!color_table->colors)
1655 color_table->size = NS_COLOR_CAPACITY;
1656 color_table->avail = 1; /* skip idx=0 as marker */
1657 color_table->colors = xmalloc (color_table->size * sizeof (NSColor *));
1658 color_table->colors[0] = nil;
1659 color_table->empty_indices = [[NSMutableSet alloc] init];
1662 /* Do we already have this color? */
1663 for (i = 1; i < color_table->avail; i++)
1664 if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1667 if ([color_table->empty_indices count] > 0)
1669 NSNumber *index = [color_table->empty_indices anyObject];
1670 [color_table->empty_indices removeObject: index];
1671 idx = [index unsignedLongValue];
1675 if (color_table->avail == color_table->size)
1676 color_table->colors =
1677 xpalloc (color_table->colors, &color_table->size, 1,
1678 min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1679 idx = color_table->avail++;
1682 color_table->colors[idx] = color;
1684 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1690 ns_free_indexed_color (unsigned long idx, struct frame *f)
1692 struct ns_color_table *color_table;
1699 color_table = FRAME_DISPLAY_INFO (f)->color_table;
1701 if (idx <= 0 || idx >= color_table->size) {
1702 message1 ("ns_free_indexed_color: Color index out of range.\n");
1706 index = [NSNumber numberWithUnsignedInt: idx];
1707 if ([color_table->empty_indices containsObject: index]) {
1708 message1 ("ns_free_indexed_color: attempt to free already freed color.\n");
1712 color = color_table->colors[idx];
1714 color_table->colors[idx] = nil;
1715 [color_table->empty_indices addObject: index];
1716 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1721 ns_get_color (const char *name, NSColor **col)
1722 /* --------------------------------------------------------------------------
1724 -------------------------------------------------------------------------- */
1725 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1726 X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1727 See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1730 static char hex[20];
1732 float r = -1.0, g, b;
1733 NSString *nsname = [NSString stringWithUTF8String: name];
1735 NSTRACE ("ns_get_color(%s, **)", name);
1739 if ([nsname isEqualToString: @"ns_selection_bg_color"])
1741 #ifdef NS_IMPL_COCOA
1742 NSString *defname = [[NSUserDefaults standardUserDefaults]
1743 stringForKey: @"AppleHighlightColor"];
1748 if ((new = [NSColor selectedTextBackgroundColor]) != nil)
1750 *col = [new colorUsingDefaultColorSpace];
1755 nsname = NS_SELECTION_BG_COLOR_DEFAULT;
1757 name = [nsname UTF8String];
1759 else if ([nsname isEqualToString: @"ns_selection_fg_color"])
1761 /* NOTE: OSX applications normally don't set foreground selection, but
1762 text may be unreadable if we don't.
1764 if ((new = [NSColor selectedTextColor]) != nil)
1766 *col = [new colorUsingDefaultColorSpace];
1771 nsname = NS_SELECTION_FG_COLOR_DEFAULT;
1772 name = [nsname UTF8String];
1775 /* First, check for some sort of numeric specification. */
1778 if (name[0] == '0' || name[0] == '1' || name[0] == '.') /* RGB decimal */
1780 NSScanner *scanner = [NSScanner scannerWithString: nsname];
1781 [scanner scanFloat: &r];
1782 [scanner scanFloat: &g];
1783 [scanner scanFloat: &b];
1785 else if (!strncmp(name, "rgb:", 4)) /* A newer X11 format -- rgb:r/g/b */
1786 scaling = (snprintf (hex, sizeof hex, "%s", name + 4) - 2) / 3;
1787 else if (name[0] == '#') /* An old X11 format; convert to newer */
1789 int len = (strlen(name) - 1);
1790 int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1792 scaling = strlen(name+start) / 3;
1793 for (i = 0; i < 3; i++)
1794 sprintf (hex + i * (scaling + 1), "%.*s/", scaling,
1795 name + start + i * scaling);
1796 hex[3 * (scaling + 1) - 1] = '\0';
1802 float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1803 if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1813 *col = [NSColor colorForEmacsRed: r green: g blue: b alpha: 1.0];
1818 /* Otherwise, color is expected to be from a list */
1820 NSEnumerator *lenum, *cenum;
1824 #ifdef NS_IMPL_GNUSTEP
1825 /* XXX: who is wrong, the requestor or the implementation? */
1826 if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1828 nsname = @"highlightColor";
1831 lenum = [[NSColorList availableColorLists] objectEnumerator];
1832 while ( (clist = [lenum nextObject]) && new == nil)
1834 cenum = [[clist allKeys] objectEnumerator];
1835 while ( (name = [cenum nextObject]) && new == nil )
1837 if ([name compare: nsname
1838 options: NSCaseInsensitiveSearch] == NSOrderedSame )
1839 new = [clist colorWithKey: name];
1845 *col = [new colorUsingDefaultColorSpace];
1852 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1853 /* --------------------------------------------------------------------------
1854 Convert a Lisp string object to a NS color
1855 -------------------------------------------------------------------------- */
1857 NSTRACE ("ns_lisp_to_color");
1858 if (STRINGP (color))
1859 return ns_get_color (SSDATA (color), col);
1860 else if (SYMBOLP (color))
1861 return ns_get_color (SSDATA (SYMBOL_NAME (color)), col);
1867 ns_color_to_lisp (NSColor *col)
1868 /* --------------------------------------------------------------------------
1869 Convert a color to a lisp string with the RGB equivalent
1870 -------------------------------------------------------------------------- */
1872 EmacsCGFloat red, green, blue, alpha, gray;
1875 NSTRACE ("ns_color_to_lisp");
1878 if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1880 if ((str =[[col colorNameComponent] UTF8String]))
1883 return build_string ((char *)str);
1886 [[col colorUsingDefaultColorSpace]
1887 getRed: &red green: &green blue: &blue alpha: &alpha];
1888 if (red == green && red == blue)
1890 [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1891 getWhite: &gray alpha: &alpha];
1892 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1893 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1895 return build_string (buf);
1898 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1899 lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1902 return build_string (buf);
1907 ns_query_color(void *col, XColor *color_def, int setPixel)
1908 /* --------------------------------------------------------------------------
1909 Get ARGB values out of NSColor col and put them into color_def.
1910 If setPixel, set the pixel to a concatenated version.
1911 and set color_def pixel to the resulting index.
1912 -------------------------------------------------------------------------- */
1914 EmacsCGFloat r, g, b, a;
1916 [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1917 color_def->red = r * 65535;
1918 color_def->green = g * 65535;
1919 color_def->blue = b * 65535;
1921 if (setPixel == YES)
1923 = ARGB_TO_ULONG((int)(a*255),
1924 (int)(r*255), (int)(g*255), (int)(b*255));
1929 ns_defined_color (struct frame *f,
1934 /* --------------------------------------------------------------------------
1935 Return true if named color found, and set color_def rgb accordingly.
1936 If makeIndex and alloc are nonzero put the color in the color_table,
1937 and set color_def pixel to the resulting index.
1938 If makeIndex is zero, set color_def pixel to ARGB.
1939 Return false if not found
1940 -------------------------------------------------------------------------- */
1943 NSTRACE_WHEN (NSTRACE_GROUP_COLOR, "ns_defined_color");
1946 if (ns_get_color (name, &col) != 0) /* Color not found */
1951 if (makeIndex && alloc)
1952 color_def->pixel = ns_index_color (col, f);
1953 ns_query_color (col, color_def, !makeIndex);
1960 x_set_frame_alpha (struct frame *f)
1961 /* --------------------------------------------------------------------------
1962 change the entire-frame transparency
1963 -------------------------------------------------------------------------- */
1965 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1967 double alpha_min = 1.0;
1969 NSTRACE ("x_set_frame_alpha");
1971 if (dpyinfo->x_highlight_frame == f)
1972 alpha = f->alpha[0];
1974 alpha = f->alpha[1];
1976 if (FLOATP (Vframe_alpha_lower_limit))
1977 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1978 else if (INTEGERP (Vframe_alpha_lower_limit))
1979 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1983 else if (1.0 < alpha)
1985 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1988 #ifdef NS_IMPL_COCOA
1990 EmacsView *view = FRAME_NS_VIEW (f);
1991 [[view window] setAlphaValue: alpha];
1997 /* ==========================================================================
2001 ========================================================================== */
2005 frame_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
2006 /* --------------------------------------------------------------------------
2007 Programmatically reposition mouse pointer in pixel coordinates
2008 -------------------------------------------------------------------------- */
2010 NSTRACE ("frame_set_mouse_pixel_position");
2013 /* FIXME: this does not work, and what about GNUstep? */
2014 #ifdef NS_IMPL_COCOA
2015 [FRAME_NS_VIEW (f) lockFocus];
2016 PSsetmouse ((float)pix_x, (float)pix_y);
2017 [FRAME_NS_VIEW (f) unlockFocus];
2023 note_mouse_movement (struct frame *frame, CGFloat x, CGFloat y)
2024 /* ------------------------------------------------------------------------
2025 Called by EmacsView on mouseMovement events. Passes on
2026 to emacs mainstream code if we moved off of a rect of interest
2027 known as last_mouse_glyph.
2028 ------------------------------------------------------------------------ */
2030 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
2033 // NSTRACE ("note_mouse_movement");
2035 dpyinfo->last_mouse_motion_frame = frame;
2036 r = &dpyinfo->last_mouse_glyph;
2038 /* Note, this doesn't get called for enter/leave, since we don't have a
2039 position. Those are taken care of in the corresponding NSView methods. */
2041 /* has movement gone beyond last rect we were tracking? */
2042 if (x < r->origin.x || x >= r->origin.x + r->size.width
2043 || y < r->origin.y || y >= r->origin.y + r->size.height)
2045 ns_update_begin (frame);
2046 frame->mouse_moved = 1;
2047 note_mouse_highlight (frame, x, y);
2048 remember_mouse_glyph (frame, x, y, r);
2049 ns_update_end (frame);
2058 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
2059 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
2061 /* --------------------------------------------------------------------------
2062 External (hook): inform emacs about mouse position and hit parts.
2063 If a scrollbar is being dragged, set bar_window, part, x, y, time.
2064 x & y should be position in the scrollbar (the whole bar, not the handle)
2065 and length of scrollbar respectively
2066 -------------------------------------------------------------------------- */
2070 Lisp_Object frame, tail;
2072 struct ns_display_info *dpyinfo;
2074 NSTRACE ("ns_mouse_position");
2078 fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
2082 dpyinfo = FRAME_DISPLAY_INFO (*fp);
2086 /* Clear the mouse-moved flag for every frame on this display. */
2087 FOR_EACH_FRAME (tail, frame)
2088 if (FRAME_NS_P (XFRAME (frame))
2089 && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
2090 XFRAME (frame)->mouse_moved = 0;
2092 dpyinfo->last_mouse_scroll_bar = nil;
2093 if (dpyinfo->last_mouse_frame
2094 && FRAME_LIVE_P (dpyinfo->last_mouse_frame))
2095 f = dpyinfo->last_mouse_frame;
2097 f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame : SELECTED_FRAME ();
2099 if (f && FRAME_NS_P (f))
2101 view = FRAME_NS_VIEW (*fp);
2103 position = [[view window] mouseLocationOutsideOfEventStream];
2104 position = [view convertPoint: position fromView: nil];
2105 remember_mouse_glyph (f, position.x, position.y,
2106 &dpyinfo->last_mouse_glyph);
2107 NSTRACE_POINT ("position", position);
2109 if (bar_window) *bar_window = Qnil;
2110 if (part) *part = scroll_bar_above_handle;
2112 if (x) XSETINT (*x, lrint (position.x));
2113 if (y) XSETINT (*y, lrint (position.y));
2115 *time = dpyinfo->last_mouse_movement_time;
2124 ns_frame_up_to_date (struct frame *f)
2125 /* --------------------------------------------------------------------------
2126 External (hook): Fix up mouse highlighting right after a full update.
2127 Can't use FRAME_MOUSE_UPDATE due to ns_frame_begin and ns_frame_end calls.
2128 -------------------------------------------------------------------------- */
2130 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_frame_up_to_date");
2134 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
2135 if (f == hlinfo->mouse_face_mouse_frame)
2139 note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
2140 hlinfo->mouse_face_mouse_x,
2141 hlinfo->mouse_face_mouse_y);
2150 ns_define_frame_cursor (struct frame *f, Cursor cursor)
2151 /* --------------------------------------------------------------------------
2152 External (RIF): set frame mouse pointer type.
2153 -------------------------------------------------------------------------- */
2155 NSTRACE ("ns_define_frame_cursor");
2156 if (FRAME_POINTER_TYPE (f) != cursor)
2158 EmacsView *view = FRAME_NS_VIEW (f);
2159 FRAME_POINTER_TYPE (f) = cursor;
2160 [[view window] invalidateCursorRectsForView: view];
2161 /* Redisplay assumes this function also draws the changed frame
2162 cursor, but this function doesn't, so do it explicitly. */
2163 x_update_cursor (f, 1);
2169 /* ==========================================================================
2173 ========================================================================== */
2177 ns_convert_key (unsigned code)
2178 /* --------------------------------------------------------------------------
2179 Internal call used by NSView-keyDown.
2180 -------------------------------------------------------------------------- */
2182 const unsigned last_keysym = ARRAYELTS (convert_ns_to_X_keysym);
2184 /* An array would be faster, but less easy to read. */
2185 for (keysym = 0; keysym < last_keysym; keysym += 2)
2186 if (code == convert_ns_to_X_keysym[keysym])
2187 return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
2189 /* if decide to use keyCode and Carbon table, use this line:
2190 return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
2195 x_get_keysym_name (int keysym)
2196 /* --------------------------------------------------------------------------
2197 Called by keyboard.c. Not sure if the return val is important, except
2199 -------------------------------------------------------------------------- */
2201 static char value[16];
2202 NSTRACE ("x_get_keysym_name");
2203 sprintf (value, "%d", keysym);
2209 /* ==========================================================================
2211 Block drawing operations
2213 ========================================================================== */
2217 ns_redraw_scroll_bars (struct frame *f)
2221 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
2222 NSTRACE ("ns_redraw_scroll_bars");
2223 for (i =[subviews count]-1; i >= 0; i--)
2225 view = [subviews objectAtIndex: i];
2226 if (![view isKindOfClass: [EmacsScroller class]]) continue;
2233 ns_clear_frame (struct frame *f)
2234 /* --------------------------------------------------------------------------
2235 External (hook): Erase the entire frame
2236 -------------------------------------------------------------------------- */
2238 NSView *view = FRAME_NS_VIEW (f);
2241 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_clear_frame");
2243 /* comes on initial frame because we have
2244 after-make-frame-functions = select-frame */
2245 if (!FRAME_DEFAULT_FACE (f))
2248 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2253 ns_focus (f, &r, 1);
2254 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
2258 /* as of 2006/11 or so this is now needed */
2259 ns_redraw_scroll_bars (f);
2265 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2266 /* --------------------------------------------------------------------------
2267 External (RIF): Clear section of frame
2268 -------------------------------------------------------------------------- */
2270 NSRect r = NSMakeRect (x, y, width, height);
2271 NSView *view = FRAME_NS_VIEW (f);
2272 struct face *face = FRAME_DEFAULT_FACE (f);
2277 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_clear_frame_area");
2279 r = NSIntersectionRect (r, [view frame]);
2280 ns_focus (f, &r, 1);
2281 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2290 ns_copy_bits (struct frame *f, NSRect src, NSRect dest)
2292 if (FRAME_NS_VIEW (f))
2294 ns_focus (f, &dest, 1);
2295 [FRAME_NS_VIEW (f) scrollRect: src
2296 by: NSMakeSize (dest.origin.x - src.origin.x,
2297 dest.origin.y - src.origin.y)];
2303 ns_scroll_run (struct window *w, struct run *run)
2304 /* --------------------------------------------------------------------------
2305 External (RIF): Insert or delete n lines at line vpos
2306 -------------------------------------------------------------------------- */
2308 struct frame *f = XFRAME (w->frame);
2309 int x, y, width, height, from_y, to_y, bottom_y;
2311 NSTRACE ("ns_scroll_run");
2313 /* begin copy from other terms */
2314 /* Get frame-relative bounding box of the text display area of W,
2315 without mode lines. Include in this box the left and right
2317 window_box (w, ANY_AREA, &x, &y, &width, &height);
2319 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2320 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2321 bottom_y = y + height;
2325 /* Scrolling up. Make sure we don't copy part of the mode
2326 line at the bottom. */
2327 if (from_y + run->height > bottom_y)
2328 height = bottom_y - from_y;
2330 height = run->height;
2334 /* Scrolling down. Make sure we don't copy over the mode line.
2336 if (to_y + run->height > bottom_y)
2337 height = bottom_y - to_y;
2339 height = run->height;
2341 /* end copy from other terms */
2351 NSRect srcRect = NSMakeRect (x, from_y, width, height);
2352 NSRect dstRect = NSMakeRect (x, to_y, width, height);
2354 ns_copy_bits (f, srcRect , dstRect);
2362 ns_after_update_window_line (struct window *w, struct glyph_row *desired_row)
2363 /* --------------------------------------------------------------------------
2364 External (RIF): preparatory to fringe update after text was updated
2365 -------------------------------------------------------------------------- */
2370 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_after_update_window_line");
2372 /* begin copy from other terms */
2375 if (!desired_row->mode_line_p && !w->pseudo_window_p)
2376 desired_row->redraw_fringe_bitmaps_p = 1;
2378 /* When a window has disappeared, make sure that no rest of
2379 full-width rows stays visible in the internal border. */
2380 if (windows_or_buffers_changed
2381 && desired_row->full_width_p
2382 && (f = XFRAME (w->frame),
2383 width = FRAME_INTERNAL_BORDER_WIDTH (f),
2385 && (height = desired_row->visible_height,
2388 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2391 ns_clear_frame_area (f, 0, y, width, height);
2392 ns_clear_frame_area (f,
2393 FRAME_PIXEL_WIDTH (f) - width,
2401 ns_shift_glyphs_for_insert (struct frame *f,
2402 int x, int y, int width, int height,
2404 /* --------------------------------------------------------------------------
2405 External (RIF): copy an area horizontally, don't worry about clearing src
2406 -------------------------------------------------------------------------- */
2408 NSRect srcRect = NSMakeRect (x, y, width, height);
2409 NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2411 NSTRACE ("ns_shift_glyphs_for_insert");
2413 ns_copy_bits (f, srcRect, dstRect);
2418 /* ==========================================================================
2420 Character encoding and metrics
2422 ========================================================================== */
2426 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2427 /* --------------------------------------------------------------------------
2428 External (RIF); compute left/right overhang of whole string and set in s
2429 -------------------------------------------------------------------------- */
2431 struct font *font = s->font;
2435 struct font_metrics metrics;
2436 unsigned int codes[2];
2437 codes[0] = *(s->char2b);
2438 codes[1] = *(s->char2b + s->nchars - 1);
2440 font->driver->text_extents (font, codes, 2, &metrics);
2441 s->left_overhang = -metrics.lbearing;
2443 = metrics.rbearing > metrics.width
2444 ? metrics.rbearing - metrics.width : 0;
2448 s->left_overhang = 0;
2449 if (EQ (font->driver->type, Qns))
2450 s->right_overhang = ((struct nsfont_info *)font)->ital ?
2451 FONT_HEIGHT (font) * 0.2 : 0;
2453 s->right_overhang = 0;
2459 /* ==========================================================================
2461 Fringe and cursor drawing
2463 ========================================================================== */
2466 extern int max_used_fringe_bitmap;
2468 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2469 struct draw_fringe_bitmap_params *p)
2470 /* --------------------------------------------------------------------------
2471 External (RIF); fringe-related
2472 -------------------------------------------------------------------------- */
2474 /* Fringe bitmaps comes in two variants, normal and periodic. A
2475 periodic bitmap is used to create a continuous pattern. Since a
2476 bitmap is rendered one text line at a time, the start offset (dh)
2477 of the bitmap varies. Concretely, this is used for the empty
2480 For a bitmap, "h + dh" is the full height and is always
2481 invariant. For a normal bitmap "dh" is zero.
2483 For example, when the period is three and the full height is 72
2484 the following combinations exists:
2490 struct frame *f = XFRAME (WINDOW_FRAME (w));
2491 struct face *face = p->face;
2492 static EmacsImage **bimgs = NULL;
2493 static int nBimgs = 0;
2495 NSTRACE_WHEN (NSTRACE_GROUP_FRINGE, "ns_draw_fringe_bitmap");
2496 NSTRACE_MSG ("which:%d cursor:%d overlay:%d width:%d height:%d period:%d",
2497 p->which, p->cursor_p, p->overlay_p, p->wd, p->h, p->dh);
2499 /* grow bimgs if needed */
2500 if (nBimgs < max_used_fringe_bitmap)
2502 bimgs = xrealloc (bimgs, max_used_fringe_bitmap * sizeof *bimgs);
2503 memset (bimgs + nBimgs, 0,
2504 (max_used_fringe_bitmap - nBimgs) * sizeof *bimgs);
2505 nBimgs = max_used_fringe_bitmap;
2508 /* Must clip because of partially visible lines. */
2509 ns_clip_to_row (w, row, ANY_AREA, YES);
2513 int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
2515 if (bx >= 0 && nx > 0)
2517 NSRect r = NSMakeRect (bx, by, nx, ny);
2519 [ns_lookup_indexed_color (face->background, f) set];
2526 NSRect r = NSMakeRect (p->x, p->y, p->wd, p->h);
2527 EmacsImage *img = bimgs[p->which - 1];
2531 // Note: For "periodic" images, allocate one EmacsImage for
2532 // the base image, and use it for all dh:s.
2533 unsigned short *bits = p->bits;
2534 int full_height = p->h + p->dh;
2536 unsigned char *cbits = xmalloc (full_height);
2538 for (i = 0; i < full_height; i++)
2540 img = [[EmacsImage alloc] initFromXBM: cbits width: 8
2543 bimgs[p->which - 1] = img;
2547 NSTRACE_RECT ("r", r);
2550 /* Since we composite the bitmap instead of just blitting it, we need
2551 to erase the whole background. */
2552 [ns_lookup_indexed_color(face->background, f) set];
2558 bm_color = ns_lookup_indexed_color(face->foreground, f);
2559 else if (p->overlay_p)
2560 bm_color = ns_lookup_indexed_color(face->background, f);
2562 bm_color = f->output_data.ns->cursor_color;
2563 [img setXBMColor: bm_color];
2566 // Note: For periodic images, the full image height is "h + hd".
2567 // By using the height h, a suitable part of the image is used.
2568 NSRect fromRect = NSMakeRect(0, 0, p->wd, p->h);
2570 NSTRACE_RECT ("fromRect", fromRect);
2572 #ifdef NS_IMPL_COCOA
2575 operation: NSCompositeSourceOver
2581 NSPoint pt = r.origin;
2583 [img compositeToPoint: pt operation: NSCompositeSourceOver];
2592 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2593 int x, int y, enum text_cursor_kinds cursor_type,
2594 int cursor_width, bool on_p, bool active_p)
2595 /* --------------------------------------------------------------------------
2596 External call (RIF): draw cursor.
2597 Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2598 -------------------------------------------------------------------------- */
2601 int fx, fy, h, cursor_height;
2602 struct frame *f = WINDOW_XFRAME (w);
2603 struct glyph *phys_cursor_glyph;
2604 struct glyph *cursor_glyph;
2606 NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2608 /* If cursor is out of bounds, don't draw garbage. This can happen
2609 in mini-buffer windows when switching between echo area glyphs
2612 NSTRACE ("ns_draw_window_cursor");
2617 w->phys_cursor_type = cursor_type;
2618 w->phys_cursor_on_p = on_p;
2620 if (cursor_type == NO_CURSOR)
2622 w->phys_cursor_width = 0;
2626 if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2628 if (glyph_row->exact_window_width_line_p
2629 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2631 glyph_row->cursor_in_fringe_p = 1;
2632 draw_fringe_bitmap (w, glyph_row, 0);
2637 /* We draw the cursor (with NSRectFill), then draw the glyph on top
2638 (other terminals do it the other way round). We must set
2639 w->phys_cursor_width to the cursor width. For bar cursors, that
2640 is CURSOR_WIDTH; for box cursors, it is the glyph width. */
2641 get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2643 /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2644 to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2645 if (cursor_type == BAR_CURSOR)
2647 if (cursor_width < 1)
2648 cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2649 w->phys_cursor_width = cursor_width;
2651 /* If we have an HBAR, "cursor_width" MAY specify height. */
2652 else if (cursor_type == HBAR_CURSOR)
2654 cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2655 if (cursor_height > glyph_row->height)
2656 cursor_height = glyph_row->height;
2657 if (h > cursor_height) // Cursor smaller than line height, move down
2658 fy += h - cursor_height;
2662 r.origin.x = fx, r.origin.y = fy;
2664 r.size.width = w->phys_cursor_width;
2666 /* TODO: only needed in rare cases with last-resort font in HELLO..
2667 should we do this more efficiently? */
2668 ns_clip_to_row (w, glyph_row, ANY_AREA, NO); /* do ns_focus(f, &r, 1); if remove */
2671 face = FACE_FROM_ID (f, phys_cursor_glyph->face_id);
2672 if (face && NS_FACE_BACKGROUND (face)
2673 == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2675 [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2676 hollow_color = FRAME_CURSOR_COLOR (f);
2679 [FRAME_CURSOR_COLOR (f) set];
2681 #ifdef NS_IMPL_COCOA
2682 /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2683 atomic. Cleaner ways of doing this should be investigated.
2684 One way would be to set a global variable DRAWING_CURSOR
2685 when making the call to draw_phys..(), don't focus in that
2686 case, then move the ns_unfocus() here after that call. */
2687 NSDisableScreenUpdates ();
2690 switch (cursor_type)
2692 case DEFAULT_CURSOR:
2695 case FILLED_BOX_CURSOR:
2698 case HOLLOW_BOX_CURSOR:
2701 NSRectFill (NSInsetRect (r, 1, 1));
2702 [FRAME_CURSOR_COLOR (f) set];
2709 /* If the character under cursor is R2L, draw the bar cursor
2710 on the right of its glyph, rather than on the left. */
2711 cursor_glyph = get_phys_cursor_glyph (w);
2712 if ((cursor_glyph->resolved_level & 1) != 0)
2713 s.origin.x += cursor_glyph->pixel_width - s.size.width;
2720 /* draw the character under the cursor */
2721 if (cursor_type != NO_CURSOR)
2722 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2724 #ifdef NS_IMPL_COCOA
2725 NSEnableScreenUpdates ();
2732 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2733 /* --------------------------------------------------------------------------
2734 External (RIF): Draw a vertical line.
2735 -------------------------------------------------------------------------- */
2737 struct frame *f = XFRAME (WINDOW_FRAME (w));
2739 NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2741 NSTRACE ("ns_draw_vertical_window_border");
2743 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2745 [ns_lookup_indexed_color(face->foreground, f) set];
2747 ns_focus (f, &r, 1);
2754 ns_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
2755 /* --------------------------------------------------------------------------
2756 External (RIF): Draw a window divider.
2757 -------------------------------------------------------------------------- */
2759 struct frame *f = XFRAME (WINDOW_FRAME (w));
2761 NSRect r = NSMakeRect (x0, y0, x1-x0, y1-y0);
2763 NSTRACE ("ns_draw_window_divider");
2765 face = FACE_FROM_ID (f, WINDOW_DIVIDER_FACE_ID);
2767 [ns_lookup_indexed_color(face->foreground, f) set];
2769 ns_focus (f, &r, 1);
2775 ns_show_hourglass (struct frame *f)
2777 /* TODO: add NSProgressIndicator to all frames. */
2781 ns_hide_hourglass (struct frame *f)
2783 /* TODO: remove NSProgressIndicator from all frames. */
2786 /* ==========================================================================
2788 Glyph drawing operations
2790 ========================================================================== */
2793 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2794 /* --------------------------------------------------------------------------
2795 Wrapper utility to account for internal border width on full-width lines,
2796 and allow top full-width rows to hit the frame top. nr should be pointer
2797 to two successive NSRects. Number of rects actually used is returned.
2798 -------------------------------------------------------------------------- */
2800 int n = get_glyph_string_clip_rects (s, nr, 2);
2804 /* --------------------------------------------------------------------
2805 Draw a wavy line under glyph string s. The wave fills wave_height
2812 wave_height = 3 | * * * *
2813 --------------------------------------------------------------------- */
2816 ns_draw_underwave (struct glyph_string *s, EmacsCGFloat width, EmacsCGFloat x)
2818 int wave_height = 3, wave_length = 2;
2819 int y, dx, dy, odd, xmax;
2824 dy = wave_height - 1;
2825 y = s->ybase - wave_height + 3;
2828 /* Find and set clipping rectangle */
2829 waveClip = NSMakeRect (x, y, width, wave_height);
2830 [[NSGraphicsContext currentContext] saveGraphicsState];
2831 NSRectClip (waveClip);
2833 /* Draw the waves */
2834 a.x = x - ((int)(x) % dx) + (EmacsCGFloat) 0.5;
2836 odd = (int)(a.x/dx) % 2;
2837 a.y = b.y = y + 0.5;
2846 [NSBezierPath strokeLineFromPoint:a toPoint:b];
2847 a.x = b.x, a.y = b.y;
2848 b.x += dx, b.y = y + 0.5 + odd*dy;
2852 /* Restore previous clipping rectangle(s) */
2853 [[NSGraphicsContext currentContext] restoreGraphicsState];
2859 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
2860 NSColor *defaultCol, CGFloat width, CGFloat x)
2861 /* --------------------------------------------------------------------------
2862 Draw underline, overline, and strike-through on glyph string s.
2863 -------------------------------------------------------------------------- */
2865 if (s->for_overlaps)
2869 if (face->underline_p)
2871 if (s->face->underline_type == FACE_UNDER_WAVE)
2873 if (face->underline_defaulted_p)
2876 [ns_lookup_indexed_color (face->underline_color, s->f) set];
2878 ns_draw_underwave (s, width, x);
2880 else if (s->face->underline_type == FACE_UNDER_LINE)
2884 unsigned long thickness, position;
2886 /* If the prev was underlined, match its appearance. */
2887 if (s->prev && s->prev->face->underline_p
2888 && s->prev->face->underline_type == FACE_UNDER_LINE
2889 && s->prev->underline_thickness > 0)
2891 thickness = s->prev->underline_thickness;
2892 position = s->prev->underline_position;
2897 unsigned long descent;
2900 descent = s->y + s->height - s->ybase;
2902 /* Use underline thickness of font, defaulting to 1. */
2903 thickness = (font && font->underline_thickness > 0)
2904 ? font->underline_thickness : 1;
2906 /* Determine the offset of underlining from the baseline. */
2907 if (x_underline_at_descent_line)
2908 position = descent - thickness;
2909 else if (x_use_underline_position_properties
2910 && font && font->underline_position >= 0)
2911 position = font->underline_position;
2913 position = lround (font->descent / 2);
2915 position = underline_minimum_offset;
2917 position = max (position, underline_minimum_offset);
2919 /* Ensure underlining is not cropped. */
2920 if (descent <= position)
2922 position = descent - 1;
2925 else if (descent < position + thickness)
2929 s->underline_thickness = thickness;
2930 s->underline_position = position;
2932 r = NSMakeRect (x, s->ybase + position, width, thickness);
2934 if (face->underline_defaulted_p)
2937 [ns_lookup_indexed_color (face->underline_color, s->f) set];
2941 /* Do overline. We follow other terms in using a thickness of 1
2942 and ignoring overline_margin. */
2943 if (face->overline_p)
2946 r = NSMakeRect (x, s->y, width, 1);
2948 if (face->overline_color_defaulted_p)
2951 [ns_lookup_indexed_color (face->overline_color, s->f) set];
2955 /* Do strike-through. We follow other terms for thickness and
2956 vertical position.*/
2957 if (face->strike_through_p)
2962 dy = lrint ((s->height - 1) / 2);
2963 r = NSMakeRect (x, s->y + dy, width, 1);
2965 if (face->strike_through_color_defaulted_p)
2968 [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
2974 ns_draw_box (NSRect r, CGFloat thickness, NSColor *col,
2975 char left_p, char right_p)
2976 /* --------------------------------------------------------------------------
2977 Draw an unfilled rect inside r, optionally leaving left and/or right open.
2978 Note we can't just use an NSDrawRect command, because of the possibility
2979 of some sides not being drawn, and because the rect will be filled.
2980 -------------------------------------------------------------------------- */
2986 s.size.height = thickness;
2988 s.origin.y += r.size.height - thickness;
2991 s.size.height = r.size.height;
2992 s.origin.y = r.origin.y;
2994 /* left, right (optional) */
2995 s.size.width = thickness;
3000 s.origin.x += r.size.width - thickness;
3007 ns_draw_relief (NSRect r, int thickness, char raised_p,
3008 char top_p, char bottom_p, char left_p, char right_p,
3009 struct glyph_string *s)
3010 /* --------------------------------------------------------------------------
3011 Draw a relief rect inside r, optionally leaving some sides open.
3012 Note we can't just use an NSDrawBezel command, because of the possibility
3013 of some sides not being drawn, and because the rect will be filled.
3014 -------------------------------------------------------------------------- */
3016 static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
3017 NSColor *newBaseCol = nil;
3020 NSTRACE ("ns_draw_relief");
3024 if (s->face->use_box_color_for_shadows_p)
3026 newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
3028 /* else if (s->first_glyph->type == IMAGE_GLYPH
3030 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
3032 newBaseCol = IMAGE_BACKGROUND (s->img, s->f, 0);
3036 newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
3039 if (newBaseCol == nil)
3040 newBaseCol = [NSColor grayColor];
3042 if (newBaseCol != baseCol) /* TODO: better check */
3045 baseCol = [newBaseCol retain];
3047 lightCol = [[baseCol highlightWithLevel: 0.2] retain];
3049 darkCol = [[baseCol shadowWithLevel: 0.3] retain];
3052 [(raised_p ? lightCol : darkCol) set];
3054 /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
3057 sr.size.height = thickness;
3058 if (top_p) NSRectFill (sr);
3061 sr.size.height = r.size.height;
3062 sr.size.width = thickness;
3063 if (left_p) NSRectFill (sr);
3065 [(raised_p ? darkCol : lightCol) set];
3068 sr.size.width = r.size.width;
3069 sr.size.height = thickness;
3070 sr.origin.y += r.size.height - thickness;
3071 if (bottom_p) NSRectFill (sr);
3074 sr.size.height = r.size.height;
3075 sr.origin.y = r.origin.y;
3076 sr.size.width = thickness;
3077 sr.origin.x += r.size.width - thickness;
3078 if (right_p) NSRectFill (sr);
3083 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
3084 /* --------------------------------------------------------------------------
3085 Function modeled after x_draw_glyph_string_box ().
3086 Sets up parameters for drawing.
3087 -------------------------------------------------------------------------- */
3089 int right_x, last_x;
3090 char left_p, right_p;
3091 struct glyph *last_glyph;
3096 if (s->hl == DRAW_MOUSE_FACE)
3098 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3100 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3105 thickness = face->box_line_width;
3107 NSTRACE ("ns_dumpglyphs_box_or_relief");
3109 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
3110 ? WINDOW_RIGHT_EDGE_X (s->w)
3111 : window_box_right (s->w, s->area));
3112 last_glyph = (s->cmp || s->img
3113 ? s->first_glyph : s->first_glyph + s->nchars-1);
3115 right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
3116 ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
3118 left_p = (s->first_glyph->left_box_line_p
3119 || (s->hl == DRAW_MOUSE_FACE
3120 && (s->prev == NULL || s->prev->hl != s->hl)));
3121 right_p = (last_glyph->right_box_line_p
3122 || (s->hl == DRAW_MOUSE_FACE
3123 && (s->next == NULL || s->next->hl != s->hl)));
3125 r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
3127 /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
3128 if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
3130 ns_draw_box (r, abs (thickness),
3131 ns_lookup_indexed_color (face->box_color, s->f),
3136 ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
3137 1, 1, left_p, right_p, s);
3143 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
3144 /* --------------------------------------------------------------------------
3145 Modeled after x_draw_glyph_string_background, which draws BG in
3146 certain cases. Others are left to the text rendering routine.
3147 -------------------------------------------------------------------------- */
3149 NSTRACE ("ns_maybe_dumpglyphs_background");
3151 if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
3153 int box_line_width = max (s->face->box_line_width, 0);
3154 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
3155 /* When xdisp.c ignores FONT_HEIGHT, we cannot trust font
3156 dimensions, since the actual glyphs might be much
3157 smaller. So in that case we always clear the rectangle
3158 with background color. */
3159 || FONT_TOO_HIGH (s->font)
3160 || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
3163 if (s->hl == DRAW_MOUSE_FACE)
3165 face = FACE_FROM_ID (s->f,
3166 MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3168 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3171 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3173 [(NS_FACE_BACKGROUND (face) != 0
3174 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
3175 : FRAME_BACKGROUND_COLOR (s->f)) set];
3178 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (s->f);
3179 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
3182 if (s->hl != DRAW_CURSOR)
3184 NSRect r = NSMakeRect (s->x, s->y + box_line_width,
3185 s->background_width,
3186 s->height-2*box_line_width);
3190 s->background_filled_p = 1;
3197 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
3198 /* --------------------------------------------------------------------------
3199 Renders an image and associated borders.
3200 -------------------------------------------------------------------------- */
3202 EmacsImage *img = s->img->pixmap;
3203 int box_line_vwidth = max (s->face->box_line_width, 0);
3204 int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3205 int bg_x, bg_y, bg_height;
3212 NSTRACE ("ns_dumpglyphs_image");
3214 if (s->face->box != FACE_NO_BOX
3215 && s->first_glyph->left_box_line_p && s->slice.x == 0)
3216 x += abs (s->face->box_line_width);
3219 bg_y = s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
3220 bg_height = s->height;
3221 /* other terms have this, but was causing problems w/tabbar mode */
3222 /* - 2 * box_line_vwidth; */
3224 if (s->slice.x == 0) x += s->img->hmargin;
3225 if (s->slice.y == 0) y += s->img->vmargin;
3227 /* Draw BG: if we need larger area than image itself cleared, do that,
3228 otherwise, since we composite the image under NS (instead of mucking
3229 with its background color), we must clear just the image area. */
3230 if (s->hl == DRAW_MOUSE_FACE)
3232 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3234 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3237 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3239 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
3241 if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
3242 || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
3244 br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
3245 s->background_filled_p = 1;
3249 br = NSMakeRect (x, y, s->slice.width, s->slice.height);
3254 /* Draw the image.. do we need to draw placeholder if img ==nil? */
3257 #ifdef NS_IMPL_COCOA
3258 NSRect dr = NSMakeRect (x, y, s->slice.width, s->slice.height);
3259 NSRect ir = NSMakeRect (s->slice.x, s->slice.y,
3260 s->slice.width, s->slice.height);
3263 operation: NSCompositeSourceOver
3268 [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3269 operation: NSCompositeSourceOver];
3273 if (s->hl == DRAW_CURSOR)
3275 [FRAME_CURSOR_COLOR (s->f) set];
3276 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3277 tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3279 /* Currently on NS img->mask is always 0. Since
3280 get_window_cursor_type specifies a hollow box cursor when on
3281 a non-masked image we never reach this clause. But we put it
3282 in in anticipation of better support for image masks on
3284 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3288 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3291 /* Draw underline, overline, strike-through. */
3292 ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3294 /* Draw relief, if requested */
3295 if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3297 if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3299 th = tool_bar_button_relief >= 0 ?
3300 tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3301 raised_p = (s->hl == DRAW_IMAGE_RAISED);
3305 th = abs (s->img->relief);
3306 raised_p = (s->img->relief > 0);
3309 r.origin.x = x - th;
3310 r.origin.y = y - th;
3311 r.size.width = s->slice.width + 2*th-1;
3312 r.size.height = s->slice.height + 2*th-1;
3313 ns_draw_relief (r, th, raised_p,
3315 s->slice.y + s->slice.height == s->img->height,
3317 s->slice.x + s->slice.width == s->img->width, s);
3320 /* If there is no mask, the background won't be seen,
3321 so draw a rectangle on the image for the cursor.
3322 Do this for all images, getting transparency right is not reliable. */
3323 if (s->hl == DRAW_CURSOR)
3325 int thickness = abs (s->img->relief);
3326 if (thickness == 0) thickness = 1;
3327 ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3333 ns_dumpglyphs_stretch (struct glyph_string *s)
3338 NSColor *fgCol, *bgCol;
3340 if (!s->background_filled_p)
3342 n = ns_get_glyph_string_clip_rect (s, r);
3343 *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3345 ns_focus (s->f, r, n);
3347 if (s->hl == DRAW_MOUSE_FACE)
3349 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3351 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3354 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3356 bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3357 fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3359 for (i = 0; i < n; ++i)
3361 if (!s->row->full_width_p)
3363 int overrun, leftoverrun;
3365 /* truncate to avoid overwriting fringe and/or scrollbar */
3366 overrun = max (0, (s->x + s->background_width)
3367 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3368 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3369 r[i].size.width -= overrun;
3371 /* truncate to avoid overwriting to left of the window box */
3372 leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3373 + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3375 if (leftoverrun > 0)
3377 r[i].origin.x += leftoverrun;
3378 r[i].size.width -= leftoverrun;
3381 /* XXX: Try to work between problem where a stretch glyph on
3382 a partially-visible bottom row will clear part of the
3383 modeline, and another where list-buffers headers and similar
3384 rows erroneously have visible_height set to 0. Not sure
3385 where this is coming from as other terms seem not to show. */
3386 r[i].size.height = min (s->height, s->row->visible_height);
3391 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3392 overwriting cursor (usually when cursor on a tab) */
3393 if (s->hl == DRAW_CURSOR)
3398 width = s->w->phys_cursor_width;
3399 r[i].size.width -= width;
3400 r[i].origin.x += width;
3404 /* Draw overlining, etc. on the cursor. */
3405 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3406 ns_draw_text_decoration (s, face, bgCol, width, x);
3408 ns_draw_text_decoration (s, face, fgCol, width, x);
3415 /* Draw overlining, etc. on the stretch glyph (or the part
3416 of the stretch glyph after the cursor). */
3417 ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3421 s->background_filled_p = 1;
3427 ns_draw_composite_glyph_string_foreground (struct glyph_string *s)
3430 struct font *font = s->font;
3432 /* If first glyph of S has a left box line, start drawing the text
3433 of S to the right of that box line. */
3434 if (s->face && s->face->box != FACE_NO_BOX
3435 && s->first_glyph->left_box_line_p)
3436 x = s->x + eabs (s->face->box_line_width);
3440 /* S is a glyph string for a composition. S->cmp_from is the index
3441 of the first character drawn for glyphs of this composition.
3442 S->cmp_from == 0 means we are drawing the very first character of
3443 this composition. */
3445 /* Draw a rectangle for the composition if the font for the very
3446 first character of the composition could not be loaded. */
3447 if (s->font_not_found_p)
3449 if (s->cmp_from == 0)
3451 NSRect r = NSMakeRect (s->x, s->y, s->width-1, s->height -1);
3452 ns_draw_box (r, 1, FRAME_CURSOR_COLOR (s->f), 1, 1);
3455 else if (! s->first_glyph->u.cmp.automatic)
3459 for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
3460 /* TAB in a composition means display glyphs with padding
3461 space on the left or right. */
3462 if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
3464 int xx = x + s->cmp->offsets[j * 2];
3465 int yy = y - s->cmp->offsets[j * 2 + 1];
3467 font->driver->draw (s, j, j + 1, xx, yy, false);
3468 if (s->face->overstrike)
3469 font->driver->draw (s, j, j + 1, xx + 1, yy, false);
3474 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
3479 for (i = j = s->cmp_from; i < s->cmp_to; i++)
3481 glyph = LGSTRING_GLYPH (gstring, i);
3482 if (NILP (LGLYPH_ADJUSTMENT (glyph)))
3483 width += LGLYPH_WIDTH (glyph);
3486 int xoff, yoff, wadjust;
3490 font->driver->draw (s, j, i, x, y, false);
3491 if (s->face->overstrike)
3492 font->driver->draw (s, j, i, x + 1, y, false);
3495 xoff = LGLYPH_XOFF (glyph);
3496 yoff = LGLYPH_YOFF (glyph);
3497 wadjust = LGLYPH_WADJUST (glyph);
3498 font->driver->draw (s, i, i + 1, x + xoff, y + yoff, false);
3499 if (s->face->overstrike)
3500 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff,
3509 font->driver->draw (s, j, i, x, y, false);
3510 if (s->face->overstrike)
3511 font->driver->draw (s, j, i, x + 1, y, false);
3517 ns_draw_glyph_string (struct glyph_string *s)
3518 /* --------------------------------------------------------------------------
3519 External (RIF): Main draw-text call.
3520 -------------------------------------------------------------------------- */
3522 /* TODO (optimize): focus for box and contents draw */
3525 char box_drawn_p = 0;
3526 struct font *font = s->face->font;
3527 if (! font) font = FRAME_FONT (s->f);
3529 NSTRACE_WHEN (NSTRACE_GROUP_GLYPHS, "ns_draw_glyph_string");
3531 if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3534 struct glyph_string *next;
3536 for (width = 0, next = s->next;
3537 next && width < s->right_overhang;
3538 width += next->width, next = next->next)
3539 if (next->first_glyph->type != IMAGE_GLYPH)
3541 if (next->first_glyph->type != STRETCH_GLYPH)
3543 n = ns_get_glyph_string_clip_rect (s->next, r);
3544 ns_focus (s->f, r, n);
3545 ns_maybe_dumpglyphs_background (s->next, 1);
3550 ns_dumpglyphs_stretch (s->next);
3552 next->num_clips = 0;
3556 if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3557 && (s->first_glyph->type == CHAR_GLYPH
3558 || s->first_glyph->type == COMPOSITE_GLYPH))
3560 n = ns_get_glyph_string_clip_rect (s, r);
3561 ns_focus (s->f, r, n);
3562 ns_maybe_dumpglyphs_background (s, 1);
3563 ns_dumpglyphs_box_or_relief (s);
3568 switch (s->first_glyph->type)
3572 n = ns_get_glyph_string_clip_rect (s, r);
3573 ns_focus (s->f, r, n);
3574 ns_dumpglyphs_image (s, r[0]);
3579 ns_dumpglyphs_stretch (s);
3583 case COMPOSITE_GLYPH:
3584 n = ns_get_glyph_string_clip_rect (s, r);
3585 ns_focus (s->f, r, n);
3587 if (s->for_overlaps || (s->cmp_from > 0
3588 && ! s->first_glyph->u.cmp.automatic))
3589 s->background_filled_p = 1;
3591 ns_maybe_dumpglyphs_background
3592 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3594 flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3595 (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3596 (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3597 NS_DUMPGLYPH_NORMAL));
3599 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3601 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3602 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3603 NS_FACE_FOREGROUND (s->face) = tmp;
3607 BOOL isComposite = s->first_glyph->type == COMPOSITE_GLYPH;
3610 ns_draw_composite_glyph_string_foreground (s);
3613 (s, s->cmp_from, s->nchars, s->x, s->ybase,
3614 (flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3615 || flags == NS_DUMPGLYPH_MOUSEFACE);
3619 NSColor *col = (NS_FACE_FOREGROUND (s->face) != 0
3620 ? ns_lookup_indexed_color (NS_FACE_FOREGROUND (s->face),
3622 : FRAME_FOREGROUND_COLOR (s->f));
3625 /* Draw underline, overline, strike-through. */
3626 ns_draw_text_decoration (s, s->face, col, s->width, s->x);
3629 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3631 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3632 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3633 NS_FACE_FOREGROUND (s->face) = tmp;
3639 case GLYPHLESS_GLYPH:
3640 n = ns_get_glyph_string_clip_rect (s, r);
3641 ns_focus (s->f, r, n);
3643 if (s->for_overlaps || (s->cmp_from > 0
3644 && ! s->first_glyph->u.cmp.automatic))
3645 s->background_filled_p = 1;
3647 ns_maybe_dumpglyphs_background
3648 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3650 /* Not yet implemented. */
3659 /* Draw box if not done already. */
3660 if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3662 n = ns_get_glyph_string_clip_rect (s, r);
3663 ns_focus (s->f, r, n);
3664 ns_dumpglyphs_box_or_relief (s);
3673 /* ==========================================================================
3677 ========================================================================== */
3681 ns_send_appdefined (int value)
3682 /* --------------------------------------------------------------------------
3683 Internal: post an appdefined event which EmacsApp-sendEvent will
3684 recognize and take as a command to halt the event loop.
3685 -------------------------------------------------------------------------- */
3687 NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_send_appdefined(%d)", value);
3689 #ifdef NS_IMPL_GNUSTEP
3690 // GNUstep needs postEvent to happen on the main thread.
3691 if (! [[NSThread currentThread] isMainThread])
3693 EmacsApp *app = (EmacsApp *)NSApp;
3694 app->nextappdefined = value;
3695 [app performSelectorOnMainThread:@selector (sendFromMainThread:)
3702 /* Only post this event if we haven't already posted one. This will end
3703 the [NXApp run] main loop after having processed all events queued at
3706 #ifdef NS_IMPL_COCOA
3707 if (! send_appdefined)
3709 /* OSX 10.10.1 swallows the AppDefined event we are sending ourselves
3710 in certain situations (rapid incoming events).
3711 So check if we have one, if not add one. */
3712 NSEvent *appev = [NSApp nextEventMatchingMask:NSApplicationDefinedMask
3713 untilDate:[NSDate distantPast]
3714 inMode:NSDefaultRunLoopMode
3716 if (! appev) send_appdefined = YES;
3720 if (send_appdefined)
3724 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
3725 send_appdefined = NO;
3727 /* Don't need wakeup timer any more */
3730 [timed_entry invalidate];
3731 [timed_entry release];
3735 nxev = [NSEvent otherEventWithType: NSApplicationDefined
3736 location: NSMakePoint (0, 0)
3739 windowNumber: [[NSApp mainWindow] windowNumber]
3740 context: [NSApp context]
3745 /* Post an application defined event on the event queue. When this is
3746 received the [NXApp run] will return, thus having processed all
3747 events which are currently queued. */
3748 [NSApp postEvent: nxev atStart: NO];
3752 #ifdef HAVE_NATIVE_FS
3756 Lisp_Object frame, tail;
3758 if (ns_last_use_native_fullscreen == ns_use_native_fullscreen)
3761 ns_last_use_native_fullscreen = ns_use_native_fullscreen;
3763 FOR_EACH_FRAME (tail, frame)
3765 struct frame *f = XFRAME (frame);
3768 EmacsView *view = FRAME_NS_VIEW (f);
3769 [view updateCollectionBehavior];
3775 /* GNUstep does not have cancelTracking. */
3776 #ifdef NS_IMPL_COCOA
3777 /* Check if menu open should be canceled or continued as normal. */
3779 ns_check_menu_open (NSMenu *menu)
3781 /* Click in menu bar? */
3782 NSArray *a = [[NSApp mainMenu] itemArray];
3786 if (menu == nil) // Menu tracking ended.
3788 if (menu_will_open_state == MENU_OPENING)
3789 menu_will_open_state = MENU_NONE;
3793 for (i = 0; ! found && i < [a count]; i++)
3794 found = menu == [[a objectAtIndex:i] submenu];
3797 if (menu_will_open_state == MENU_NONE && emacs_event)
3799 NSEvent *theEvent = [NSApp currentEvent];
3800 struct frame *emacsframe = SELECTED_FRAME ();
3802 [menu cancelTracking];
3803 menu_will_open_state = MENU_PENDING;
3804 emacs_event->kind = MENU_BAR_ACTIVATE_EVENT;
3805 EV_TRAILER (theEvent);
3807 CGEventRef ourEvent = CGEventCreate (NULL);
3808 menu_mouse_point = CGEventGetLocation (ourEvent);
3809 CFRelease (ourEvent);
3811 else if (menu_will_open_state == MENU_OPENING)
3813 menu_will_open_state = MENU_NONE;
3818 /* Redo saved menu click if state is MENU_PENDING. */
3820 ns_check_pending_open_menu ()
3822 if (menu_will_open_state == MENU_PENDING)
3824 CGEventSourceRef source
3825 = CGEventSourceCreate (kCGEventSourceStateHIDSystemState);
3827 CGEventRef event = CGEventCreateMouseEvent (source,
3828 kCGEventLeftMouseDown,
3830 kCGMouseButtonLeft);
3831 CGEventSetType (event, kCGEventLeftMouseDown);
3832 CGEventPost (kCGHIDEventTap, event);
3836 menu_will_open_state = MENU_OPENING;
3839 #endif /* NS_IMPL_COCOA */
3842 unwind_apploopnr (Lisp_Object not_used)
3845 n_emacs_events_pending = 0;
3846 ns_finish_events ();
3851 ns_read_socket (struct terminal *terminal, struct input_event *hold_quit)
3852 /* --------------------------------------------------------------------------
3853 External (hook): Post an event to ourself and keep reading events until
3854 we read it back again. In effect process all events which were waiting.
3855 From 21+ we have to manage the event buffer ourselves.
3856 -------------------------------------------------------------------------- */
3858 struct input_event ev;
3861 NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_read_socket");
3863 #ifdef HAVE_NATIVE_FS
3867 if ([NSApp modalWindow] != nil)
3870 if (hold_event_q.nr > 0)
3873 for (i = 0; i < hold_event_q.nr; ++i)
3874 kbd_buffer_store_event_hold (&hold_event_q.q[i], hold_quit);
3875 hold_event_q.nr = 0;
3880 n_emacs_events_pending = 0;
3881 ns_init_events (&ev);
3882 q_event_ptr = hold_quit;
3884 /* we manage autorelease pools by allocate/reallocate each time around
3885 the loop; strict nesting is occasionally violated but seems not to
3886 matter.. earlier methods using full nesting caused major memory leaks */
3887 [outerpool release];
3888 outerpool = [[NSAutoreleasePool alloc] init];
3890 /* If have pending open-file requests, attend to the next one of those. */
3891 if (ns_pending_files && [ns_pending_files count] != 0
3892 && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3894 [ns_pending_files removeObjectAtIndex: 0];
3896 /* Deal with pending service requests. */
3897 else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3899 NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3900 withArg: [ns_pending_service_args objectAtIndex: 0]])
3902 [ns_pending_service_names removeObjectAtIndex: 0];
3903 [ns_pending_service_args removeObjectAtIndex: 0];
3907 ptrdiff_t specpdl_count = SPECPDL_INDEX ();
3908 /* Run and wait for events. We must always send one NX_APPDEFINED event
3909 to ourself, otherwise [NXApp run] will never exit. */
3910 send_appdefined = YES;
3911 ns_send_appdefined (-1);
3913 if (++apploopnr != 1)
3917 record_unwind_protect (unwind_apploopnr, Qt);
3919 unbind_to (specpdl_count, Qnil); /* calls unwind_apploopnr */
3922 nevents = n_emacs_events_pending;
3923 n_emacs_events_pending = 0;
3924 ns_finish_events ();
3933 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3934 fd_set *exceptfds, struct timespec const *timeout,
3935 sigset_t const *sigmask)
3936 /* --------------------------------------------------------------------------
3937 Replacement for select, checking for events
3938 -------------------------------------------------------------------------- */
3942 struct input_event event;
3945 NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_select");
3947 #ifdef HAVE_NATIVE_FS
3951 if (hold_event_q.nr > 0)
3953 /* We already have events pending. */
3959 for (k = 0; k < nfds+1; k++)
3961 if (readfds && FD_ISSET(k, readfds)) ++nr;
3962 if (writefds && FD_ISSET(k, writefds)) ++nr;
3966 || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0))
3967 return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
3969 [outerpool release];
3970 outerpool = [[NSAutoreleasePool alloc] init];
3973 send_appdefined = YES;
3976 pthread_mutex_lock (&select_mutex);
3981 select_readfds = *readfds;
3982 select_valid += SELECT_HAVE_READ;
3986 select_writefds = *writefds;
3987 select_valid += SELECT_HAVE_WRITE;
3992 select_timeout = *timeout;
3993 select_valid += SELECT_HAVE_TMO;
3996 pthread_mutex_unlock (&select_mutex);
3998 /* Inform fd_handler that select should be called */
4000 emacs_write_sig (selfds[1], &c, 1);
4002 else if (nr == 0 && timeout)
4004 /* No file descriptor, just a timeout, no need to wake fd_handler */
4005 double time = timespectod (*timeout);
4006 timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
4009 @selector (timeout_handler:)
4014 else /* No timeout and no file descriptors, can this happen? */
4016 /* Send appdefined so we exit from the loop */
4017 ns_send_appdefined (-1);
4021 ns_init_events (&event);
4022 if (++apploopnr != 1)
4028 ptrdiff_t specpdl_count = SPECPDL_INDEX ();
4029 record_unwind_protect (unwind_apploopnr, Qt);
4031 unbind_to (specpdl_count, Qnil); /* calls unwind_apploopnr */
4034 ns_finish_events ();
4035 if (nr > 0 && readfds)
4038 emacs_write_sig (selfds[1], &c, 1);
4042 t = last_appdefined_event_data;
4044 if (t != NO_APPDEFINED_DATA)
4046 last_appdefined_event_data = NO_APPDEFINED_DATA;
4050 /* The NX_APPDEFINED event we received was a timeout. */
4055 /* The NX_APPDEFINED event we received was the result of
4056 at least one real input event arriving. */
4062 /* Received back from select () in fd_handler; copy the results */
4063 pthread_mutex_lock (&select_mutex);
4064 if (readfds) *readfds = select_readfds;
4065 if (writefds) *writefds = select_writefds;
4066 pthread_mutex_unlock (&select_mutex);
4081 /* ==========================================================================
4085 ========================================================================== */
4089 ns_set_vertical_scroll_bar (struct window *window,
4090 int portion, int whole, int position)
4091 /* --------------------------------------------------------------------------
4092 External (hook): Update or add scrollbar
4093 -------------------------------------------------------------------------- */
4097 struct frame *f = XFRAME (WINDOW_FRAME (window));
4098 EmacsView *view = FRAME_NS_VIEW (f);
4100 int window_y, window_height;
4101 int top, left, height, width;
4102 BOOL update_p = YES;
4104 /* optimization; display engine sends WAY too many of these.. */
4105 if (!NILP (window->vertical_scroll_bar))
4107 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4108 if ([bar checkSamePosition: position portion: portion whole: whole])
4110 if (view->scrollbarsNeedingUpdate == 0)
4112 if (!windows_or_buffers_changed)
4116 view->scrollbarsNeedingUpdate--;
4121 NSTRACE ("ns_set_vertical_scroll_bar");
4123 /* Get dimensions. */
4124 window_box (window, ANY_AREA, 0, &window_y, 0, &window_height);
4126 height = window_height;
4127 width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
4128 left = WINDOW_SCROLL_BAR_AREA_X (window);
4130 r = NSMakeRect (left, top, width, height);
4131 /* the parent view is flipped, so we need to flip y value */
4133 r.origin.y = (v.size.height - r.size.height - r.origin.y);
4135 XSETWINDOW (win, window);
4138 /* we want at least 5 lines to display a scrollbar */
4139 if (WINDOW_TOTAL_LINES (window) < 5)
4141 if (!NILP (window->vertical_scroll_bar))
4143 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4144 [bar removeFromSuperview];
4145 wset_vertical_scroll_bar (window, Qnil);
4148 ns_clear_frame_area (f, left, top, width, height);
4153 if (NILP (window->vertical_scroll_bar))
4155 if (width > 0 && height > 0)
4156 ns_clear_frame_area (f, left, top, width, height);
4158 bar = [[EmacsScroller alloc] initFrame: r window: win];
4159 wset_vertical_scroll_bar (window, make_save_ptr (bar));
4165 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4166 oldRect = [bar frame];
4167 r.size.width = oldRect.size.width;
4168 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4170 if (oldRect.origin.x != r.origin.x)
4171 ns_clear_frame_area (f, left, top, width, height);
4177 [bar setPosition: position portion: portion whole: whole];
4183 ns_set_horizontal_scroll_bar (struct window *window,
4184 int portion, int whole, int position)
4185 /* --------------------------------------------------------------------------
4186 External (hook): Update or add scrollbar
4187 -------------------------------------------------------------------------- */
4191 struct frame *f = XFRAME (WINDOW_FRAME (window));
4192 EmacsView *view = FRAME_NS_VIEW (f);
4194 int top, height, left, width;
4195 int window_x, window_width;
4196 BOOL update_p = YES;
4198 /* optimization; display engine sends WAY too many of these.. */
4199 if (!NILP (window->horizontal_scroll_bar))
4201 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4202 if ([bar checkSamePosition: position portion: portion whole: whole])
4204 if (view->scrollbarsNeedingUpdate == 0)
4206 if (!windows_or_buffers_changed)
4210 view->scrollbarsNeedingUpdate--;
4215 NSTRACE ("ns_set_horizontal_scroll_bar");
4217 /* Get dimensions. */
4218 window_box (window, ANY_AREA, 0, &window_x, &window_width, 0);
4220 width = window_width;
4221 height = WINDOW_CONFIG_SCROLL_BAR_LINES (window) * FRAME_LINE_HEIGHT (f);
4222 top = WINDOW_SCROLL_BAR_AREA_Y (window);
4224 r = NSMakeRect (left, top, width, height);
4225 /* the parent view is flipped, so we need to flip y value */
4227 /* ??????? PXW/scrollbars !!!!!!!!!!!!!!!!!!!! */
4228 r.origin.y = (v.size.height - r.size.height - r.origin.y);
4230 XSETWINDOW (win, window);
4233 if (WINDOW_TOTAL_COLS (window) < 5)
4235 if (!NILP (window->horizontal_scroll_bar))
4237 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4238 [bar removeFromSuperview];
4239 wset_horizontal_scroll_bar (window, Qnil);
4241 ns_clear_frame_area (f, left, top, width, height);
4246 if (NILP (window->horizontal_scroll_bar))
4248 if (width > 0 && height > 0)
4249 ns_clear_frame_area (f, left, top, width, height);
4251 bar = [[EmacsScroller alloc] initFrame: r window: win];
4252 wset_horizontal_scroll_bar (window, make_save_ptr (bar));
4258 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4259 oldRect = [bar frame];
4260 r.size.width = oldRect.size.width;
4261 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4263 if (oldRect.origin.x != r.origin.x)
4264 ns_clear_frame_area (f, left, top, width, height);
4271 [bar setPosition: position portion: portion whole: whole];
4277 ns_condemn_scroll_bars (struct frame *f)
4278 /* --------------------------------------------------------------------------
4279 External (hook): arrange for all frame's scrollbars to be removed
4280 at next call to judge_scroll_bars, except for those redeemed.
4281 -------------------------------------------------------------------------- */
4285 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
4287 NSTRACE ("ns_condemn_scroll_bars");
4289 for (i =[subviews count]-1; i >= 0; i--)
4291 view = [subviews objectAtIndex: i];
4292 if ([view isKindOfClass: [EmacsScroller class]])
4299 ns_redeem_scroll_bar (struct window *window)
4300 /* --------------------------------------------------------------------------
4301 External (hook): arrange to spare this window's scrollbar
4302 at next call to judge_scroll_bars.
4303 -------------------------------------------------------------------------- */
4306 NSTRACE ("ns_redeem_scroll_bar");
4307 if (!NILP (window->vertical_scroll_bar))
4309 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4313 if (!NILP (window->horizontal_scroll_bar))
4315 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4322 ns_judge_scroll_bars (struct frame *f)
4323 /* --------------------------------------------------------------------------
4324 External (hook): destroy all scrollbars on frame that weren't
4325 redeemed after call to condemn_scroll_bars.
4326 -------------------------------------------------------------------------- */
4330 EmacsView *eview = FRAME_NS_VIEW (f);
4331 NSArray *subviews = [[eview superview] subviews];
4334 NSTRACE ("ns_judge_scroll_bars");
4335 for (i = [subviews count]-1; i >= 0; --i)
4337 view = [subviews objectAtIndex: i];
4338 if (![view isKindOfClass: [EmacsScroller class]]) continue;
4344 [eview updateFrameSize: NO];
4347 /* ==========================================================================
4351 ========================================================================== */
4354 x_display_pixel_height (struct ns_display_info *dpyinfo)
4356 NSArray *screens = [NSScreen screens];
4357 NSEnumerator *enumerator = [screens objectEnumerator];
4362 while ((screen = [enumerator nextObject]) != nil)
4363 frame = NSUnionRect (frame, [screen frame]);
4365 return NSHeight (frame);
4369 x_display_pixel_width (struct ns_display_info *dpyinfo)
4371 NSArray *screens = [NSScreen screens];
4372 NSEnumerator *enumerator = [screens objectEnumerator];
4377 while ((screen = [enumerator nextObject]) != nil)
4378 frame = NSUnionRect (frame, [screen frame]);
4380 return NSWidth (frame);
4384 static Lisp_Object ns_string_to_lispmod (const char *s)
4385 /* --------------------------------------------------------------------------
4386 Convert modifier name to lisp symbol
4387 -------------------------------------------------------------------------- */
4389 if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
4391 else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
4393 else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
4395 else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
4397 else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
4399 else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
4407 ns_default (const char *parameter, Lisp_Object *result,
4408 Lisp_Object yesval, Lisp_Object noval,
4409 BOOL is_float, BOOL is_modstring)
4410 /* --------------------------------------------------------------------------
4411 Check a parameter value in user's preferences
4412 -------------------------------------------------------------------------- */
4414 const char *value = ns_get_defaults_value (parameter);
4420 if (c_strcasecmp (value, "YES") == 0)
4422 else if (c_strcasecmp (value, "NO") == 0)
4424 else if (is_float && (f = strtod (value, &pos), pos != value))
4425 *result = make_float (f);
4426 else if (is_modstring && value)
4427 *result = ns_string_to_lispmod (value);
4428 else fprintf (stderr,
4429 "Bad value for default \"%s\": \"%s\"\n", parameter, value);
4435 ns_initialize_display_info (struct ns_display_info *dpyinfo)
4436 /* --------------------------------------------------------------------------
4437 Initialize global info and storage for display.
4438 -------------------------------------------------------------------------- */
4440 NSScreen *screen = [NSScreen mainScreen];
4441 NSWindowDepth depth = [screen depth];
4443 dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
4444 dpyinfo->resy = 72.27;
4445 dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
4446 NSColorSpaceFromDepth (depth)]
4447 && ![NSCalibratedWhiteColorSpace isEqualToString:
4448 NSColorSpaceFromDepth (depth)];
4449 dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
4450 dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
4451 dpyinfo->color_table->colors = NULL;
4452 dpyinfo->root_window = 42; /* a placeholder.. */
4453 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
4454 dpyinfo->n_fonts = 0;
4455 dpyinfo->smallest_font_height = 1;
4456 dpyinfo->smallest_char_width = 1;
4458 reset_mouse_highlight (&dpyinfo->mouse_highlight);
4462 /* This and next define (many of the) public functions in this file. */
4463 /* x_... are generic versions in xdisp.c that we, and other terms, get away
4464 with using despite presence in the "system dependent" redisplay
4465 interface. In addition, many of the ns_ methods have code that is
4466 shared with all terms, indicating need for further refactoring. */
4467 extern frame_parm_handler ns_frame_parm_handlers[];
4468 static struct redisplay_interface ns_redisplay_interface =
4470 ns_frame_parm_handlers,
4474 x_clear_end_of_line,
4476 ns_after_update_window_line,
4477 ns_update_window_begin,
4478 ns_update_window_end,
4479 0, /* flush_display */
4480 x_clear_window_mouse_face,
4481 x_get_glyph_overhangs,
4482 x_fix_overlapping_area,
4483 ns_draw_fringe_bitmap,
4484 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
4485 0, /* destroy_fringe_bitmap */
4486 ns_compute_glyph_string_overhangs,
4487 ns_draw_glyph_string,
4488 ns_define_frame_cursor,
4489 ns_clear_frame_area,
4490 ns_draw_window_cursor,
4491 ns_draw_vertical_window_border,
4492 ns_draw_window_divider,
4493 ns_shift_glyphs_for_insert,
4500 ns_delete_display (struct ns_display_info *dpyinfo)
4506 /* This function is called when the last frame on a display is deleted. */
4508 ns_delete_terminal (struct terminal *terminal)
4510 struct ns_display_info *dpyinfo = terminal->display_info.ns;
4512 NSTRACE ("ns_delete_terminal");
4514 /* Protect against recursive calls. delete_frame in
4515 delete_terminal calls us back when it deletes our last frame. */
4516 if (!terminal->name)
4521 x_destroy_all_bitmaps (dpyinfo);
4522 ns_delete_display (dpyinfo);
4527 static struct terminal *
4528 ns_create_terminal (struct ns_display_info *dpyinfo)
4529 /* --------------------------------------------------------------------------
4530 Set up use of NS before we make the first connection.
4531 -------------------------------------------------------------------------- */
4533 struct terminal *terminal;
4535 NSTRACE ("ns_create_terminal");
4537 terminal = create_terminal (output_ns, &ns_redisplay_interface);
4539 terminal->display_info.ns = dpyinfo;
4540 dpyinfo->terminal = terminal;
4542 terminal->clear_frame_hook = ns_clear_frame;
4543 terminal->ring_bell_hook = ns_ring_bell;
4544 terminal->update_begin_hook = ns_update_begin;
4545 terminal->update_end_hook = ns_update_end;
4546 terminal->read_socket_hook = ns_read_socket;
4547 terminal->frame_up_to_date_hook = ns_frame_up_to_date;
4548 terminal->mouse_position_hook = ns_mouse_position;
4549 terminal->frame_rehighlight_hook = ns_frame_rehighlight;
4550 terminal->frame_raise_lower_hook = ns_frame_raise_lower;
4551 terminal->fullscreen_hook = ns_fullscreen_hook;
4552 terminal->menu_show_hook = ns_menu_show;
4553 terminal->popup_dialog_hook = ns_popup_dialog;
4554 terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
4555 terminal->set_horizontal_scroll_bar_hook = ns_set_horizontal_scroll_bar;
4556 terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
4557 terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
4558 terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
4559 terminal->delete_frame_hook = x_destroy_window;
4560 terminal->delete_terminal_hook = ns_delete_terminal;
4561 /* Other hooks are NULL by default. */
4567 struct ns_display_info *
4568 ns_term_init (Lisp_Object display_name)
4569 /* --------------------------------------------------------------------------
4570 Start the Application and get things rolling.
4571 -------------------------------------------------------------------------- */
4573 struct terminal *terminal;
4574 struct ns_display_info *dpyinfo;
4575 static int ns_initialized = 0;
4578 if (ns_initialized) return x_display_list;
4583 NSTRACE ("ns_term_init");
4585 [outerpool release];
4586 outerpool = [[NSAutoreleasePool alloc] init];
4588 /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4589 /*GSDebugAllocationActive (YES); */
4593 Fset_input_interrupt_mode (Qnil);
4595 if (selfds[0] == -1)
4597 if (emacs_pipe (selfds) != 0)
4599 fprintf (stderr, "Failed to create pipe: %s\n",
4600 emacs_strerror (errno));
4604 fcntl (selfds[0], F_SETFL, O_NONBLOCK|fcntl (selfds[0], F_GETFL));
4605 FD_ZERO (&select_readfds);
4606 FD_ZERO (&select_writefds);
4607 pthread_mutex_init (&select_mutex, NULL);
4610 ns_pending_files = [[NSMutableArray alloc] init];
4611 ns_pending_service_names = [[NSMutableArray alloc] init];
4612 ns_pending_service_args = [[NSMutableArray alloc] init];
4614 /* Start app and create the main menu, window, view.
4615 Needs to be here because ns_initialize_display_info () uses AppKit classes.
4616 The view will then ask the NSApp to stop and return to Emacs. */
4617 [EmacsApp sharedApplication];
4620 [NSApp setDelegate: NSApp];
4622 /* Start the select thread. */
4623 [NSThread detachNewThreadSelector:@selector (fd_handler:)
4627 /* debugging: log all notifications */
4628 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
4629 selector: @selector (logNotification:)
4630 name: nil object: nil]; */
4632 dpyinfo = xzalloc (sizeof *dpyinfo);
4634 ns_initialize_display_info (dpyinfo);
4635 terminal = ns_create_terminal (dpyinfo);
4637 terminal->kboard = allocate_kboard (Qns);
4638 /* Don't let the initial kboard remain current longer than necessary.
4639 That would cause problems if a file loaded on startup tries to
4640 prompt in the mini-buffer. */
4641 if (current_kboard == initial_kboard)
4642 current_kboard = terminal->kboard;
4643 terminal->kboard->reference_count++;
4645 dpyinfo->next = x_display_list;
4646 x_display_list = dpyinfo;
4648 dpyinfo->name_list_element = Fcons (display_name, Qnil);
4650 terminal->name = xlispstrdup (display_name);
4654 if (!inhibit_x_resources)
4656 ns_default ("GSFontAntiAlias", &ns_antialias_text,
4659 /* this is a standard variable */
4660 ns_default ("AppleAntiAliasingThreshold", &tmp,
4661 make_float (10.0), make_float (6.0), YES, NO);
4662 ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4665 NSTRACE_MSG ("Colors");
4668 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4672 Lisp_Object color_file, color_map, color;
4676 color_file = Fexpand_file_name (build_string ("rgb.txt"),
4677 Fsymbol_value (intern ("data-directory")));
4679 color_map = Fx_load_color_file (color_file);
4680 if (NILP (color_map))
4681 fatal ("Could not read %s.\n", SDATA (color_file));
4683 cl = [[NSColorList alloc] initWithName: @"Emacs"];
4684 for ( ; CONSP (color_map); color_map = XCDR (color_map))
4686 color = XCAR (color_map);
4687 name = SSDATA (XCAR (color));
4688 c = XINT (XCDR (color));
4690 [NSColor colorForEmacsRed: RED_FROM_ULONG (c) / 255.0
4691 green: GREEN_FROM_ULONG (c) / 255.0
4692 blue: BLUE_FROM_ULONG (c) / 255.0
4694 forKey: [NSString stringWithUTF8String: name]];
4696 [cl writeToFile: nil];
4700 NSTRACE_MSG ("Versions");
4703 #ifdef NS_IMPL_GNUSTEP
4704 Vwindow_system_version = build_string (gnustep_base_version);
4706 /*PSnextrelease (128, c); */
4707 char c[DBL_BUFSIZE_BOUND];
4708 int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4709 Vwindow_system_version = make_unibyte_string (c, len);
4713 delete_keyboard_wait_descriptor (0);
4715 ns_app_name = [[NSProcessInfo processInfo] processName];
4717 /* Set up OS X app menu */
4719 NSTRACE_MSG ("Menu init");
4721 #ifdef NS_IMPL_COCOA
4725 /* set up the application menu */
4726 svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4727 [svcsMenu setAutoenablesItems: NO];
4728 appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4729 [appMenu setAutoenablesItems: NO];
4730 mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4731 dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4733 [appMenu insertItemWithTitle: @"About Emacs"
4734 action: @selector (orderFrontStandardAboutPanel:)
4737 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4738 [appMenu insertItemWithTitle: @"Preferences..."
4739 action: @selector (showPreferencesWindow:)
4742 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4743 item = [appMenu insertItemWithTitle: @"Services"
4744 action: @selector (menuDown:)
4747 [appMenu setSubmenu: svcsMenu forItem: item];
4748 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4749 [appMenu insertItemWithTitle: @"Hide Emacs"
4750 action: @selector (hide:)
4753 item = [appMenu insertItemWithTitle: @"Hide Others"
4754 action: @selector (hideOtherApplications:)
4757 [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4758 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4759 [appMenu insertItemWithTitle: @"Quit Emacs"
4760 action: @selector (terminate:)
4764 item = [mainMenu insertItemWithTitle: ns_app_name
4765 action: @selector (menuDown:)
4768 [mainMenu setSubmenu: appMenu forItem: item];
4769 [dockMenu insertItemWithTitle: @"New Frame"
4770 action: @selector (newFrame:)
4774 [NSApp setMainMenu: mainMenu];
4775 [NSApp setAppleMenu: appMenu];
4776 [NSApp setServicesMenu: svcsMenu];
4777 /* Needed at least on Cocoa, to get dock menu to show windows */
4778 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4780 [[NSNotificationCenter defaultCenter]
4781 addObserver: mainMenu
4782 selector: @selector (trackingNotification:)
4783 name: NSMenuDidBeginTrackingNotification object: mainMenu];
4784 [[NSNotificationCenter defaultCenter]
4785 addObserver: mainMenu
4786 selector: @selector (trackingNotification:)
4787 name: NSMenuDidEndTrackingNotification object: mainMenu];
4789 #endif /* MAC OS X menu setup */
4791 /* Register our external input/output types, used for determining
4792 applicable services and also drag/drop eligibility. */
4794 NSTRACE_MSG ("Input/output types");
4796 ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
4797 ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
4799 ns_drag_types = [[NSArray arrayWithObjects:
4801 NSTabularTextPboardType,
4802 NSFilenamesPboardType,
4803 NSURLPboardType, nil] retain];
4805 /* If fullscreen is in init/default-frame-alist, focus isn't set
4806 right for fullscreen windows, so set this. */
4807 [NSApp activateIgnoringOtherApps:YES];
4809 NSTRACE_MSG ("Call NSApp run");
4812 ns_do_open_file = YES;
4814 #ifdef NS_IMPL_GNUSTEP
4815 /* GNUstep steals SIGCHLD for use in NSTask, but we don't use NSTask.
4816 We must re-catch it so subprocess works. */
4817 catch_child_signal ();
4820 NSTRACE_MSG ("ns_term_init done");
4829 ns_term_shutdown (int sig)
4831 [[NSUserDefaults standardUserDefaults] synchronize];
4833 /* code not reached in emacs.c after this is called by shut_down_emacs: */
4834 if (STRINGP (Vauto_save_list_file_name))
4835 unlink (SSDATA (Vauto_save_list_file_name));
4837 if (sig == 0 || sig == SIGTERM)
4839 [NSApp terminate: NSApp];
4841 else // force a stack trace to happen
4848 /* ==========================================================================
4850 EmacsApp implementation
4852 ========================================================================== */
4855 @implementation EmacsApp
4859 NSTRACE ("[EmacsApp init]");
4861 if ((self = [super init]))
4863 #ifdef NS_IMPL_COCOA
4864 self->isFirst = YES;
4866 #ifdef NS_IMPL_GNUSTEP
4867 self->applicationDidFinishLaunchingCalled = NO;
4874 #ifdef NS_IMPL_COCOA
4877 NSTRACE ("[EmacsApp run]");
4879 #ifndef NSAppKitVersionNumber10_9
4880 #define NSAppKitVersionNumber10_9 1265
4883 if ((int)NSAppKitVersionNumber != NSAppKitVersionNumber10_9)
4889 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
4891 if (isFirst) [self finishLaunching];
4894 shouldKeepRunning = YES;
4898 pool = [[NSAutoreleasePool alloc] init];
4901 [self nextEventMatchingMask:NSAnyEventMask
4902 untilDate:[NSDate distantFuture]
4903 inMode:NSDefaultRunLoopMode
4906 [self sendEvent:event];
4907 [self updateWindows];
4908 } while (shouldKeepRunning);
4913 - (void)stop: (id)sender
4915 NSTRACE ("[EmacsApp stop:]");
4917 shouldKeepRunning = NO;
4918 // Stop possible dialog also. Noop if no dialog present.
4919 // The file dialog still leaks 7k - 10k on 10.9 though.
4920 [super stop:sender];
4922 #endif /* NS_IMPL_COCOA */
4924 - (void)logNotification: (NSNotification *)notification
4926 NSTRACE ("[EmacsApp logNotification:]");
4928 const char *name = [[notification name] UTF8String];
4929 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4930 && !strstr (name, "WindowNumber"))
4931 NSLog (@"notification: '%@'", [notification name]);
4935 - (void)sendEvent: (NSEvent *)theEvent
4936 /* --------------------------------------------------------------------------
4937 Called when NSApp is running for each event received. Used to stop
4938 the loop when we choose, since there's no way to just run one iteration.
4939 -------------------------------------------------------------------------- */
4941 int type = [theEvent type];
4942 NSWindow *window = [theEvent window];
4944 NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "[EmacsApp sendEvent:]");
4945 NSTRACE_MSG ("Type: %d", type);
4947 #ifdef NS_IMPL_GNUSTEP
4948 // Keyboard events aren't propagated to file dialogs for some reason.
4949 if ([NSApp modalWindow] != nil &&
4950 (type == NSKeyDown || type == NSKeyUp || type == NSFlagsChanged))
4952 [[NSApp modalWindow] sendEvent: theEvent];
4957 if (represented_filename != nil && represented_frame)
4959 NSString *fstr = represented_filename;
4960 NSView *view = FRAME_NS_VIEW (represented_frame);
4961 #ifdef NS_IMPL_COCOA
4962 /* work around a bug observed on 10.3 and later where
4963 setTitleWithRepresentedFilename does not clear out previous state
4964 if given filename does not exist */
4965 if (! [[NSFileManager defaultManager] fileExistsAtPath: fstr])
4966 [[view window] setRepresentedFilename: @""];
4968 [[view window] setRepresentedFilename: fstr];
4969 [represented_filename release];
4970 represented_filename = nil;
4971 represented_frame = NULL;
4974 if (type == NSApplicationDefined)
4976 switch ([theEvent data2])
4978 #ifdef NS_IMPL_COCOA
4979 case NSAPP_DATA2_RUNASSCRIPT:
4984 case NSAPP_DATA2_RUNFILEDIALOG:
4985 ns_run_file_dialog ();
4991 if (type == NSCursorUpdate && window == nil)
4993 fprintf (stderr, "Dropping external cursor update event.\n");
4997 if (type == NSApplicationDefined)
4999 /* Events posted by ns_send_appdefined interrupt the run loop here.
5000 But, if a modal window is up, an appdefined can still come through,
5001 (e.g., from a makeKeyWindow event) but stopping self also stops the
5002 modal loop. Just defer it until later. */
5003 if ([NSApp modalWindow] == nil)
5005 last_appdefined_event_data = [theEvent data1];
5010 send_appdefined = YES;
5015 #ifdef NS_IMPL_COCOA
5016 /* If no dialog and none of our frames have focus and it is a move, skip it.
5017 It is a mouse move in an auxiliary menu, i.e. on the top right on OSX,
5018 such as Wifi, sound, date or similar.
5019 This prevents "spooky" highlighting in the frame under the menu. */
5020 if (type == NSMouseMoved && [NSApp modalWindow] == nil)
5022 struct ns_display_info *di;
5023 BOOL has_focus = NO;
5024 for (di = x_display_list; ! has_focus && di; di = di->next)
5025 has_focus = di->x_focus_frame != 0;
5031 NSTRACE_UNSILENCE();
5033 [super sendEvent: theEvent];
5037 - (void)showPreferencesWindow: (id)sender
5039 struct frame *emacsframe = SELECTED_FRAME ();
5040 NSEvent *theEvent = [NSApp currentEvent];
5044 emacs_event->kind = NS_NONKEY_EVENT;
5045 emacs_event->code = KEY_NS_SHOW_PREFS;
5046 emacs_event->modifiers = 0;
5047 EV_TRAILER (theEvent);
5051 - (void)newFrame: (id)sender
5053 NSTRACE ("[EmacsApp newFrame:]");
5055 struct frame *emacsframe = SELECTED_FRAME ();
5056 NSEvent *theEvent = [NSApp currentEvent];
5060 emacs_event->kind = NS_NONKEY_EVENT;
5061 emacs_event->code = KEY_NS_NEW_FRAME;
5062 emacs_event->modifiers = 0;
5063 EV_TRAILER (theEvent);
5067 /* Open a file (used by below, after going into queue read by ns_read_socket) */
5068 - (BOOL) openFile: (NSString *)fileName
5070 NSTRACE ("[EmacsApp openFile:]");
5072 struct frame *emacsframe = SELECTED_FRAME ();
5073 NSEvent *theEvent = [NSApp currentEvent];
5078 emacs_event->kind = NS_NONKEY_EVENT;
5079 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
5080 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
5081 ns_input_line = Qnil; /* can be start or cons start,end */
5082 emacs_event->modifiers =0;
5083 EV_TRAILER (theEvent);
5089 /* **************************************************************************
5091 EmacsApp delegate implementation
5093 ************************************************************************** */
5095 - (void)applicationDidFinishLaunching: (NSNotification *)notification
5096 /* --------------------------------------------------------------------------
5097 When application is loaded, terminate event loop in ns_term_init
5098 -------------------------------------------------------------------------- */
5100 NSTRACE ("[EmacsApp applicationDidFinishLaunching:]");
5102 #ifdef NS_IMPL_GNUSTEP
5103 ((EmacsApp *)self)->applicationDidFinishLaunchingCalled = YES;
5105 [NSApp setServicesProvider: NSApp];
5107 [self antialiasThresholdDidChange:nil];
5108 #ifdef NS_IMPL_COCOA
5109 [[NSNotificationCenter defaultCenter]
5111 selector:@selector(antialiasThresholdDidChange:)
5112 name:NSAntialiasThresholdChangedNotification
5116 ns_send_appdefined (-2);
5119 - (void)antialiasThresholdDidChange:(NSNotification *)notification
5121 #ifdef NS_IMPL_COCOA
5122 macfont_update_antialias_threshold ();
5127 /* Termination sequences:
5130 MenuBar | File | Exit:
5131 Select Quit from App menubar:
5133 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5136 Select Quit from Dock menu:
5139 Cancel -> Nothing else
5143 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5148 - (void) terminate: (id)sender
5150 NSTRACE ("[EmacsApp terminate:]");
5152 struct frame *emacsframe = SELECTED_FRAME ();
5157 emacs_event->kind = NS_NONKEY_EVENT;
5158 emacs_event->code = KEY_NS_POWER_OFF;
5159 emacs_event->arg = Qt; /* mark as non-key event */
5160 EV_TRAILER ((id)nil);
5164 runAlertPanel(NSString *title,
5165 NSString *msgFormat,
5166 NSString *defaultButton,
5167 NSString *alternateButton)
5169 #if !defined (NS_IMPL_COCOA) || \
5170 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
5171 return NSRunAlertPanel(title, msgFormat, defaultButton, alternateButton, nil)
5172 == NSAlertDefaultReturn;
5174 NSAlert *alert = [[NSAlert alloc] init];
5175 [alert setAlertStyle: NSCriticalAlertStyle];
5176 [alert setMessageText: msgFormat];
5177 [alert addButtonWithTitle: defaultButton];
5178 [alert addButtonWithTitle: alternateButton];
5179 NSInteger ret = [alert runModal];
5181 return ret == NSAlertFirstButtonReturn;
5186 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
5188 NSTRACE ("[EmacsApp applicationShouldTerminate:]");
5192 if (NILP (ns_confirm_quit)) // || ns_shutdown_properly --> TO DO
5193 return NSTerminateNow;
5195 ret = runAlertPanel(ns_app_name,
5196 @"Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?",
5197 @"Save Buffers and Exit", @"Cancel");
5200 return NSTerminateNow;
5202 return NSTerminateCancel;
5203 return NSTerminateNow; /* just in case */
5207 not_in_argv (NSString *arg)
5210 const char *a = [arg UTF8String];
5211 for (k = 1; k < initial_argc; ++k)
5212 if (strcmp (a, initial_argv[k]) == 0) return 0;
5216 /* Notification from the Workspace to open a file */
5217 - (BOOL)application: sender openFile: (NSString *)file
5219 if (ns_do_open_file || not_in_argv (file))
5220 [ns_pending_files addObject: file];
5225 /* Open a file as a temporary file */
5226 - (BOOL)application: sender openTempFile: (NSString *)file
5228 if (ns_do_open_file || not_in_argv (file))
5229 [ns_pending_files addObject: file];
5234 /* Notification from the Workspace to open a file noninteractively (?) */
5235 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
5237 if (ns_do_open_file || not_in_argv (file))
5238 [ns_pending_files addObject: file];
5242 /* Notification from the Workspace to open multiple files */
5243 - (void)application: sender openFiles: (NSArray *)fileList
5245 NSEnumerator *files = [fileList objectEnumerator];
5247 /* Don't open files from the command line unconditionally,
5248 Cocoa parses the command line wrong, --option value tries to open value
5249 if --option is the last option. */
5250 while ((file = [files nextObject]) != nil)
5251 if (ns_do_open_file || not_in_argv (file))
5252 [ns_pending_files addObject: file];
5254 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
5259 /* Handle dock menu requests. */
5260 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
5266 /* TODO: these may help w/IO switching btwn terminal and NSApp */
5267 - (void)applicationWillBecomeActive: (NSNotification *)notification
5269 NSTRACE ("[EmacsApp applicationWillBecomeActive:]");
5270 //ns_app_active=YES;
5273 - (void)applicationDidBecomeActive: (NSNotification *)notification
5275 NSTRACE ("[EmacsApp applicationDidBecomeActive:]");
5277 #ifdef NS_IMPL_GNUSTEP
5278 if (! applicationDidFinishLaunchingCalled)
5279 [self applicationDidFinishLaunching:notification];
5281 //ns_app_active=YES;
5283 ns_update_auto_hide_menu_bar ();
5284 // No constraining takes place when the application is not active.
5285 ns_constrain_all_frames ();
5287 - (void)applicationDidResignActive: (NSNotification *)notification
5289 NSTRACE ("[EmacsApp applicationDidResignActive:]");
5292 ns_send_appdefined (-1);
5297 /* ==========================================================================
5299 EmacsApp aux handlers for managing event loop
5301 ========================================================================== */
5304 - (void)timeout_handler: (NSTimer *)timedEntry
5305 /* --------------------------------------------------------------------------
5306 The timeout specified to ns_select has passed.
5307 -------------------------------------------------------------------------- */
5309 /*NSTRACE ("timeout_handler"); */
5310 ns_send_appdefined (-2);
5313 #ifdef NS_IMPL_GNUSTEP
5314 - (void)sendFromMainThread:(id)unused
5316 ns_send_appdefined (nextappdefined);
5320 - (void)fd_handler:(id)unused
5321 /* --------------------------------------------------------------------------
5322 Check data waiting on file descriptors and terminate if so
5323 -------------------------------------------------------------------------- */
5326 int waiting = 1, nfds;
5329 fd_set readfds, writefds, *wfds;
5330 struct timespec timeout, *tmo;
5331 NSAutoreleasePool *pool = nil;
5333 /* NSTRACE ("fd_handler"); */
5338 pool = [[NSAutoreleasePool alloc] init];
5344 FD_SET (selfds[0], &fds);
5345 result = select (selfds[0]+1, &fds, NULL, NULL, NULL);
5346 if (result > 0 && read (selfds[0], &c, 1) == 1 && c == 'g')
5351 pthread_mutex_lock (&select_mutex);
5354 if (select_valid & SELECT_HAVE_READ)
5355 readfds = select_readfds;
5359 if (select_valid & SELECT_HAVE_WRITE)
5361 writefds = select_writefds;
5366 if (select_valid & SELECT_HAVE_TMO)
5368 timeout = select_timeout;
5374 pthread_mutex_unlock (&select_mutex);
5376 FD_SET (selfds[0], &readfds);
5377 if (selfds[0] >= nfds) nfds = selfds[0]+1;
5379 result = pselect (nfds, &readfds, wfds, NULL, tmo, NULL);
5382 ns_send_appdefined (-2);
5383 else if (result > 0)
5385 if (FD_ISSET (selfds[0], &readfds))
5387 if (read (selfds[0], &c, 1) == 1 && c == 's')
5392 pthread_mutex_lock (&select_mutex);
5393 if (select_valid & SELECT_HAVE_READ)
5394 select_readfds = readfds;
5395 if (select_valid & SELECT_HAVE_WRITE)
5396 select_writefds = writefds;
5397 if (select_valid & SELECT_HAVE_TMO)
5398 select_timeout = timeout;
5399 pthread_mutex_unlock (&select_mutex);
5401 ns_send_appdefined (result);
5411 /* ==========================================================================
5415 ========================================================================== */
5417 /* called from system: queue for next pass through event loop */
5418 - (void)requestService: (NSPasteboard *)pboard
5419 userData: (NSString *)userData
5420 error: (NSString **)error
5422 [ns_pending_service_names addObject: userData];
5423 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
5424 SSDATA (ns_string_from_pasteboard (pboard))]];
5428 /* called from ns_read_socket to clear queue */
5429 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
5431 struct frame *emacsframe = SELECTED_FRAME ();
5432 NSEvent *theEvent = [NSApp currentEvent];
5434 NSTRACE ("[EmacsApp fulfillService:withArg:]");
5439 emacs_event->kind = NS_NONKEY_EVENT;
5440 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
5441 ns_input_spi_name = build_string ([name UTF8String]);
5442 ns_input_spi_arg = build_string ([arg UTF8String]);
5443 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5444 EV_TRAILER (theEvent);
5454 /* ==========================================================================
5456 EmacsView implementation
5458 ========================================================================== */
5461 @implementation EmacsView
5463 /* needed to inform when window closed from LISP */
5464 - (void) setWindowClosing: (BOOL)closing
5466 NSTRACE ("[EmacsView setWindowClosing:%d]", closing);
5468 windowClosing = closing;
5474 NSTRACE ("[EmacsView dealloc]");
5476 if (fs_state == FULLSCREEN_BOTH)
5477 [nonfs_window release];
5482 /* called on font panel selection */
5483 - (void)changeFont: (id)sender
5485 NSEvent *e = [[self window] currentEvent];
5486 struct face *face = FRAME_DEFAULT_FACE (emacsframe);
5487 struct font *font = face->font;
5492 NSTRACE ("[EmacsView changeFont:]");
5497 #ifdef NS_IMPL_GNUSTEP
5498 nsfont = ((struct nsfont_info *)font)->nsfont;
5500 #ifdef NS_IMPL_COCOA
5501 nsfont = (NSFont *) macfont_get_nsctfont (font);
5504 if ((newFont = [sender convertFont: nsfont]))
5506 SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
5508 emacs_event->kind = NS_NONKEY_EVENT;
5509 emacs_event->modifiers = 0;
5510 emacs_event->code = KEY_NS_CHANGE_FONT;
5512 size = [newFont pointSize];
5513 ns_input_fontsize = make_number (lrint (size));
5514 ns_input_font = build_string ([[newFont familyName] UTF8String]);
5520 - (BOOL)acceptsFirstResponder
5522 NSTRACE ("[EmacsView acceptsFirstResponder]");
5527 - (void)resetCursorRects
5529 NSRect visible = [self visibleRect];
5530 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
5531 NSTRACE ("[EmacsView resetCursorRects]");
5533 if (currentCursor == nil)
5534 currentCursor = [NSCursor arrowCursor];
5536 if (!NSIsEmptyRect (visible))
5537 [self addCursorRect: visible cursor: currentCursor];
5538 [currentCursor setOnMouseEntered: YES];
5543 /*****************************************************************************/
5544 /* Keyboard handling. */
5547 - (void)keyDown: (NSEvent *)theEvent
5549 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5551 unsigned fnKeysym = 0;
5552 static NSMutableArray *nsEvArray;
5554 unsigned int flags = [theEvent modifierFlags];
5556 NSTRACE ("[EmacsView keyDown:]");
5558 /* Rhapsody and OS X give up and down events for the arrow keys */
5559 if (ns_fake_keydown == YES)
5560 ns_fake_keydown = NO;
5561 else if ([theEvent type] != NSKeyDown)
5567 if (![[self window] isKeyWindow]
5568 && [[theEvent window] isKindOfClass: [EmacsWindow class]]
5569 /* we must avoid an infinite loop here. */
5570 && (EmacsView *)[[theEvent window] delegate] != self)
5572 /* XXX: There is an occasional condition in which, when Emacs display
5573 updates a different frame from the current one, and temporarily
5574 selects it, then processes some interrupt-driven input
5575 (dispnew.c:3878), OS will send the event to the correct NSWindow, but
5576 for some reason that window has its first responder set to the NSView
5577 most recently updated (I guess), which is not the correct one. */
5578 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
5582 if (nsEvArray == nil)
5583 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
5585 [NSCursor setHiddenUntilMouseMoves: YES];
5587 if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
5589 clear_mouse_face (hlinfo);
5590 hlinfo->mouse_face_hidden = 1;
5593 if (!processingCompose)
5595 /* When using screen sharing, no left or right information is sent,
5596 so use Left key in those cases. */
5597 int is_left_key, is_right_key;
5599 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
5600 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
5602 /* (Carbon way: [theEvent keyCode]) */
5604 /* is it a "function key"? */
5605 /* Note: Sometimes a plain key will have the NSNumericPadKeyMask
5606 flag set (this is probably a bug in the OS).
5608 if (code < 0x00ff && (flags&NSNumericPadKeyMask))
5610 fnKeysym = ns_convert_key ([theEvent keyCode] | NSNumericPadKeyMask);
5614 fnKeysym = ns_convert_key (code);
5619 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
5620 because Emacs treats Delete and KP-Delete same (in simple.el). */
5621 if ((fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
5622 #ifdef NS_IMPL_GNUSTEP
5623 /* GNUstep uses incompatible keycodes, even for those that are
5624 supposed to be hardware independent. Just check for delete.
5625 Keypad delete does not have keysym 0xFFFF.
5626 See http://savannah.gnu.org/bugs/?25395
5628 || (fnKeysym == 0xFFFF && code == 127)
5631 code = 0xFF08; /* backspace */
5636 /* are there modifiers? */
5637 emacs_event->modifiers = 0;
5639 if (flags & NSHelpKeyMask)
5640 emacs_event->modifiers |= hyper_modifier;
5642 if (flags & NSShiftKeyMask)
5643 emacs_event->modifiers |= shift_modifier;
5645 is_right_key = (flags & NSRightCommandKeyMask) == NSRightCommandKeyMask;
5646 is_left_key = (flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask
5647 || (! is_right_key && (flags & NSCommandKeyMask) == NSCommandKeyMask);
5650 emacs_event->modifiers |= parse_solitary_modifier
5651 (EQ (ns_right_command_modifier, Qleft)
5652 ? ns_command_modifier
5653 : ns_right_command_modifier);
5657 emacs_event->modifiers |= parse_solitary_modifier
5658 (ns_command_modifier);
5660 /* if super (default), take input manager's word so things like
5661 dvorak / qwerty layout work */
5662 if (EQ (ns_command_modifier, Qsuper)
5664 && [[theEvent characters] length] != 0)
5666 /* XXX: the code we get will be unshifted, so if we have
5667 a shift modifier, must convert ourselves */
5668 if (!(flags & NSShiftKeyMask))
5669 code = [[theEvent characters] characterAtIndex: 0];
5671 /* this is ugly and also requires linking w/Carbon framework
5672 (for LMGetKbdType) so for now leave this rare (?) case
5673 undealt with.. in future look into CGEvent methods */
5676 long smv = GetScriptManagerVariable (smKeyScript);
5677 Handle uchrHandle = GetResource
5678 ('uchr', GetScriptVariable (smv, smScriptKeys));
5680 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
5681 [[theEvent characters] characterAtIndex: 0],
5682 kUCKeyActionDisplay,
5683 (flags & ~NSCommandKeyMask) >> 8,
5684 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
5685 &dummy, 1, &dummy, &code);
5692 is_right_key = (flags & NSRightControlKeyMask) == NSRightControlKeyMask;
5693 is_left_key = (flags & NSLeftControlKeyMask) == NSLeftControlKeyMask
5694 || (! is_right_key && (flags & NSControlKeyMask) == NSControlKeyMask);
5697 emacs_event->modifiers |= parse_solitary_modifier
5698 (EQ (ns_right_control_modifier, Qleft)
5699 ? ns_control_modifier
5700 : ns_right_control_modifier);
5703 emacs_event->modifiers |= parse_solitary_modifier
5704 (ns_control_modifier);
5706 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
5707 emacs_event->modifiers |=
5708 parse_solitary_modifier (ns_function_modifier);
5710 left_is_none = NILP (ns_alternate_modifier)
5711 || EQ (ns_alternate_modifier, Qnone);
5713 is_right_key = (flags & NSRightAlternateKeyMask)
5714 == NSRightAlternateKeyMask;
5715 is_left_key = (flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask
5717 && (flags & NSAlternateKeyMask) == NSAlternateKeyMask);
5721 if ((NILP (ns_right_alternate_modifier)
5722 || EQ (ns_right_alternate_modifier, Qnone)
5723 || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
5725 { /* accept pre-interp alt comb */
5726 if ([[theEvent characters] length] > 0)
5727 code = [[theEvent characters] characterAtIndex: 0];
5728 /*HACK: clear lone shift modifier to stop next if from firing */
5729 if (emacs_event->modifiers == shift_modifier)
5730 emacs_event->modifiers = 0;
5733 emacs_event->modifiers |= parse_solitary_modifier
5734 (EQ (ns_right_alternate_modifier, Qleft)
5735 ? ns_alternate_modifier
5736 : ns_right_alternate_modifier);
5739 if (is_left_key) /* default = meta */
5741 if (left_is_none && !fnKeysym)
5742 { /* accept pre-interp alt comb */
5743 if ([[theEvent characters] length] > 0)
5744 code = [[theEvent characters] characterAtIndex: 0];
5745 /*HACK: clear lone shift modifier to stop next if from firing */
5746 if (emacs_event->modifiers == shift_modifier)
5747 emacs_event->modifiers = 0;
5750 emacs_event->modifiers |=
5751 parse_solitary_modifier (ns_alternate_modifier);
5755 fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
5756 code, fnKeysym, flags, emacs_event->modifiers);
5758 /* if it was a function key or had modifiers, pass it directly to emacs */
5759 if (fnKeysym || (emacs_event->modifiers
5760 && (emacs_event->modifiers != shift_modifier)
5761 && [[theEvent charactersIgnoringModifiers] length] > 0))
5762 /*[[theEvent characters] length] */
5764 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5766 code |= (1<<28)|(3<<16);
5767 else if (code == 0x7f)
5768 code |= (1<<28)|(3<<16);
5770 emacs_event->kind = code > 0xFF
5771 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5773 emacs_event->code = code;
5774 EV_TRAILER (theEvent);
5775 processingCompose = NO;
5781 if (NS_KEYLOG && !processingCompose)
5782 fprintf (stderr, "keyDown: Begin compose sequence.\n");
5784 processingCompose = YES;
5785 [nsEvArray addObject: theEvent];
5786 [self interpretKeyEvents: nsEvArray];
5787 [nsEvArray removeObject: theEvent];
5791 #ifdef NS_IMPL_COCOA
5792 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
5793 decided not to send key-down for.
5794 See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
5795 This only applies on Tiger and earlier.
5796 If it matches one of these, send it on to keyDown. */
5797 -(void)keyUp: (NSEvent *)theEvent
5799 int flags = [theEvent modifierFlags];
5800 int code = [theEvent keyCode];
5802 NSTRACE ("[EmacsView keyUp:]");
5804 if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
5805 code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
5808 fprintf (stderr, "keyUp: passed test");
5809 ns_fake_keydown = YES;
5810 [self keyDown: theEvent];
5816 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
5819 /* <NSTextInput>: called when done composing;
5820 NOTE: also called when we delete over working text, followed immed.
5821 by doCommandBySelector: deleteBackward: */
5822 - (void)insertText: (id)aString
5825 int len = [(NSString *)aString length];
5828 NSTRACE ("[EmacsView insertText:]");
5831 NSLog (@"insertText '%@'\tlen = %d", aString, len);
5832 processingCompose = NO;
5837 /* first, clear any working text */
5838 if (workingText != nil)
5839 [self deleteWorkingText];
5841 /* now insert the string as keystrokes */
5842 for (i =0; i<len; i++)
5844 code = [aString characterAtIndex: i];
5845 /* TODO: still need this? */
5847 code = '~'; /* 0x7E */
5848 if (code != 32) /* Space */
5849 emacs_event->modifiers = 0;
5851 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5852 emacs_event->code = code;
5853 EV_TRAILER ((id)nil);
5858 /* <NSTextInput>: inserts display of composing characters */
5859 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
5861 NSString *str = [aString respondsToSelector: @selector (string)] ?
5862 [aString string] : aString;
5864 NSTRACE ("[EmacsView setMarkedText:selectedRange:]");
5867 NSLog (@"setMarkedText '%@' len =%lu range %lu from %lu",
5868 str, (unsigned long)[str length],
5869 (unsigned long)selRange.length,
5870 (unsigned long)selRange.location);
5872 if (workingText != nil)
5873 [self deleteWorkingText];
5874 if ([str length] == 0)
5880 processingCompose = YES;
5881 workingText = [str copy];
5882 ns_working_text = build_string ([workingText UTF8String]);
5884 emacs_event->kind = NS_TEXT_EVENT;
5885 emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
5886 EV_TRAILER ((id)nil);
5890 /* delete display of composing characters [not in <NSTextInput>] */
5891 - (void)deleteWorkingText
5893 NSTRACE ("[EmacsView deleteWorkingText]");
5895 if (workingText == nil)
5898 NSLog(@"deleteWorkingText len =%lu\n", (unsigned long)[workingText length]);
5899 [workingText release];
5901 processingCompose = NO;
5906 emacs_event->kind = NS_TEXT_EVENT;
5907 emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
5908 EV_TRAILER ((id)nil);
5912 - (BOOL)hasMarkedText
5914 NSTRACE ("[EmacsView hasMarkedText]");
5916 return workingText != nil;
5920 - (NSRange)markedRange
5922 NSTRACE ("[EmacsView markedRange]");
5924 NSRange rng = workingText != nil
5925 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
5927 NSLog (@"markedRange request");
5934 NSTRACE ("[EmacsView unmarkText]");
5937 NSLog (@"unmark (accept) text");
5938 [self deleteWorkingText];
5939 processingCompose = NO;
5943 /* used to position char selection windows, etc. */
5944 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
5948 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
5950 NSTRACE ("[EmacsView firstRectForCharacterRange:]");
5953 NSLog (@"firstRectForCharRange request");
5955 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
5956 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
5957 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
5958 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
5959 +FRAME_LINE_HEIGHT (emacsframe));
5961 pt = [self convertPoint: pt toView: nil];
5962 pt = [[self window] convertBaseToScreen: pt];
5968 - (NSInteger)conversationIdentifier
5970 return (NSInteger)self;
5974 - (void)doCommandBySelector: (SEL)aSelector
5976 NSTRACE ("[EmacsView doCommandBySelector:]");
5979 NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
5981 processingCompose = NO;
5982 if (aSelector == @selector (deleteBackward:))
5984 /* happens when user backspaces over an ongoing composition:
5985 throw a 'delete' into the event queue */
5988 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5989 emacs_event->code = 0xFF08;
5990 EV_TRAILER ((id)nil);
5994 - (NSArray *)validAttributesForMarkedText
5996 static NSArray *arr = nil;
5997 if (arr == nil) arr = [NSArray new];
5998 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
6002 - (NSRange)selectedRange
6005 NSLog (@"selectedRange request");
6006 return NSMakeRange (NSNotFound, 0);
6009 #if defined (NS_IMPL_COCOA) || GNUSTEP_GUI_MAJOR_VERSION > 0 || \
6010 GNUSTEP_GUI_MINOR_VERSION > 22
6011 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
6013 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
6017 NSLog (@"characterIndexForPoint request");
6021 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
6023 static NSAttributedString *str = nil;
6024 if (str == nil) str = [NSAttributedString new];
6026 NSLog (@"attributedSubstringFromRange request");
6030 /* End <NSTextInput> impl. */
6031 /*****************************************************************************/
6034 /* This is what happens when the user presses a mouse button. */
6035 - (void)mouseDown: (NSEvent *)theEvent
6037 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6038 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
6040 NSTRACE ("[EmacsView mouseDown:]");
6042 [self deleteWorkingText];
6047 dpyinfo->last_mouse_frame = emacsframe;
6048 /* appears to be needed to prevent spurious movement events generated on
6050 emacsframe->mouse_moved = 0;
6052 if ([theEvent type] == NSScrollWheel)
6054 CGFloat delta = [theEvent deltaY];
6055 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
6058 delta = [theEvent deltaX];
6061 NSTRACE_MSG ("deltaIsZero");
6064 emacs_event->kind = HORIZ_WHEEL_EVENT;
6067 emacs_event->kind = WHEEL_EVENT;
6069 emacs_event->code = 0;
6070 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
6071 ((delta > 0) ? up_modifier : down_modifier);
6075 emacs_event->kind = MOUSE_CLICK_EVENT;
6076 emacs_event->code = EV_BUTTON (theEvent);
6077 emacs_event->modifiers = EV_MODIFIERS (theEvent)
6078 | EV_UDMODIFIERS (theEvent);
6080 XSETINT (emacs_event->x, lrint (p.x));
6081 XSETINT (emacs_event->y, lrint (p.y));
6082 EV_TRAILER (theEvent);
6086 - (void)rightMouseDown: (NSEvent *)theEvent
6088 NSTRACE ("[EmacsView rightMouseDown:]");
6089 [self mouseDown: theEvent];
6093 - (void)otherMouseDown: (NSEvent *)theEvent
6095 NSTRACE ("[EmacsView otherMouseDown:]");
6096 [self mouseDown: theEvent];
6100 - (void)mouseUp: (NSEvent *)theEvent
6102 NSTRACE ("[EmacsView mouseUp:]");
6103 [self mouseDown: theEvent];
6107 - (void)rightMouseUp: (NSEvent *)theEvent
6109 NSTRACE ("[EmacsView rightMouseUp:]");
6110 [self mouseDown: theEvent];
6114 - (void)otherMouseUp: (NSEvent *)theEvent
6116 NSTRACE ("[EmacsView otherMouseUp:]");
6117 [self mouseDown: theEvent];
6121 - (void) scrollWheel: (NSEvent *)theEvent
6123 NSTRACE ("[EmacsView scrollWheel:]");
6124 [self mouseDown: theEvent];
6128 /* Tell emacs the mouse has moved. */
6129 - (void)mouseMoved: (NSEvent *)e
6131 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
6132 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6136 NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "[EmacsView mouseMoved:]");
6138 dpyinfo->last_mouse_movement_time = EV_TIMESTAMP (e);
6139 pt = [self convertPoint: [e locationInWindow] fromView: nil];
6140 dpyinfo->last_mouse_motion_x = pt.x;
6141 dpyinfo->last_mouse_motion_y = pt.y;
6143 /* update any mouse face */
6144 if (hlinfo->mouse_face_hidden)
6146 hlinfo->mouse_face_hidden = 0;
6147 clear_mouse_face (hlinfo);
6150 /* tooltip handling */
6151 previous_help_echo_string = help_echo_string;
6152 help_echo_string = Qnil;
6154 if (!NILP (Vmouse_autoselect_window))
6156 NSTRACE_MSG ("mouse_autoselect_window");
6157 static Lisp_Object last_mouse_window;
6159 = window_from_coordinates (emacsframe, pt.x, pt.y, 0, 0);
6161 if (WINDOWP (window)
6162 && !EQ (window, last_mouse_window)
6163 && !EQ (window, selected_window)
6164 && (focus_follows_mouse
6165 || (EQ (XWINDOW (window)->frame,
6166 XWINDOW (selected_window)->frame))))
6168 NSTRACE_MSG ("in_window");
6169 emacs_event->kind = SELECT_WINDOW_EVENT;
6170 emacs_event->frame_or_window = window;
6173 /* Remember the last window where we saw the mouse. */
6174 last_mouse_window = window;
6177 if (!note_mouse_movement (emacsframe, pt.x, pt.y))
6178 help_echo_string = previous_help_echo_string;
6180 XSETFRAME (frame, emacsframe);
6181 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
6183 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
6184 (note_mouse_highlight), which is called through the
6185 note_mouse_movement () call above */
6186 any_help_event_p = YES;
6187 gen_help_event (help_echo_string, frame, help_echo_window,
6188 help_echo_object, help_echo_pos);
6191 if (emacsframe->mouse_moved && send_appdefined)
6192 ns_send_appdefined (-1);
6196 - (void)mouseDragged: (NSEvent *)e
6198 NSTRACE ("[EmacsView mouseDragged:]");
6199 [self mouseMoved: e];
6203 - (void)rightMouseDragged: (NSEvent *)e
6205 NSTRACE ("[EmacsView rightMouseDragged:]");
6206 [self mouseMoved: e];
6210 - (void)otherMouseDragged: (NSEvent *)e
6212 NSTRACE ("[EmacsView otherMouseDragged:]");
6213 [self mouseMoved: e];
6217 - (BOOL)windowShouldClose: (id)sender
6219 NSEvent *e =[[self window] currentEvent];
6221 NSTRACE ("[EmacsView windowShouldClose:]");
6222 windowClosing = YES;
6225 emacs_event->kind = DELETE_WINDOW_EVENT;
6226 emacs_event->modifiers = 0;
6227 emacs_event->code = 0;
6229 /* Don't close this window, let this be done from lisp code. */
6233 - (void) updateFrameSize: (BOOL) delay;
6235 NSWindow *window = [self window];
6236 NSRect wr = [window frame];
6238 int oldc = cols, oldr = rows;
6239 int oldw = FRAME_PIXEL_WIDTH (emacsframe);
6240 int oldh = FRAME_PIXEL_HEIGHT (emacsframe);
6243 NSTRACE ("[EmacsView updateFrameSize:]");
6244 NSTRACE_SIZE ("Original size", NSMakeSize (oldw, oldh));
6245 NSTRACE_RECT ("Original frame", wr);
6246 NSTRACE_MSG ("Original columns: %d", cols);
6247 NSTRACE_MSG ("Original rows: %d", rows);
6249 if (! [self isFullscreen])
6251 #ifdef NS_IMPL_GNUSTEP
6252 // GNUstep does not always update the tool bar height. Force it.
6253 if (toolbar && [toolbar isVisible])
6254 update_frame_tool_bar (emacsframe);
6257 extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6258 + FRAME_TOOLBAR_HEIGHT (emacsframe);
6261 if (wait_for_tool_bar)
6263 if (FRAME_TOOLBAR_HEIGHT (emacsframe) == 0)
6265 NSTRACE_MSG ("Waiting for toolbar");
6268 wait_for_tool_bar = NO;
6271 neww = (int)wr.size.width - emacsframe->border_width;
6272 newh = (int)wr.size.height - extra;
6274 NSTRACE_SIZE ("New size", NSMakeSize (neww, newh));
6275 NSTRACE_MSG ("tool_bar_height: %d", emacsframe->tool_bar_height);
6277 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, neww);
6278 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, newh);
6280 if (cols < MINWIDTH)
6283 if (rows < MINHEIGHT)
6286 NSTRACE_MSG ("New columns: %d", cols);
6287 NSTRACE_MSG ("New rows: %d", rows);
6289 if (oldr != rows || oldc != cols || neww != oldw || newh != oldh)
6291 NSView *view = FRAME_NS_VIEW (emacsframe);
6292 NSWindow *win = [view window];
6294 change_frame_size (emacsframe,
6295 FRAME_PIXEL_TO_TEXT_WIDTH (emacsframe, neww),
6296 FRAME_PIXEL_TO_TEXT_HEIGHT (emacsframe, newh),
6298 SET_FRAME_GARBAGED (emacsframe);
6299 cancel_mouse_face (emacsframe);
6301 wr = NSMakeRect (0, 0, neww, newh);
6303 [view setFrame: wr];
6305 // to do: consider using [NSNotificationCenter postNotificationName:].
6306 [self windowDidMove: // Update top/left.
6307 [NSNotification notificationWithName:NSWindowDidMoveNotification
6308 object:[view window]]];
6312 NSTRACE_MSG ("No change");
6316 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
6317 /* normalize frame to gridded text size */
6321 NSTRACE ("[EmacsView windowWillResize:toSize: " NSTRACE_FMT_SIZE "]",
6322 NSTRACE_ARG_SIZE (frameSize));
6323 NSTRACE_RECT ("[sender frame]", [sender frame]);
6324 NSTRACE_FSTYPE ("fs_state", fs_state);
6326 if (fs_state == FULLSCREEN_MAXIMIZED
6327 && (maximized_width != (int)frameSize.width
6328 || maximized_height != (int)frameSize.height))
6329 [self setFSValue: FULLSCREEN_NONE];
6330 else if (fs_state == FULLSCREEN_WIDTH
6331 && maximized_width != (int)frameSize.width)
6332 [self setFSValue: FULLSCREEN_NONE];
6333 else if (fs_state == FULLSCREEN_HEIGHT
6334 && maximized_height != (int)frameSize.height)
6335 [self setFSValue: FULLSCREEN_NONE];
6337 if (fs_state == FULLSCREEN_NONE)
6338 maximized_width = maximized_height = -1;
6340 if (! [self isFullscreen])
6342 extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6343 + FRAME_TOOLBAR_HEIGHT (emacsframe);
6346 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, frameSize.width);
6347 if (cols < MINWIDTH)
6350 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe,
6351 frameSize.height - extra);
6352 if (rows < MINHEIGHT)
6354 #ifdef NS_IMPL_COCOA
6356 /* this sets window title to have size in it; the wm does this under GS */
6357 NSRect r = [[self window] frame];
6358 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
6366 else if (fs_state == FULLSCREEN_NONE && ! maximizing_resize)
6369 NSWindow *window = [self window];
6372 char *t = strdup ([[[self window] title] UTF8String]);
6373 char *pos = strstr (t, " — ");
6378 size_title = xmalloc (strlen (old_title) + 40);
6379 esprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
6380 [window setTitle: [NSString stringWithUTF8String: size_title]];
6385 #endif /* NS_IMPL_COCOA */
6387 NSTRACE_MSG ("cols: %d rows: %d", cols, rows);
6389 /* Restrict the new size to the text gird.
6391 Don't restrict the width if the user only adjusted the height, and
6392 vice versa. (Without this, the frame would shrink, and move
6393 slightly, if the window was resized by dragging one of its
6395 if (!frame_resize_pixelwise)
6397 NSRect r = [[self window] frame];
6399 if (r.size.width != frameSize.width)
6402 FRAME_TEXT_COLS_TO_PIXEL_WIDTH (emacsframe, cols);
6405 if (r.size.height != frameSize.height)
6408 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows) + extra;
6412 NSTRACE_RETURN_SIZE (frameSize);
6418 - (void)windowDidResize: (NSNotification *)notification
6420 NSTRACE ("[EmacsView windowDidResize:]");
6421 if (!FRAME_LIVE_P (emacsframe))
6423 NSTRACE_MSG ("Ignored (frame dead)");
6426 if (emacsframe->output_data.ns->in_animation)
6428 NSTRACE_MSG ("Ignored (in animation)");
6432 if (! [self fsIsNative])
6434 NSWindow *theWindow = [notification object];
6435 /* We can get notification on the non-FS window when in
6437 if ([self window] != theWindow) return;
6440 NSTRACE_RECT ("frame", [[notification object] frame]);
6442 #ifdef NS_IMPL_GNUSTEP
6443 NSWindow *theWindow = [notification object];
6445 /* In GNUstep, at least currently, it's possible to get a didResize
6446 without getting a willResize.. therefore we need to act as if we got
6447 the willResize now */
6448 NSSize sz = [theWindow frame].size;
6449 sz = [self windowWillResize: theWindow toSize: sz];
6450 #endif /* NS_IMPL_GNUSTEP */
6452 if (cols > 0 && rows > 0)
6454 [self updateFrameSize: YES];
6457 ns_send_appdefined (-1);
6460 #ifdef NS_IMPL_COCOA
6461 - (void)viewDidEndLiveResize
6463 NSTRACE ("[EmacsView viewDidEndLiveResize]");
6465 [super viewDidEndLiveResize];
6468 [[self window] setTitle: [NSString stringWithUTF8String: old_title]];
6472 maximizing_resize = NO;
6474 #endif /* NS_IMPL_COCOA */
6477 - (void)windowDidBecomeKey: (NSNotification *)notification
6478 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6480 [self windowDidBecomeKey];
6484 - (void)windowDidBecomeKey /* for direct calls */
6486 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6487 struct frame *old_focus = dpyinfo->x_focus_frame;
6489 NSTRACE ("[EmacsView windowDidBecomeKey]");
6491 if (emacsframe != old_focus)
6492 dpyinfo->x_focus_frame = emacsframe;
6494 ns_frame_rehighlight (emacsframe);
6498 emacs_event->kind = FOCUS_IN_EVENT;
6499 EV_TRAILER ((id)nil);
6504 - (void)windowDidResignKey: (NSNotification *)notification
6505 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6507 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6508 BOOL is_focus_frame = dpyinfo->x_focus_frame == emacsframe;
6509 NSTRACE ("[EmacsView windowDidResignKey:]");
6512 dpyinfo->x_focus_frame = 0;
6514 emacsframe->mouse_moved = 0;
6515 ns_frame_rehighlight (emacsframe);
6517 /* FIXME: for some reason needed on second and subsequent clicks away
6518 from sole-frame Emacs to get hollow box to show */
6519 if (!windowClosing && [[self window] isVisible] == YES)
6521 x_update_cursor (emacsframe, 1);
6522 x_set_frame_alpha (emacsframe);
6525 if (any_help_event_p)
6528 XSETFRAME (frame, emacsframe);
6529 help_echo_string = Qnil;
6530 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
6533 if (emacs_event && is_focus_frame)
6535 [self deleteWorkingText];
6536 emacs_event->kind = FOCUS_OUT_EVENT;
6537 EV_TRAILER ((id)nil);
6542 - (void)windowWillMiniaturize: sender
6544 NSTRACE ("[EmacsView windowWillMiniaturize:]");
6548 - (void)setFrame:(NSRect)frameRect;
6550 NSTRACE ("[EmacsView setFrame:" NSTRACE_FMT_RECT "]",
6551 NSTRACE_ARG_RECT (frameRect));
6553 [super setFrame:(NSRect)frameRect];
6569 - initFrameFromEmacs: (struct frame *)f
6577 NSTRACE ("[EmacsView initFrameFromEmacs:]");
6578 NSTRACE_MSG ("cols:%d lines:%d\n", f->text_cols, f->text_lines);
6581 processingCompose = NO;
6582 scrollbarsNeedingUpdate = 0;
6583 fs_state = FULLSCREEN_NONE;
6584 fs_before_fs = next_maximized = -1;
6585 #ifdef HAVE_NATIVE_FS
6586 fs_is_native = ns_use_native_fullscreen;
6590 maximized_width = maximized_height = -1;
6593 ns_userRect = NSMakeRect (0, 0, 0, 0);
6594 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
6595 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
6596 [self initWithFrame: r];
6597 [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
6599 FRAME_NS_VIEW (f) = self;
6601 #ifdef NS_IMPL_COCOA
6603 maximizing_resize = NO;
6606 win = [[EmacsWindow alloc]
6607 initWithContentRect: r
6608 styleMask: (NSResizableWindowMask |
6609 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6610 NSTitledWindowMask |
6612 NSMiniaturizableWindowMask |
6613 NSClosableWindowMask)
6614 backing: NSBackingStoreBuffered
6617 #ifdef HAVE_NATIVE_FS
6618 [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
6622 bwidth = f->border_width = wr.size.width - r.size.width;
6623 tibar_height = FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
6625 [win setAcceptsMouseMovedEvents: YES];
6626 [win setDelegate: self];
6627 #if !defined (NS_IMPL_COCOA) || \
6628 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6629 [win useOptimizedDrawing: YES];
6632 [[win contentView] addSubview: self];
6635 [self registerForDraggedTypes: ns_drag_types];
6638 name = [NSString stringWithUTF8String:
6639 NILP (tem) ? "Emacs" : SSDATA (tem)];
6640 [win setTitle: name];
6642 /* toolbar support */
6643 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
6644 [NSString stringWithFormat: @"Emacs Frame %d",
6646 [win setToolbar: toolbar];
6647 [toolbar setVisible: NO];
6649 /* Don't set frame garbaged until tool bar is up to date?
6650 This avoids an extra clear and redraw (flicker) at frame creation. */
6651 if (FRAME_EXTERNAL_TOOL_BAR (f)) wait_for_tool_bar = YES;
6652 else wait_for_tool_bar = NO;
6655 #ifdef NS_IMPL_COCOA
6657 NSButton *toggleButton;
6658 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
6659 [toggleButton setTarget: self];
6660 [toggleButton setAction: @selector (toggleToolbar: )];
6663 FRAME_TOOLBAR_HEIGHT (f) = 0;
6667 [win setMiniwindowTitle:
6668 [NSString stringWithUTF8String: SSDATA (tem)]];
6671 NSScreen *screen = [win screen];
6675 NSPoint pt = NSMakePoint
6676 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
6677 IN_BOUND (-SCREENMAX,
6678 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX));
6680 [win setFrameTopLeftPoint: pt];
6682 NSTRACE_RECT ("new frame", [win frame]);
6686 [win makeFirstResponder: self];
6688 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6689 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
6690 [win setBackgroundColor: col];
6691 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6692 [win setOpaque: NO];
6694 #if !defined (NS_IMPL_COCOA) || \
6695 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6696 [self allocateGState];
6698 [NSApp registerServicesMenuSendTypes: ns_send_types
6706 - (void)windowDidMove: sender
6708 NSWindow *win = [self window];
6709 NSRect r = [win frame];
6710 NSArray *screens = [NSScreen screens];
6711 NSScreen *screen = [screens objectAtIndex: 0];
6713 NSTRACE ("[EmacsView windowDidMove:]");
6715 if (!emacsframe->output_data.ns)
6719 emacsframe->left_pos = r.origin.x;
6720 emacsframe->top_pos =
6721 [screen frame].size.height - (r.origin.y + r.size.height);
6726 /* Called AFTER method below, but before our windowWillResize call there leads
6727 to windowDidResize -> x_set_window_size. Update emacs' notion of frame
6728 location so set_window_size moves the frame. */
6729 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
6731 NSTRACE (("[EmacsView windowShouldZoom:toFrame:" NSTRACE_FMT_RECT "]"
6732 NSTRACE_FMT_RETURN "YES"),
6733 NSTRACE_ARG_RECT (newFrame));
6735 emacsframe->output_data.ns->zooming = 1;
6740 /* Override to do something slightly nonstandard, but nice. First click on
6741 zoom button will zoom vertically. Second will zoom completely. Third
6742 returns to original. */
6743 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
6744 defaultFrame:(NSRect)defaultFrame
6746 // TODO: Rename to "currentFrame" and assign "result" properly in
6748 NSRect result = [sender frame];
6750 NSTRACE (("[EmacsView windowWillUseStandardFrame:defaultFrame:"
6751 NSTRACE_FMT_RECT "]"),
6752 NSTRACE_ARG_RECT (defaultFrame));
6753 NSTRACE_FSTYPE ("fs_state", fs_state);
6754 NSTRACE_FSTYPE ("fs_before_fs", fs_before_fs);
6755 NSTRACE_FSTYPE ("next_maximized", next_maximized);
6756 NSTRACE_RECT ("ns_userRect", ns_userRect);
6757 NSTRACE_RECT ("[sender frame]", [sender frame]);
6759 if (fs_before_fs != -1) /* Entering fullscreen */
6761 NSTRACE_MSG ("Entering fullscreen");
6762 result = defaultFrame;
6766 // Save the window size and position (frame) before the resize.
6767 if (fs_state != FULLSCREEN_MAXIMIZED
6768 && fs_state != FULLSCREEN_WIDTH)
6770 ns_userRect.size.width = result.size.width;
6771 ns_userRect.origin.x = result.origin.x;
6774 if (fs_state != FULLSCREEN_MAXIMIZED
6775 && fs_state != FULLSCREEN_HEIGHT)
6777 ns_userRect.size.height = result.size.height;
6778 ns_userRect.origin.y = result.origin.y;
6781 NSTRACE_RECT ("ns_userRect (2)", ns_userRect);
6783 if (next_maximized == FULLSCREEN_HEIGHT
6784 || (next_maximized == -1
6785 && abs ((int)(defaultFrame.size.height - result.size.height))
6786 > FRAME_LINE_HEIGHT (emacsframe)))
6789 NSTRACE_MSG ("FULLSCREEN_HEIGHT");
6790 maximized_height = result.size.height = defaultFrame.size.height;
6791 maximized_width = -1;
6792 result.origin.y = defaultFrame.origin.y;
6793 if (ns_userRect.size.height != 0)
6795 result.origin.x = ns_userRect.origin.x;
6796 result.size.width = ns_userRect.size.width;
6798 [self setFSValue: FULLSCREEN_HEIGHT];
6799 #ifdef NS_IMPL_COCOA
6800 maximizing_resize = YES;
6803 else if (next_maximized == FULLSCREEN_WIDTH)
6805 NSTRACE_MSG ("FULLSCREEN_WIDTH");
6806 maximized_width = result.size.width = defaultFrame.size.width;
6807 maximized_height = -1;
6808 result.origin.x = defaultFrame.origin.x;
6809 if (ns_userRect.size.width != 0)
6811 result.origin.y = ns_userRect.origin.y;
6812 result.size.height = ns_userRect.size.height;
6814 [self setFSValue: FULLSCREEN_WIDTH];
6816 else if (next_maximized == FULLSCREEN_MAXIMIZED
6817 || (next_maximized == -1
6818 && abs ((int)(defaultFrame.size.width - result.size.width))
6819 > FRAME_COLUMN_WIDTH (emacsframe)))
6821 NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
6823 result = defaultFrame; /* second click */
6824 maximized_width = result.size.width;
6825 maximized_height = result.size.height;
6826 [self setFSValue: FULLSCREEN_MAXIMIZED];
6827 #ifdef NS_IMPL_COCOA
6828 maximizing_resize = YES;
6834 NSTRACE_MSG ("Restore");
6835 result = ns_userRect.size.height ? ns_userRect : result;
6836 NSTRACE_RECT ("restore (2)", result);
6837 ns_userRect = NSMakeRect (0, 0, 0, 0);
6838 #ifdef NS_IMPL_COCOA
6839 maximizing_resize = fs_state != FULLSCREEN_NONE;
6841 [self setFSValue: FULLSCREEN_NONE];
6842 maximized_width = maximized_height = -1;
6846 if (fs_before_fs == -1) next_maximized = -1;
6848 NSTRACE_RECT ("Final ns_userRect", ns_userRect);
6849 NSTRACE_MSG ("Final maximized_width: %d", maximized_width);
6850 NSTRACE_MSG ("Final maximized_height: %d", maximized_height);
6851 NSTRACE_FSTYPE ("Final next_maximized", next_maximized);
6853 [self windowWillResize: sender toSize: result.size];
6855 NSTRACE_RETURN_RECT (result);
6861 - (void)windowDidDeminiaturize: sender
6863 NSTRACE ("[EmacsView windowDidDeminiaturize:]");
6864 if (!emacsframe->output_data.ns)
6867 SET_FRAME_ICONIFIED (emacsframe, 0);
6868 SET_FRAME_VISIBLE (emacsframe, 1);
6869 windows_or_buffers_changed = 63;
6873 emacs_event->kind = DEICONIFY_EVENT;
6874 EV_TRAILER ((id)nil);
6879 - (void)windowDidExpose: sender
6881 NSTRACE ("[EmacsView windowDidExpose:]");
6882 if (!emacsframe->output_data.ns)
6885 SET_FRAME_VISIBLE (emacsframe, 1);
6886 SET_FRAME_GARBAGED (emacsframe);
6888 if (send_appdefined)
6889 ns_send_appdefined (-1);
6893 - (void)windowDidMiniaturize: sender
6895 NSTRACE ("[EmacsView windowDidMiniaturize:]");
6896 if (!emacsframe->output_data.ns)
6899 SET_FRAME_ICONIFIED (emacsframe, 1);
6900 SET_FRAME_VISIBLE (emacsframe, 0);
6904 emacs_event->kind = ICONIFY_EVENT;
6905 EV_TRAILER ((id)nil);
6909 #ifdef HAVE_NATIVE_FS
6910 - (NSApplicationPresentationOptions)window:(NSWindow *)window
6911 willUseFullScreenPresentationOptions:
6912 (NSApplicationPresentationOptions)proposedOptions
6914 return proposedOptions|NSApplicationPresentationAutoHideToolbar;
6918 - (void)windowWillEnterFullScreen:(NSNotification *)notification
6920 NSTRACE ("[EmacsView windowWillEnterFullScreen:]");
6921 [self windowWillEnterFullScreen];
6923 - (void)windowWillEnterFullScreen /* provided for direct calls */
6925 NSTRACE ("[EmacsView windowWillEnterFullScreen]");
6926 fs_before_fs = fs_state;
6929 - (void)windowDidEnterFullScreen:(NSNotification *)notification
6931 NSTRACE ("[EmacsView windowDidEnterFullScreen:]");
6932 [self windowDidEnterFullScreen];
6935 - (void)windowDidEnterFullScreen /* provided for direct calls */
6937 NSTRACE ("[EmacsView windowDidEnterFullScreen]");
6938 [self setFSValue: FULLSCREEN_BOTH];
6939 if (! [self fsIsNative])
6941 [self windowDidBecomeKey];
6942 [nonfs_window orderOut:self];
6946 BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (emacsframe) ? YES : NO;
6947 #ifdef NS_IMPL_COCOA
6948 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6949 unsigned val = (unsigned)[NSApp presentationOptions];
6951 // OSX 10.7 bug fix, the menu won't appear without this.
6952 // val is non-zero on other OSX versions.
6955 NSApplicationPresentationOptions options
6956 = NSApplicationPresentationAutoHideDock
6957 | NSApplicationPresentationAutoHideMenuBar
6958 | NSApplicationPresentationFullScreen
6959 | NSApplicationPresentationAutoHideToolbar;
6961 [NSApp setPresentationOptions: options];
6965 [toolbar setVisible:tbar_visible];
6969 - (void)windowWillExitFullScreen:(NSNotification *)notification
6971 NSTRACE ("[EmacsView windowWillExitFullScreen:]");
6972 [self windowWillExitFullScreen];
6975 - (void)windowWillExitFullScreen /* provided for direct calls */
6977 NSTRACE ("[EmacsView windowWillExitFullScreen]");
6978 if (!FRAME_LIVE_P (emacsframe))
6980 NSTRACE_MSG ("Ignored (frame dead)");
6983 if (next_maximized != -1)
6984 fs_before_fs = next_maximized;
6987 - (void)windowDidExitFullScreen:(NSNotification *)notification
6989 NSTRACE ("[EmacsView windowDidExitFullScreen:]");
6990 [self windowDidExitFullScreen];
6993 - (void)windowDidExitFullScreen /* provided for direct calls */
6995 NSTRACE ("[EamcsView windowDidExitFullScreen]");
6996 if (!FRAME_LIVE_P (emacsframe))
6998 NSTRACE_MSG ("Ignored (frame dead)");
7001 [self setFSValue: fs_before_fs];
7003 #ifdef HAVE_NATIVE_FS
7004 [self updateCollectionBehavior];
7006 if (FRAME_EXTERNAL_TOOL_BAR (emacsframe))
7008 [toolbar setVisible:YES];
7009 update_frame_tool_bar (emacsframe);
7010 [self updateFrameSize:YES];
7011 [[self window] display];
7014 [toolbar setVisible:NO];
7016 if (next_maximized != -1)
7017 [[self window] performZoom:self];
7022 return fs_is_native;
7025 - (BOOL)isFullscreen
7027 NSTRACE ("[EmacsView isFullscreen]");
7029 if (! fs_is_native) return nonfs_window != nil;
7030 #ifdef HAVE_NATIVE_FS
7031 return ([[self window] styleMask] & NSFullScreenWindowMask) != 0;
7037 #ifdef HAVE_NATIVE_FS
7038 - (void)updateCollectionBehavior
7040 NSTRACE ("[EmacsView updateCollectionBehavior]");
7042 if (! [self isFullscreen])
7044 NSWindow *win = [self window];
7045 NSWindowCollectionBehavior b = [win collectionBehavior];
7046 if (ns_use_native_fullscreen)
7047 b |= NSWindowCollectionBehaviorFullScreenPrimary;
7049 b &= ~NSWindowCollectionBehaviorFullScreenPrimary;
7051 [win setCollectionBehavior: b];
7052 fs_is_native = ns_use_native_fullscreen;
7057 - (void)toggleFullScreen: (id)sender
7065 NSTRACE ("[EmacsView toggleFullScreen:]");
7069 #ifdef HAVE_NATIVE_FS
7070 [[self window] toggleFullScreen:sender];
7076 onFirstScreen = [[w screen] isEqual:[[NSScreen screens] objectAtIndex:0]];
7079 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
7080 (FRAME_DEFAULT_FACE (f)),
7083 if (fs_state != FULLSCREEN_BOTH)
7085 NSScreen *screen = [w screen];
7087 #if defined (NS_IMPL_COCOA) && \
7088 MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7089 /* Hide ghost menu bar on secondary monitor? */
7090 if (! onFirstScreen)
7091 onFirstScreen = [NSScreen screensHaveSeparateSpaces];
7093 /* Hide dock and menubar if we are on the primary screen. */
7096 #ifdef NS_IMPL_COCOA
7097 NSApplicationPresentationOptions options
7098 = NSApplicationPresentationAutoHideDock
7099 | NSApplicationPresentationAutoHideMenuBar;
7101 [NSApp setPresentationOptions: options];
7103 [NSMenu setMenuBarVisible:NO];
7107 fw = [[EmacsFSWindow alloc]
7108 initWithContentRect:[w contentRectForFrameRect:wr]
7109 styleMask:NSBorderlessWindowMask
7110 backing:NSBackingStoreBuffered
7114 [fw setContentView:[w contentView]];
7115 [fw setTitle:[w title]];
7116 [fw setDelegate:self];
7117 [fw setAcceptsMouseMovedEvents: YES];
7118 #if !defined (NS_IMPL_COCOA) || \
7119 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
7120 [fw useOptimizedDrawing: YES];
7122 [fw setBackgroundColor: col];
7123 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
7126 f->border_width = 0;
7127 FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
7128 tobar_height = FRAME_TOOLBAR_HEIGHT (f);
7129 FRAME_TOOLBAR_HEIGHT (f) = 0;
7133 [self windowWillEnterFullScreen];
7134 [fw makeKeyAndOrderFront:NSApp];
7135 [fw makeFirstResponder:self];
7137 r = [fw frameRectForContentRect:[screen frame]];
7138 [fw setFrame: r display:YES animate:ns_use_fullscreen_animation];
7139 [self windowDidEnterFullScreen];
7150 #ifdef NS_IMPL_COCOA
7151 [NSApp setPresentationOptions: NSApplicationPresentationDefault];
7153 [NSMenu setMenuBarVisible:YES];
7157 [w setContentView:[fw contentView]];
7158 [w setBackgroundColor: col];
7159 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
7162 f->border_width = bwidth;
7163 FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
7164 if (FRAME_EXTERNAL_TOOL_BAR (f))
7165 FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
7167 // to do: consider using [NSNotificationCenter postNotificationName:] to send notifications.
7169 [self windowWillExitFullScreen];
7170 [fw setFrame: [w frame] display:YES animate:ns_use_fullscreen_animation];
7172 [w makeKeyAndOrderFront:NSApp];
7173 [self windowDidExitFullScreen];
7174 [self updateFrameSize:YES];
7180 NSTRACE ("[EmacsView handleFS]");
7182 if (fs_state != emacsframe->want_fullscreen)
7184 if (fs_state == FULLSCREEN_BOTH)
7186 NSTRACE_MSG ("fs_state == FULLSCREEN_BOTH");
7187 [self toggleFullScreen:self];
7190 switch (emacsframe->want_fullscreen)
7192 case FULLSCREEN_BOTH:
7193 NSTRACE_MSG ("FULLSCREEN_BOTH");
7194 [self toggleFullScreen:self];
7196 case FULLSCREEN_WIDTH:
7197 NSTRACE_MSG ("FULLSCREEN_WIDTH");
7198 next_maximized = FULLSCREEN_WIDTH;
7199 if (fs_state != FULLSCREEN_BOTH)
7200 [[self window] performZoom:self];
7202 case FULLSCREEN_HEIGHT:
7203 NSTRACE_MSG ("FULLSCREEN_HEIGHT");
7204 next_maximized = FULLSCREEN_HEIGHT;
7205 if (fs_state != FULLSCREEN_BOTH)
7206 [[self window] performZoom:self];
7208 case FULLSCREEN_MAXIMIZED:
7209 NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
7210 next_maximized = FULLSCREEN_MAXIMIZED;
7211 if (fs_state != FULLSCREEN_BOTH)
7212 [[self window] performZoom:self];
7214 case FULLSCREEN_NONE:
7215 NSTRACE_MSG ("FULLSCREEN_NONE");
7216 if (fs_state != FULLSCREEN_BOTH)
7218 next_maximized = FULLSCREEN_NONE;
7219 [[self window] performZoom:self];
7224 emacsframe->want_fullscreen = FULLSCREEN_NONE;
7229 - (void) setFSValue: (int)value
7231 NSTRACE ("[EmacsView setFSValue:" NSTRACE_FMT_FSTYPE "]",
7232 NSTRACE_ARG_FSTYPE(value));
7234 Lisp_Object lval = Qnil;
7237 case FULLSCREEN_BOTH:
7240 case FULLSCREEN_WIDTH:
7243 case FULLSCREEN_HEIGHT:
7246 case FULLSCREEN_MAXIMIZED:
7250 store_frame_param (emacsframe, Qfullscreen, lval);
7254 - (void)mouseEntered: (NSEvent *)theEvent
7256 NSTRACE ("[EmacsView mouseEntered:]");
7258 FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7259 = EV_TIMESTAMP (theEvent);
7263 - (void)mouseExited: (NSEvent *)theEvent
7265 Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
7267 NSTRACE ("[EmacsView mouseExited:]");
7272 FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7273 = EV_TIMESTAMP (theEvent);
7275 if (emacsframe == hlinfo->mouse_face_mouse_frame)
7277 clear_mouse_face (hlinfo);
7278 hlinfo->mouse_face_mouse_frame = 0;
7285 NSTRACE ("[EmacsView menuDown:]");
7286 if (context_menu_value == -1)
7287 context_menu_value = [sender tag];
7290 NSInteger tag = [sender tag];
7291 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
7292 emacsframe->menu_bar_vector,
7296 ns_send_appdefined (-1);
7301 - (EmacsToolbar *)toolbar
7307 /* this gets called on toolbar button click */
7308 - toolbarClicked: (id)item
7311 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
7313 NSTRACE ("[EmacsView toolbarClicked:]");
7318 /* send first event (for some reason two needed) */
7319 theEvent = [[self window] currentEvent];
7320 emacs_event->kind = TOOL_BAR_EVENT;
7321 XSETFRAME (emacs_event->arg, emacsframe);
7322 EV_TRAILER (theEvent);
7324 emacs_event->kind = TOOL_BAR_EVENT;
7325 /* XSETINT (emacs_event->code, 0); */
7326 emacs_event->arg = AREF (emacsframe->tool_bar_items,
7327 idx + TOOL_BAR_ITEM_KEY);
7328 emacs_event->modifiers = EV_MODIFIERS (theEvent);
7329 EV_TRAILER (theEvent);
7334 - toggleToolbar: (id)sender
7336 NSTRACE ("[EmacsView toggleToolbar:]");
7341 emacs_event->kind = NS_NONKEY_EVENT;
7342 emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
7343 EV_TRAILER ((id)nil);
7348 - (void)drawRect: (NSRect)rect
7350 int x = NSMinX (rect), y = NSMinY (rect);
7351 int width = NSWidth (rect), height = NSHeight (rect);
7353 NSTRACE ("[EmacsView drawRect:" NSTRACE_FMT_RECT "]",
7354 NSTRACE_ARG_RECT(rect));
7356 if (!emacsframe || !emacsframe->output_data.ns)
7359 ns_clear_frame_area (emacsframe, x, y, width, height);
7361 expose_frame (emacsframe, x, y, width, height);
7365 drawRect: may be called (at least in OS X 10.5) for invisible
7366 views as well for some reason. Thus, do not infer visibility
7369 emacsframe->async_visible = 1;
7370 emacsframe->async_iconified = 0;
7375 /* NSDraggingDestination protocol methods. Actually this is not really a
7376 protocol, but a category of Object. O well... */
7378 -(NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
7380 NSTRACE ("[EmacsView draggingEntered:]");
7381 return NSDragOperationGeneric;
7385 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
7391 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
7396 NSEvent *theEvent = [[self window] currentEvent];
7398 NSDragOperation op = [sender draggingSourceOperationMask];
7401 NSTRACE ("[EmacsView performDragOperation:]");
7406 position = [self convertPoint: [sender draggingLocation] fromView: nil];
7407 x = lrint (position.x); y = lrint (position.y);
7409 pb = [sender draggingPasteboard];
7410 type = [pb availableTypeFromArray: ns_drag_types];
7412 if (! (op & (NSDragOperationMove|NSDragOperationDelete)) &&
7413 // URL drags contain all operations (0xf), don't allow all to be set.
7416 if (op & NSDragOperationLink)
7417 modifiers |= NSControlKeyMask;
7418 if (op & NSDragOperationCopy)
7419 modifiers |= NSAlternateKeyMask;
7420 if (op & NSDragOperationGeneric)
7421 modifiers |= NSCommandKeyMask;
7424 modifiers = EV_MODIFIERS2 (modifiers);
7429 else if ([type isEqualToString: NSFilenamesPboardType])
7432 NSEnumerator *fenum;
7435 if (!(files = [pb propertyListForType: type]))
7438 fenum = [files objectEnumerator];
7439 while ( (file = [fenum nextObject]) )
7441 emacs_event->kind = DRAG_N_DROP_EVENT;
7442 XSETINT (emacs_event->x, x);
7443 XSETINT (emacs_event->y, y);
7444 ns_input_file = append2 (ns_input_file,
7445 build_string ([file UTF8String]));
7446 emacs_event->modifiers = modifiers;
7447 emacs_event->arg = list2 (Qfile, build_string ([file UTF8String]));
7448 EV_TRAILER (theEvent);
7452 else if ([type isEqualToString: NSURLPboardType])
7454 NSURL *url = [NSURL URLFromPasteboard: pb];
7455 if (url == nil) return NO;
7457 emacs_event->kind = DRAG_N_DROP_EVENT;
7458 XSETINT (emacs_event->x, x);
7459 XSETINT (emacs_event->y, y);
7460 emacs_event->modifiers = modifiers;
7461 emacs_event->arg = list2 (Qurl,
7462 build_string ([[url absoluteString]
7464 EV_TRAILER (theEvent);
7466 if ([url isFileURL] != NO)
7468 NSString *file = [url path];
7469 ns_input_file = append2 (ns_input_file,
7470 build_string ([file UTF8String]));
7474 else if ([type isEqualToString: NSStringPboardType]
7475 || [type isEqualToString: NSTabularTextPboardType])
7479 if (! (data = [pb stringForType: type]))
7482 emacs_event->kind = DRAG_N_DROP_EVENT;
7483 XSETINT (emacs_event->x, x);
7484 XSETINT (emacs_event->y, y);
7485 emacs_event->modifiers = modifiers;
7486 emacs_event->arg = list2 (Qnil, build_string ([data UTF8String]));
7487 EV_TRAILER (theEvent);
7492 fprintf (stderr, "Invalid data type in dragging pasteboard");
7498 - (id) validRequestorForSendType: (NSString *)typeSent
7499 returnType: (NSString *)typeReturned
7501 NSTRACE ("[EmacsView validRequestorForSendType:returnType:]");
7502 if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
7503 && typeReturned == nil)
7505 if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
7509 return [super validRequestorForSendType: typeSent
7510 returnType: typeReturned];
7514 /* The next two methods are part of NSServicesRequests informal protocol,
7515 supposedly called when a services menu item is chosen from this app.
7516 But this should not happen because we override the services menu with our
7517 own entries which call ns-perform-service.
7518 Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
7519 So let's at least stub them out until further investigation can be done. */
7521 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
7523 /* we could call ns_string_from_pasteboard(pboard) here but then it should
7524 be written into the buffer in place of the existing selection..
7525 ordinary service calls go through functions defined in ns-win.el */
7529 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
7531 NSArray *typesDeclared;
7534 NSTRACE ("[EmacsView writeSelectionToPasteboard:types:]");
7536 /* We only support NSStringPboardType */
7537 if ([types containsObject:NSStringPboardType] == NO) {
7541 val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7542 if (CONSP (val) && SYMBOLP (XCAR (val)))
7545 if (CONSP (val) && NILP (XCDR (val)))
7548 if (! STRINGP (val))
7551 typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
7552 [pb declareTypes:typesDeclared owner:nil];
7553 ns_string_to_pasteboard (pb, val);
7558 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
7559 (gives a miniaturized version of the window); currently we use the latter for
7560 frames whose active buffer doesn't correspond to any file
7561 (e.g., '*scratch*') */
7562 - setMiniwindowImage: (BOOL) setMini
7564 id image = [[self window] miniwindowImage];
7565 NSTRACE ("[EmacsView setMiniwindowImage:%d]", setMini);
7567 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
7568 about "AppleDockIconEnabled" notwithstanding, however the set message
7569 below has its effect nonetheless. */
7570 if (image != emacsframe->output_data.ns->miniimage)
7572 if (image && [image isKindOfClass: [EmacsImage class]])
7574 [[self window] setMiniwindowImage:
7575 setMini ? emacsframe->output_data.ns->miniimage : nil];
7582 - (void) setRows: (int) r andColumns: (int) c
7584 NSTRACE ("[EmacsView setRows:%d andColumns:%d]", r, c);
7589 - (int) fullscreenState
7594 @end /* EmacsView */
7598 /* ==========================================================================
7600 EmacsWindow implementation
7602 ========================================================================== */
7604 @implementation EmacsWindow
7606 #ifdef NS_IMPL_COCOA
7607 - (id)accessibilityAttributeValue:(NSString *)attribute
7609 Lisp_Object str = Qnil;
7610 struct frame *f = SELECTED_FRAME ();
7611 struct buffer *curbuf = XBUFFER (XWINDOW (f->selected_window)->contents);
7613 NSTRACE ("[EmacsWindow accessibilityAttributeValue:]");
7615 if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
7616 return NSAccessibilityTextFieldRole;
7618 if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]
7619 && curbuf && ! NILP (BVAR (curbuf, mark_active)))
7621 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7623 else if (curbuf && [attribute isEqualToString:NSAccessibilityValueAttribute])
7625 if (! NILP (BVAR (curbuf, mark_active)))
7626 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7630 ptrdiff_t start_byte = BUF_BEGV_BYTE (curbuf);
7631 ptrdiff_t byte_range = BUF_ZV_BYTE (curbuf) - start_byte;
7632 ptrdiff_t range = BUF_ZV (curbuf) - BUF_BEGV (curbuf);
7634 if (! NILP (BVAR (curbuf, enable_multibyte_characters)))
7635 str = make_uninit_multibyte_string (range, byte_range);
7637 str = make_uninit_string (range);
7638 /* To check: This returns emacs-utf-8, which is a superset of utf-8.
7639 Is this a problem? */
7640 memcpy (SDATA (str), BYTE_POS_ADDR (start_byte), byte_range);
7647 if (CONSP (str) && SYMBOLP (XCAR (str)))
7650 if (CONSP (str) && NILP (XCDR (str)))
7655 const char *utfStr = SSDATA (str);
7656 NSString *nsStr = [NSString stringWithUTF8String: utfStr];
7661 return [super accessibilityAttributeValue:attribute];
7663 #endif /* NS_IMPL_COCOA */
7665 /* Constrain size and placement of a frame.
7667 By returning the original "frameRect", the frame is not
7668 constrained. This can lead to unwanted situations where, for
7669 example, the menu bar covers the frame.
7671 The default implementation (accessed using "super") constrains the
7672 frame to the visible area of SCREEN, minus the menu bar (if
7673 present) and the Dock. Note that default implementation also calls
7674 windowWillResize, with the frame it thinks should have. (This can
7675 make the frame exit maximized mode.)
7677 Note that this should work in situations where multiple monitors
7678 are present. Common configurations are side-by-side monitors and a
7679 monitor on top of another (e.g. when a laptop is placed under a
7681 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
7683 NSTRACE ("[EmacsWindow constrainFrameRect:" NSTRACE_FMT_RECT " toScreen:]",
7684 NSTRACE_ARG_RECT (frameRect));
7686 #ifdef NS_IMPL_COCOA
7687 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7688 // If separate spaces is on, it is like each screen is independent. There is
7689 // no spanning of frames across screens.
7690 if ([NSScreen screensHaveSeparateSpaces])
7692 NSTRACE_MSG ("Screens have separate spaces");
7693 frameRect = [super constrainFrameRect:frameRect toScreen:screen];
7694 NSTRACE_RETURN_RECT (frameRect);
7700 return constrain_frame_rect(frameRect);
7704 - (void)performZoom:(id)sender
7706 NSTRACE ("[EmacsWindow performZoom:]");
7708 return [super performZoom:sender];
7711 - (void)zoom:(id)sender
7713 struct frame * f = SELECTED_FRAME ();
7715 NSTRACE ("[EmacsWindow zoom:]");
7717 ns_update_auto_hide_menu_bar();
7719 // Below are three zoom implementations. In the final commit, the
7720 // idea is that the last should be included.
7723 // Native zoom done using the standard zoom animation. Size of the
7724 // resulting frame reduced to accommodate the Dock and, if present,
7726 [super zoom:sender];
7729 // Native zoom done using the standard zoom animation, plus an
7730 // explicit resize to cover the full screen.
7731 [super zoom:sender];
7733 // After the native zoom, resize the resulting frame to fill the
7734 // entire screen, except the menu-bar.
7736 // This works for all practical purposes. (The only minor oddity is
7737 // when transiting from full-height frame to a maximized, the
7738 // animation reduces the height of the frame slightly (to the 4
7739 // pixels needed to accommodate the Doc) before it snaps back into
7740 // full height. The user would need a very trained eye to spot
7742 NSScreen * screen = [self screen];
7745 int fs_state = [(EmacsView *)[self delegate] fullscreenState];
7747 NSTRACE_FSTYPE ("fullscreenState", fs_state);
7749 NSRect sr = [screen frame];
7750 NSRect wr = [self frame];
7751 NSTRACE_RECT ("Rect after zoom", wr);
7755 if (fs_state == FULLSCREEN_MAXIMIZED
7756 || fs_state == FULLSCREEN_HEIGHT)
7759 newWr.size.height = sr.size.height - ns_menu_bar_height(screen);
7762 if (fs_state == FULLSCREEN_MAXIMIZED
7763 || fs_state == FULLSCREEN_WIDTH)
7766 newWr.size.width = sr.size.width;
7769 if (newWr.size.width != wr.size.width
7770 || newWr.size.height != wr.size.height
7771 || newWr.origin.x != wr.origin.x
7772 || newWr.origin.y != wr.origin.y)
7774 NSTRACE_MSG ("New frame different");
7775 [self setFrame: newWr display: NO];
7779 // Non-native zoom which is done instantaneously. The resulting frame
7780 // covers the entire screen, except the menu-bar, if present.
7781 NSScreen * screen = [self screen];
7784 NSRect sr = [screen frame];
7785 sr.size.height -= ns_menu_bar_height (screen);
7787 sr = [[self delegate] windowWillUseStandardFrame:self
7789 [self setFrame: sr display: NO];
7794 - (void)setFrame:(NSRect)windowFrame
7795 display:(BOOL)displayViews
7797 NSTRACE ("[EmacsWindow setFrame:" NSTRACE_FMT_RECT " display:%d]",
7798 NSTRACE_ARG_RECT (windowFrame), displayViews);
7800 [super setFrame:windowFrame display:displayViews];
7803 - (void)setFrame:(NSRect)windowFrame
7804 display:(BOOL)displayViews
7805 animate:(BOOL)performAnimation
7807 NSTRACE ("[EmacsWindow setFrame:" NSTRACE_FMT_RECT
7808 " display:%d performAnimation:%d]",
7809 NSTRACE_ARG_RECT (windowFrame), displayViews, performAnimation);
7811 [super setFrame:windowFrame display:displayViews animate:performAnimation];
7814 - (void)setFrameTopLeftPoint:(NSPoint)point
7816 NSTRACE ("[EmacsWindow setFrameTopLeftPoint:" NSTRACE_FMT_POINT "]",
7817 NSTRACE_ARG_POINT (point));
7819 [super setFrameTopLeftPoint:point];
7821 @end /* EmacsWindow */
7824 @implementation EmacsFSWindow
7826 - (BOOL)canBecomeKeyWindow
7831 - (BOOL)canBecomeMainWindow
7838 /* ==========================================================================
7840 EmacsScroller implementation
7842 ========================================================================== */
7845 @implementation EmacsScroller
7847 /* for repeat button push */
7848 #define SCROLL_BAR_FIRST_DELAY 0.5
7849 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
7851 + (CGFloat) scrollerWidth
7853 /* TODO: if we want to allow variable widths, this is the place to do it,
7854 however neither GNUstep nor Cocoa support it very well */
7856 #if !defined (NS_IMPL_COCOA) || \
7857 MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
7858 r = [NSScroller scrollerWidth];
7860 r = [NSScroller scrollerWidthForControlSize: NSRegularControlSize
7861 scrollerStyle: NSScrollerStyleLegacy];
7867 - initFrame: (NSRect )r window: (Lisp_Object)nwin
7869 NSTRACE ("[EmacsScroller initFrame: window:]");
7871 r.size.width = [EmacsScroller scrollerWidth];
7872 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
7873 [self setContinuous: YES];
7874 [self setEnabled: YES];
7876 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
7877 locked against the top and bottom edges, and right edge on OS X, where
7878 scrollers are on right. */
7879 #ifdef NS_IMPL_GNUSTEP
7880 [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
7882 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
7885 window = XWINDOW (nwin);
7887 pixel_height = NSHeight (r);
7888 if (pixel_height == 0) pixel_height = 1;
7889 min_portion = 20 / pixel_height;
7891 frame = XFRAME (window->frame);
7892 if (FRAME_LIVE_P (frame))
7895 EmacsView *view = FRAME_NS_VIEW (frame);
7896 NSView *sview = [[view window] contentView];
7897 NSArray *subs = [sview subviews];
7899 /* disable optimization stopping redraw of other scrollbars */
7900 view->scrollbarsNeedingUpdate = 0;
7901 for (i =[subs count]-1; i >= 0; i--)
7902 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
7903 view->scrollbarsNeedingUpdate++;
7904 [sview addSubview: self];
7907 /* [self setFrame: r]; */
7913 - (void)setFrame: (NSRect)newRect
7915 NSTRACE ("[EmacsScroller setFrame:]");
7917 /* block_input (); */
7918 pixel_height = NSHeight (newRect);
7919 if (pixel_height == 0) pixel_height = 1;
7920 min_portion = 20 / pixel_height;
7921 [super setFrame: newRect];
7922 /* unblock_input (); */
7928 NSTRACE ("[EmacsScroller dealloc]");
7930 wset_vertical_scroll_bar (window, Qnil);
7938 NSTRACE ("[EmacsScroller condemn]");
7946 NSTRACE ("[EmacsScroller reprieve]");
7954 NSTRACE ("[EmacsScroller judge]");
7955 bool ret = condemned;
7960 /* ensure other scrollbar updates after deletion */
7961 view = (EmacsView *)FRAME_NS_VIEW (frame);
7963 view->scrollbarsNeedingUpdate++;
7965 wset_vertical_scroll_bar (window, Qnil);
7967 [self removeFromSuperview];
7975 - (void)resetCursorRects
7977 NSRect visible = [self visibleRect];
7978 NSTRACE ("[EmacsScroller resetCursorRects]");
7980 if (!NSIsEmptyRect (visible))
7981 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
7982 [[NSCursor arrowCursor] setOnMouseEntered: YES];
7986 - (int) checkSamePosition: (int) position portion: (int) portion
7989 return em_position ==position && em_portion ==portion && em_whole ==whole
7990 && portion != whole; /* needed for resize empty buf */
7994 - setPosition: (int)position portion: (int)portion whole: (int)whole
7996 NSTRACE ("[EmacsScroller setPosition:portion:whole:]");
7998 em_position = position;
7999 em_portion = portion;
8002 if (portion >= whole)
8004 #ifdef NS_IMPL_COCOA
8005 [self setKnobProportion: 1.0];
8006 [self setDoubleValue: 1.0];
8008 [self setFloatValue: 0.0 knobProportion: 1.0];
8015 portion = max ((float)whole*min_portion/pixel_height, portion);
8016 pos = (float)position / (whole - portion);
8017 por = (CGFloat)portion/whole;
8018 #ifdef NS_IMPL_COCOA
8019 [self setKnobProportion: por];
8020 [self setDoubleValue: pos];
8022 [self setFloatValue: pos knobProportion: por];
8029 /* set up emacs_event */
8030 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
8034 NSTRACE ("[EmacsScroller sendScrollEventAtLoc:fromEvent:]");
8039 emacs_event->part = last_hit_part;
8040 emacs_event->code = 0;
8041 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
8042 XSETWINDOW (win, window);
8043 emacs_event->frame_or_window = win;
8044 emacs_event->timestamp = EV_TIMESTAMP (e);
8045 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
8046 emacs_event->arg = Qnil;
8047 XSETINT (emacs_event->x, loc * pixel_height);
8048 XSETINT (emacs_event->y, pixel_height-20);
8052 n_emacs_events_pending++;
8053 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
8056 hold_event (emacs_event);
8057 EVENT_INIT (*emacs_event);
8058 ns_send_appdefined (-1);
8062 /* called manually thru timer to implement repeated button action w/hold-down */
8063 - repeatScroll: (NSTimer *)scrollEntry
8065 NSEvent *e = [[self window] currentEvent];
8066 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
8067 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
8069 NSTRACE ("[EmacsScroller repeatScroll:]");
8071 /* clear timer if need be */
8072 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
8074 [scroll_repeat_entry invalidate];
8075 [scroll_repeat_entry release];
8076 scroll_repeat_entry = nil;
8082 = [[NSTimer scheduledTimerWithTimeInterval:
8083 SCROLL_BAR_CONTINUOUS_DELAY
8085 selector: @selector (repeatScroll:)
8091 [self sendScrollEventAtLoc: 0 fromEvent: e];
8096 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
8097 mouseDragged events without going into a modal loop. */
8098 - (void)mouseDown: (NSEvent *)e
8101 /* hitPart is only updated AFTER event is passed on */
8102 NSScrollerPart part = [self testPart: [e locationInWindow]];
8103 CGFloat inc = 0.0, loc, kloc, pos;
8106 NSTRACE ("[EmacsScroller mouseDown:]");
8110 case NSScrollerDecrementPage:
8111 last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
8112 case NSScrollerIncrementPage:
8113 last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
8114 case NSScrollerDecrementLine:
8115 last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
8116 case NSScrollerIncrementLine:
8117 last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
8118 case NSScrollerKnob:
8119 last_hit_part = scroll_bar_handle; break;
8120 case NSScrollerKnobSlot: /* GNUstep-only */
8121 last_hit_part = scroll_bar_move_ratio; break;
8122 default: /* NSScrollerNoPart? */
8123 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
8130 pos = 0; /* ignored */
8132 /* set a timer to repeat, as we can't let superclass do this modally */
8134 = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
8136 selector: @selector (repeatScroll:)
8143 /* handle, or on GNUstep possibly slot */
8144 NSEvent *fake_event;
8146 /* compute float loc in slot and mouse offset on knob */
8147 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
8149 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
8155 else if (loc >= NSHeight (sr))
8157 loc = NSHeight (sr);
8165 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
8167 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
8169 last_mouse_offset = kloc;
8171 /* if knob, tell emacs a location offset by knob pos
8172 (to indicate top of handle) */
8173 if (part == NSScrollerKnob)
8174 pos = (loc - last_mouse_offset) / NSHeight (sr);
8176 /* else this is a slot click on GNUstep: go straight there */
8177 pos = loc / NSHeight (sr);
8179 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
8180 fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
8181 location: [e locationInWindow]
8182 modifierFlags: [e modifierFlags]
8183 timestamp: [e timestamp]
8184 windowNumber: [e windowNumber]
8185 context: [e context]
8186 eventNumber: [e eventNumber]
8187 clickCount: [e clickCount]
8188 pressure: [e pressure]];
8189 [super mouseUp: fake_event];
8192 if (part != NSScrollerKnob)
8193 [self sendScrollEventAtLoc: pos fromEvent: e];
8197 /* Called as we manually track scroller drags, rather than superclass. */
8198 - (void)mouseDragged: (NSEvent *)e
8203 NSTRACE ("[EmacsScroller mouseDragged:]");
8205 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
8207 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
8213 else if (loc >= NSHeight (sr) + last_mouse_offset)
8215 loc = NSHeight (sr) + last_mouse_offset;
8218 pos = (loc - last_mouse_offset) / NSHeight (sr);
8219 [self sendScrollEventAtLoc: pos fromEvent: e];
8223 - (void)mouseUp: (NSEvent *)e
8225 NSTRACE ("[EmacsScroller mouseUp:]");
8227 if (scroll_repeat_entry)
8229 [scroll_repeat_entry invalidate];
8230 [scroll_repeat_entry release];
8231 scroll_repeat_entry = nil;
8233 last_hit_part = scroll_bar_above_handle;
8237 /* treat scrollwheel events in the bar as though they were in the main window */
8238 - (void) scrollWheel: (NSEvent *)theEvent
8240 NSTRACE ("[EmacsScroller scrollWheel:]");
8242 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
8243 [view mouseDown: theEvent];
8246 @end /* EmacsScroller */
8249 #ifdef NS_IMPL_GNUSTEP
8250 /* Dummy class to get rid of startup warnings. */
8251 @implementation EmacsDocument
8257 /* ==========================================================================
8259 Font-related functions; these used to be in nsfaces.m
8261 ========================================================================== */
8265 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
8267 struct font *font = XFONT_OBJECT (font_object);
8268 EmacsView *view = FRAME_NS_VIEW (f);
8269 int font_ascent, font_descent;
8272 fontset = fontset_from_font (font_object);
8273 FRAME_FONTSET (f) = fontset;
8275 if (FRAME_FONT (f) == font)
8276 /* This font is already set in frame F. There's nothing more to
8280 FRAME_FONT (f) = font;
8282 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
8283 FRAME_COLUMN_WIDTH (f) = font->average_width;
8284 get_font_ascent_descent (font, &font_ascent, &font_descent);
8285 FRAME_LINE_HEIGHT (f) = font_ascent + font_descent;
8287 /* Compute the scroll bar width in character columns. */
8288 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
8290 int wid = FRAME_COLUMN_WIDTH (f);
8291 FRAME_CONFIG_SCROLL_BAR_COLS (f)
8292 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
8296 int wid = FRAME_COLUMN_WIDTH (f);
8297 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
8300 /* Compute the scroll bar height in character lines. */
8301 if (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) > 0)
8303 int height = FRAME_LINE_HEIGHT (f);
8304 FRAME_CONFIG_SCROLL_BAR_LINES (f)
8305 = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + height - 1) / height;
8309 int height = FRAME_LINE_HEIGHT (f);
8310 FRAME_CONFIG_SCROLL_BAR_LINES (f) = (14 + height - 1) / height;
8313 /* Now make the frame display the given font. */
8314 if (FRAME_NS_WINDOW (f) != 0 && ! [view isFullscreen])
8315 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
8316 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 3,
8323 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
8324 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
8328 ns_xlfd_to_fontname (const char *xlfd)
8329 /* --------------------------------------------------------------------------
8330 Convert an X font name (XLFD) to an NS font name.
8331 Only family is used.
8332 The string returned is temporarily allocated.
8333 -------------------------------------------------------------------------- */
8335 char *name = xmalloc (180);
8339 if (!strncmp (xlfd, "--", 2))
8340 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
8342 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
8344 /* stopgap for malformed XLFD input */
8345 if (strlen (name) == 0)
8346 strcpy (name, "Monaco");
8348 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
8349 also uppercase after '-' or ' ' */
8350 name[0] = c_toupper (name[0]);
8351 for (len =strlen (name), i =0; i<len; i++)
8357 name[i+1] = c_toupper (name[i+1]);
8359 else if (name[i] == '_')
8363 name[i+1] = c_toupper (name[i+1]);
8366 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
8367 ret = [[NSString stringWithUTF8String: name] UTF8String];
8374 syms_of_nsterm (void)
8376 NSTRACE ("syms_of_nsterm");
8378 ns_antialias_threshold = 10.0;
8380 /* from 23+ we need to tell emacs what modifiers there are.. */
8381 DEFSYM (Qmodifier_value, "modifier-value");
8382 DEFSYM (Qalt, "alt");
8383 DEFSYM (Qhyper, "hyper");
8384 DEFSYM (Qmeta, "meta");
8385 DEFSYM (Qsuper, "super");
8386 DEFSYM (Qcontrol, "control");
8387 DEFSYM (QUTF8_STRING, "UTF8_STRING");
8389 DEFSYM (Qfile, "file");
8390 DEFSYM (Qurl, "url");
8392 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
8393 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
8394 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
8395 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
8396 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
8398 DEFVAR_LISP ("ns-input-file", ns_input_file,
8399 "The file specified in the last NS event.");
8400 ns_input_file =Qnil;
8402 DEFVAR_LISP ("ns-working-text", ns_working_text,
8403 "String for visualizing working composition sequence.");
8404 ns_working_text =Qnil;
8406 DEFVAR_LISP ("ns-input-font", ns_input_font,
8407 "The font specified in the last NS event.");
8408 ns_input_font =Qnil;
8410 DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
8411 "The fontsize specified in the last NS event.");
8412 ns_input_fontsize =Qnil;
8414 DEFVAR_LISP ("ns-input-line", ns_input_line,
8415 "The line specified in the last NS event.");
8416 ns_input_line =Qnil;
8418 DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
8419 "The service name specified in the last NS event.");
8420 ns_input_spi_name =Qnil;
8422 DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
8423 "The service argument specified in the last NS event.");
8424 ns_input_spi_arg =Qnil;
8426 DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
8427 "This variable describes the behavior of the alternate or option key.\n\
8428 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8429 Set to none means that the alternate / option key is not interpreted by Emacs\n\
8430 at all, allowing it to be used at a lower level for accented character entry.");
8431 ns_alternate_modifier = Qmeta;
8433 DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
8434 "This variable describes the behavior of the right alternate or option key.\n\
8435 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8436 Set to left means be the same key as `ns-alternate-modifier'.\n\
8437 Set to none means that the alternate / option key is not interpreted by Emacs\n\
8438 at all, allowing it to be used at a lower level for accented character entry.");
8439 ns_right_alternate_modifier = Qleft;
8441 DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
8442 "This variable describes the behavior of the command key.\n\
8443 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
8444 ns_command_modifier = Qsuper;
8446 DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
8447 "This variable describes the behavior of the right command key.\n\
8448 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8449 Set to left means be the same key as `ns-command-modifier'.\n\
8450 Set to none means that the command / option key is not interpreted by Emacs\n\
8451 at all, allowing it to be used at a lower level for accented character entry.");
8452 ns_right_command_modifier = Qleft;
8454 DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
8455 "This variable describes the behavior of the control key.\n\
8456 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
8457 ns_control_modifier = Qcontrol;
8459 DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
8460 "This variable describes the behavior of the right control key.\n\
8461 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8462 Set to left means be the same key as `ns-control-modifier'.\n\
8463 Set to none means that the control / option key is not interpreted by Emacs\n\
8464 at all, allowing it to be used at a lower level for accented character entry.");
8465 ns_right_control_modifier = Qleft;
8467 DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
8468 "This variable describes the behavior of the function key (on laptops).\n\
8469 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8470 Set to none means that the function key is not interpreted by Emacs at all,\n\
8471 allowing it to be used at a lower level for accented character entry.");
8472 ns_function_modifier = Qnone;
8474 DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
8475 "Non-nil (the default) means to render text antialiased.");
8476 ns_antialias_text = Qt;
8478 DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
8479 "Whether to confirm application quit using dialog.");
8480 ns_confirm_quit = Qnil;
8482 DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
8483 doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
8484 Only works on OSX 10.6 or later. */);
8485 ns_auto_hide_menu_bar = Qnil;
8487 DEFVAR_BOOL ("ns-use-native-fullscreen", ns_use_native_fullscreen,
8488 doc: /*Non-nil means to use native fullscreen on OSX >= 10.7.
8489 Nil means use fullscreen the old (< 10.7) way. The old way works better with
8490 multiple monitors, but lacks tool bar. This variable is ignored on OSX < 10.7.
8491 Default is t for OSX >= 10.7, nil otherwise. */);
8492 #ifdef HAVE_NATIVE_FS
8493 ns_use_native_fullscreen = YES;
8495 ns_use_native_fullscreen = NO;
8497 ns_last_use_native_fullscreen = ns_use_native_fullscreen;
8499 DEFVAR_BOOL ("ns-use-fullscreen-animation", ns_use_fullscreen_animation,
8500 doc: /*Non-nil means use animation on non-native fullscreen.
8501 For native fullscreen, this does nothing.
8502 Default is nil. */);
8503 ns_use_fullscreen_animation = NO;
8505 DEFVAR_BOOL ("ns-use-srgb-colorspace", ns_use_srgb_colorspace,
8506 doc: /*Non-nil means to use sRGB colorspace on OSX >= 10.7.
8507 Note that this does not apply to images.
8508 This variable is ignored on OSX < 10.7 and GNUstep. */);
8509 ns_use_srgb_colorspace = YES;
8511 /* TODO: move to common code */
8512 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
8513 doc: /* Which toolkit scroll bars Emacs uses, if any.
8514 A value of nil means Emacs doesn't use toolkit scroll bars.
8515 With the X Window system, the value is a symbol describing the
8516 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
8517 With MS Windows or Nextstep, the value is t. */);
8518 Vx_toolkit_scroll_bars = Qt;
8520 DEFVAR_BOOL ("x-use-underline-position-properties",
8521 x_use_underline_position_properties,
8522 doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
8523 A value of nil means ignore them. If you encounter fonts with bogus
8524 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
8525 to 4.1, set this to nil. */);
8526 x_use_underline_position_properties = 0;
8528 DEFVAR_BOOL ("x-underline-at-descent-line",
8529 x_underline_at_descent_line,
8530 doc: /* Non-nil means to draw the underline at the same place as the descent line.
8531 A value of nil means to draw the underline according to the value of the
8532 variable `x-use-underline-position-properties', which is usually at the
8533 baseline level. The default value is nil. */);
8534 x_underline_at_descent_line = 0;
8536 /* Tell Emacs about this window system. */
8537 Fprovide (Qns, Qnil);
8539 DEFSYM (Qcocoa, "cocoa");
8540 DEFSYM (Qgnustep, "gnustep");
8542 #ifdef NS_IMPL_COCOA
8543 Fprovide (Qcocoa, Qnil);
8546 Fprovide (Qgnustep, Qnil);