1 /* NeXT/Open/GNUstep / MacOSX communication module. -*- coding: utf-8 -*-
3 Copyright (C) 1989, 1993-1994, 2005-2006, 2008-2016 Free Software
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
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];
589 ns_release_object (void *obj)
590 /* --------------------------------------------------------------------------
591 Release an object (callable from C)
592 -------------------------------------------------------------------------- */
599 ns_retain_object (void *obj)
600 /* --------------------------------------------------------------------------
601 Retain an object (callable from C)
602 -------------------------------------------------------------------------- */
609 ns_alloc_autorelease_pool (void)
610 /* --------------------------------------------------------------------------
611 Allocate a pool for temporary objects (callable from C)
612 -------------------------------------------------------------------------- */
614 return [[NSAutoreleasePool alloc] init];
619 ns_release_autorelease_pool (void *pool)
620 /* --------------------------------------------------------------------------
621 Free a pool and temporary objects it refers to (callable from C)
622 -------------------------------------------------------------------------- */
624 ns_release_object (pool);
628 /* True, if the menu bar should be hidden. */
631 ns_menu_bar_should_be_hidden (void)
633 return !NILP (ns_auto_hide_menu_bar)
634 && [NSApp respondsToSelector:@selector(setPresentationOptions:)];
639 ns_menu_bar_height (NSScreen *screen)
640 /* The height of the menu bar, if visible.
642 Note: Don't use this when fullscreen is enabled -- the screen
643 sometimes includes, sometimes excludes the menu bar area. */
647 if (ns_menu_bar_should_be_hidden())
653 NSRect screenFrame = [screen frame];
654 NSRect screenVisibleFrame = [screen visibleFrame];
656 CGFloat frameTop = screenFrame.origin.y + screenFrame.size.height;
657 CGFloat visibleFrameTop = (screenVisibleFrame.origin.y
658 + screenVisibleFrame.size.height);
660 res = frameTop - visibleFrameTop;
664 NSTRACE ("ns_menu_bar_height " NSTRACE_FMT_RETURN " %.0f", res);
670 /* ==========================================================================
672 Focus (clipping) and screen update
674 ========================================================================== */
677 // Window constraining
678 // -------------------
680 // To ensure that the windows are not placed under the menu bar, they
681 // are typically moved by the call-back constrainFrameRect. However,
682 // by overriding it, it's possible to inhibit this, leaving the window
683 // in it's original position.
685 // It's possible to hide the menu bar. However, technically, it's only
686 // possible to hide it when the application is active. To ensure that
687 // this work properly, the menu bar and window constraining are
688 // deferred until the application becomes active.
690 // Even though it's not possible to manually move a window above the
691 // top of the screen, it is allowed if it's done programmatically,
692 // when the menu is hidden. This allows the editable area to cover the
693 // full screen height.
698 // Use the following extra files:
701 // ;; Hide menu and place frame slightly above the top of the screen.
702 // (setq ns-auto-hide-menu-bar t)
703 // (set-frame-position (selected-frame) 0 -20)
707 // emacs -Q -l init.el
709 // Result: No menu bar, and the title bar should be above the screen.
715 // Result: Menu bar visible, frame placed immediately below the menu.
718 static NSRect constrain_frame_rect(NSRect frameRect, bool isFullscreen)
720 NSTRACE ("constrain_frame_rect(" NSTRACE_FMT_RECT ")",
721 NSTRACE_ARG_RECT (frameRect));
723 // --------------------
724 // Collect information about the screen the frame is covering.
727 NSArray *screens = [NSScreen screens];
728 NSUInteger nr_screens = [screens count];
732 // The height of the menu bar, if present in any screen the frame is
734 int menu_bar_height = 0;
736 // A rectangle covering all the screen the frame is displayed in.
737 NSRect multiscreenRect = NSMakeRect(0, 0, 0, 0);
738 for (i = 0; i < nr_screens; ++i )
740 NSScreen *s = [screens objectAtIndex: i];
741 NSRect scrRect = [s frame];
743 NSTRACE_MSG ("Screen %d: " NSTRACE_FMT_RECT,
744 i, NSTRACE_ARG_RECT (scrRect));
746 if (NSIntersectionRect (frameRect, scrRect).size.height != 0)
748 multiscreenRect = NSUnionRect (multiscreenRect, scrRect);
752 CGFloat screen_menu_bar_height = ns_menu_bar_height (s);
753 menu_bar_height = max(menu_bar_height, screen_menu_bar_height);
758 NSTRACE_RECT ("multiscreenRect", multiscreenRect);
760 NSTRACE_MSG ("menu_bar_height: %d", menu_bar_height);
762 if (multiscreenRect.size.width == 0
763 || multiscreenRect.size.height == 0)
765 // Failed to find any monitor, give up.
766 NSTRACE_MSG ("multiscreenRect empty");
767 NSTRACE_RETURN_RECT (frameRect);
772 // --------------------
773 // Find a suitable placement.
776 if (ns_menu_bar_should_be_hidden())
778 // When the menu bar is hidden, the user may place part of the
779 // frame above the top of the screen, for example to hide the
782 // Hence, keep the original position.
786 // Ensure that the frame is below the menu bar, or below the top
789 // This assume that the menu bar is placed at the top in the
790 // rectangle that covers the monitors. (It doesn't have to be,
791 // but if it's not it's hard to do anything useful.)
792 CGFloat topOfWorkArea = (multiscreenRect.origin.y
793 + multiscreenRect.size.height
796 CGFloat topOfFrame = frameRect.origin.y + frameRect.size.height;
797 if (topOfFrame > topOfWorkArea)
799 frameRect.origin.y -= topOfFrame - topOfWorkArea;
800 NSTRACE_RECT ("After placement adjust", frameRect);
804 // Include the following section to restrict frame to the screens.
805 // (If so, update it to allow the frame to stretch down below the
808 // --------------------
809 // Ensure frame doesn't stretch below the screens.
812 CGFloat diff = multiscreenRect.origin.y - frameRect.origin.y;
816 frameRect.origin.y = multiscreenRect.origin.y;
817 frameRect.size.height -= diff;
821 NSTRACE_RETURN_RECT (frameRect);
827 ns_constrain_all_frames (void)
828 /* --------------------------------------------------------------------------
829 Ensure that the menu bar doesn't cover any frames.
830 -------------------------------------------------------------------------- */
832 Lisp_Object tail, frame;
834 NSTRACE ("ns_constrain_all_frames");
838 FOR_EACH_FRAME (tail, frame)
840 struct frame *f = XFRAME (frame);
843 EmacsView *view = FRAME_NS_VIEW (f);
845 if (![view isFullscreen])
848 setFrame:constrain_frame_rect([[view window] frame], false)
859 ns_update_auto_hide_menu_bar (void)
860 /* --------------------------------------------------------------------------
861 Show or hide the menu bar, based on user setting.
862 -------------------------------------------------------------------------- */
865 NSTRACE ("ns_update_auto_hide_menu_bar");
869 if (NSApp != nil && [NSApp isActive])
871 // Note, "setPresentationOptions" triggers an error unless the
872 // application is active.
873 BOOL menu_bar_should_be_hidden = ns_menu_bar_should_be_hidden ();
875 if (menu_bar_should_be_hidden != ns_menu_bar_is_hidden)
877 NSApplicationPresentationOptions options
878 = NSApplicationPresentationDefault;
880 if (menu_bar_should_be_hidden)
881 options |= NSApplicationPresentationAutoHideMenuBar
882 | NSApplicationPresentationAutoHideDock;
884 [NSApp setPresentationOptions: options];
886 ns_menu_bar_is_hidden = menu_bar_should_be_hidden;
888 if (!ns_menu_bar_is_hidden)
890 ns_constrain_all_frames ();
901 ns_update_begin (struct frame *f)
902 /* --------------------------------------------------------------------------
903 Prepare for a grouped sequence of drawing calls
904 external (RIF) call; whole frame, called before update_window_begin
905 -------------------------------------------------------------------------- */
907 EmacsView *view = FRAME_NS_VIEW (f);
908 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_begin");
910 ns_update_auto_hide_menu_bar ();
913 if ([view isFullscreen] && [view fsIsNative])
915 // Fix reappearing tool bar in fullscreen for OSX 10.7
916 BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (f) ? YES : NO;
917 NSToolbar *toolbar = [FRAME_NS_VIEW (f) toolbar];
918 if (! tbar_visible != ! [toolbar isVisible])
919 [toolbar setVisible: tbar_visible];
923 ns_updating_frame = f;
926 /* drawRect may have been called for say the minibuffer, and then clip path
927 is for the minibuffer. But the display engine may draw more because
928 we have set the frame as garbaged. So reset clip path to the whole
933 NSRect r = [view frame];
934 NSRect cr = [[view window] frame];
935 /* If a large frame size is set, r may be larger than the window frame
936 before constrained. In that case don't change the clip path, as we
937 will clear in to the tool bar and title bar. */
939 + FRAME_NS_TITLEBAR_HEIGHT (f)
940 + FRAME_TOOLBAR_HEIGHT (f) <= cr.size.height)
942 bp = [[NSBezierPath bezierPathWithRect: r] retain];
949 #ifdef NS_IMPL_GNUSTEP
950 uRect = NSMakeRect (0, 0, 0, 0);
956 ns_update_window_begin (struct window *w)
957 /* --------------------------------------------------------------------------
958 Prepare for a grouped sequence of drawing calls
959 external (RIF) call; for one window, called after update_begin
960 -------------------------------------------------------------------------- */
962 struct frame *f = XFRAME (WINDOW_FRAME (w));
963 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
965 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_window_begin");
966 w->output_cursor = w->cursor;
970 if (f == hlinfo->mouse_face_mouse_frame)
972 /* Don't do highlighting for mouse motion during the update. */
973 hlinfo->mouse_face_defer = 1;
975 /* If the frame needs to be redrawn,
976 simply forget about any prior mouse highlighting. */
977 if (FRAME_GARBAGED_P (f))
978 hlinfo->mouse_face_window = Qnil;
980 /* (further code for mouse faces ifdef'd out in other terms elided) */
988 ns_update_window_end (struct window *w, bool cursor_on_p,
989 bool mouse_face_overwritten_p)
990 /* --------------------------------------------------------------------------
991 Finished a grouped sequence of drawing calls
992 external (RIF) call; for one window called before update_end
993 -------------------------------------------------------------------------- */
995 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_window_end");
997 /* note: this fn is nearly identical in all terms */
998 if (!w->pseudo_window_p)
1003 display_and_set_cursor (w, 1,
1004 w->output_cursor.hpos, w->output_cursor.vpos,
1005 w->output_cursor.x, w->output_cursor.y);
1007 if (draw_window_fringes (w, 1))
1009 if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
1010 x_draw_right_divider (w);
1012 x_draw_vertical_border (w);
1018 /* If a row with mouse-face was overwritten, arrange for
1019 frame_up_to_date to redisplay the mouse highlight. */
1020 if (mouse_face_overwritten_p)
1021 reset_mouse_highlight (MOUSE_HL_INFO (XFRAME (w->frame)));
1026 ns_update_end (struct frame *f)
1027 /* --------------------------------------------------------------------------
1028 Finished a grouped sequence of drawing calls
1029 external (RIF) call; for whole frame, called after update_window_end
1030 -------------------------------------------------------------------------- */
1032 EmacsView *view = FRAME_NS_VIEW (f);
1034 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_update_end");
1036 /* if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
1037 MOUSE_HL_INFO (f)->mouse_face_defer = 0;
1042 [[view window] flushWindow];
1045 ns_updating_frame = NULL;
1049 ns_focus (struct frame *f, NSRect *r, int n)
1050 /* --------------------------------------------------------------------------
1051 Internal: Focus on given frame. During small local updates this is used to
1052 draw, however during large updates, ns_update_begin and ns_update_end are
1053 called to wrap the whole thing, in which case these calls are stubbed out.
1054 Except, on GNUstep, we accumulate the rectangle being drawn into, because
1055 the back end won't do this automatically, and will just end up flushing
1057 -------------------------------------------------------------------------- */
1059 NSTRACE_WHEN (NSTRACE_GROUP_FOCUS, "ns_focus");
1062 NSTRACE_RECT ("r", *r);
1065 if (f != ns_updating_frame)
1067 NSView *view = FRAME_NS_VIEW (f);
1068 if (view != focus_view)
1070 if (focus_view != NULL)
1072 [focus_view unlockFocus];
1073 [[focus_view window] flushWindow];
1080 /*if (view) debug_lock++; */
1087 [[NSGraphicsContext currentContext] saveGraphicsState];
1089 NSRectClipList (r, 2);
1098 ns_unfocus (struct frame *f)
1099 /* --------------------------------------------------------------------------
1100 Internal: Remove focus on given frame
1101 -------------------------------------------------------------------------- */
1103 NSTRACE_WHEN (NSTRACE_GROUP_FOCUS, "ns_unfocus");
1107 [[NSGraphicsContext currentContext] restoreGraphicsState];
1111 if (f != ns_updating_frame)
1113 if (focus_view != NULL)
1115 [focus_view unlockFocus];
1116 [[focus_view window] flushWindow];
1125 ns_clip_to_row (struct window *w, struct glyph_row *row,
1126 enum glyph_row_area area, BOOL gc)
1127 /* --------------------------------------------------------------------------
1128 Internal (but parallels other terms): Focus drawing on given row
1129 -------------------------------------------------------------------------- */
1131 struct frame *f = XFRAME (WINDOW_FRAME (w));
1133 int window_x, window_y, window_width;
1135 window_box (w, area, &window_x, &window_y, &window_width, 0);
1137 clip_rect.origin.x = window_x;
1138 clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
1139 clip_rect.origin.y = max (clip_rect.origin.y, window_y);
1140 clip_rect.size.width = window_width;
1141 clip_rect.size.height = row->visible_height;
1143 ns_focus (f, &clip_rect, 1);
1147 /* ==========================================================================
1149 Visible bell and beep.
1151 ========================================================================== */
1154 @interface EmacsBell : NSImageView
1156 // Number of currently active bell:s.
1157 unsigned int nestCount;
1160 - (void)show:(NSView *)view;
1165 @implementation EmacsBell
1169 NSTRACE ("[EmacsBell init]");
1170 if ((self = [super init]))
1174 #ifdef NS_IMPL_GNUSTEP
1175 // GNUstep doesn't provide named images. This was reported in
1176 // 2011, see https://savannah.gnu.org/bugs/?33396
1178 // As a drop in replacement, a semitransparent gray square is used.
1179 self.image = [[NSImage alloc] initWithSize:NSMakeSize(32, 32)];
1180 [self.image lockFocus];
1181 [[NSColor colorForEmacsRed:0.5 green:0.5 blue:0.5 alpha:0.5] set];
1182 NSRectFill(NSMakeRect(0, 0, 32, 32));
1183 [self.image unlockFocus];
1185 self.image = [NSImage imageNamed:NSImageNameCaution];
1191 - (void)show:(NSView *)view
1193 NSTRACE ("[EmacsBell show:]");
1194 NSTRACE_MSG ("nestCount: %u", nestCount);
1196 // Show the image, unless it's already shown.
1199 NSRect rect = [view bounds];
1201 pos.x = rect.origin.x + (rect.size.width - self.image.size.width )/2;
1202 pos.y = rect.origin.y + (rect.size.height - self.image.size.height)/2;
1204 [self setFrameOrigin:pos];
1205 [self setFrameSize:self.image.size];
1208 [[[view window] contentView] addSubview:self
1209 positioned:NSWindowAbove
1215 [self performSelector:@selector(hide) withObject:self afterDelay:0.5];
1221 // Note: Trace output from this method isn't shown, reason unknown.
1222 // NSTRACE ("[EmacsBell hide]");
1227 // Remove the image once the last bell became inactive.
1239 [self removeFromSuperview];
1247 static EmacsBell * bell_view = nil;
1250 ns_ring_bell (struct frame *f)
1251 /* --------------------------------------------------------------------------
1253 -------------------------------------------------------------------------- */
1255 NSTRACE ("ns_ring_bell");
1258 struct frame *frame = SELECTED_FRAME ();
1261 if (bell_view == nil)
1263 bell_view = [[EmacsBell alloc] init];
1269 view = FRAME_NS_VIEW (frame);
1272 [bell_view show:view];
1284 static void hide_bell ()
1285 /* --------------------------------------------------------------------------
1286 Ensure the bell is hidden.
1287 -------------------------------------------------------------------------- */
1289 if (bell_view != nil)
1296 /* ==========================================================================
1298 Frame / window manager related functions
1300 ========================================================================== */
1304 ns_raise_frame (struct frame *f)
1305 /* --------------------------------------------------------------------------
1306 Bring window to foreground and make it active
1307 -------------------------------------------------------------------------- */
1311 check_window_system (f);
1312 view = FRAME_NS_VIEW (f);
1314 if (FRAME_VISIBLE_P (f))
1315 [[view window] makeKeyAndOrderFront: NSApp];
1321 ns_lower_frame (struct frame *f)
1322 /* --------------------------------------------------------------------------
1324 -------------------------------------------------------------------------- */
1328 check_window_system (f);
1329 view = FRAME_NS_VIEW (f);
1331 [[view window] orderBack: NSApp];
1337 ns_frame_raise_lower (struct frame *f, bool raise)
1338 /* --------------------------------------------------------------------------
1340 -------------------------------------------------------------------------- */
1342 NSTRACE ("ns_frame_raise_lower");
1352 ns_frame_rehighlight (struct frame *frame)
1353 /* --------------------------------------------------------------------------
1354 External (hook): called on things like window switching within frame
1355 -------------------------------------------------------------------------- */
1357 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
1358 struct frame *old_highlight = dpyinfo->x_highlight_frame;
1360 NSTRACE ("ns_frame_rehighlight");
1361 if (dpyinfo->x_focus_frame)
1363 dpyinfo->x_highlight_frame
1364 = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1365 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1366 : dpyinfo->x_focus_frame);
1367 if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
1369 fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
1370 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
1374 dpyinfo->x_highlight_frame = 0;
1376 if (dpyinfo->x_highlight_frame &&
1377 dpyinfo->x_highlight_frame != old_highlight)
1381 x_update_cursor (old_highlight, 1);
1382 x_set_frame_alpha (old_highlight);
1384 if (dpyinfo->x_highlight_frame)
1386 x_update_cursor (dpyinfo->x_highlight_frame, 1);
1387 x_set_frame_alpha (dpyinfo->x_highlight_frame);
1394 x_make_frame_visible (struct frame *f)
1395 /* --------------------------------------------------------------------------
1396 External: Show the window (X11 semantics)
1397 -------------------------------------------------------------------------- */
1399 NSTRACE ("x_make_frame_visible");
1400 /* XXX: at some points in past this was not needed, as the only place that
1401 called this (frame.c:Fraise_frame ()) also called raise_lower;
1402 if this ends up the case again, comment this out again. */
1403 if (!FRAME_VISIBLE_P (f))
1405 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1407 SET_FRAME_VISIBLE (f, 1);
1410 /* Making a new frame from a fullscreen frame will make the new frame
1411 fullscreen also. So skip handleFS as this will print an error. */
1412 if ([view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH
1413 && [view isFullscreen])
1416 if (f->want_fullscreen != FULLSCREEN_NONE)
1427 x_make_frame_invisible (struct frame *f)
1428 /* --------------------------------------------------------------------------
1429 External: Hide the window (X11 semantics)
1430 -------------------------------------------------------------------------- */
1433 NSTRACE ("x_make_frame_invisible");
1434 check_window_system (f);
1435 view = FRAME_NS_VIEW (f);
1436 [[view window] orderOut: NSApp];
1437 SET_FRAME_VISIBLE (f, 0);
1438 SET_FRAME_ICONIFIED (f, 0);
1443 x_iconify_frame (struct frame *f)
1444 /* --------------------------------------------------------------------------
1445 External: Iconify window
1446 -------------------------------------------------------------------------- */
1449 struct ns_display_info *dpyinfo;
1451 NSTRACE ("x_iconify_frame");
1452 check_window_system (f);
1453 view = FRAME_NS_VIEW (f);
1454 dpyinfo = FRAME_DISPLAY_INFO (f);
1456 if (dpyinfo->x_highlight_frame == f)
1457 dpyinfo->x_highlight_frame = 0;
1459 if ([[view window] windowNumber] <= 0)
1461 /* the window is still deferred. Make it very small, bring it
1462 on screen and order it out. */
1463 NSRect s = { { 100, 100}, {0, 0} };
1465 t = [[view window] frame];
1466 [[view window] setFrame: s display: NO];
1467 [[view window] orderBack: NSApp];
1468 [[view window] orderOut: NSApp];
1469 [[view window] setFrame: t display: NO];
1471 [[view window] miniaturize: NSApp];
1474 /* Free X resources of frame F. */
1477 x_free_frame_resources (struct frame *f)
1480 struct ns_display_info *dpyinfo;
1481 Mouse_HLInfo *hlinfo;
1483 NSTRACE ("x_free_frame_resources");
1484 check_window_system (f);
1485 view = FRAME_NS_VIEW (f);
1486 dpyinfo = FRAME_DISPLAY_INFO (f);
1487 hlinfo = MOUSE_HL_INFO (f);
1489 [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1493 free_frame_menubar (f);
1494 free_frame_faces (f);
1496 if (f == dpyinfo->x_focus_frame)
1497 dpyinfo->x_focus_frame = 0;
1498 if (f == dpyinfo->x_highlight_frame)
1499 dpyinfo->x_highlight_frame = 0;
1500 if (f == hlinfo->mouse_face_mouse_frame)
1501 reset_mouse_highlight (hlinfo);
1503 if (f->output_data.ns->miniimage != nil)
1504 [f->output_data.ns->miniimage release];
1506 [[view window] close];
1509 xfree (f->output_data.ns);
1515 x_destroy_window (struct frame *f)
1516 /* --------------------------------------------------------------------------
1517 External: Delete the window
1518 -------------------------------------------------------------------------- */
1520 NSTRACE ("x_destroy_window");
1521 check_window_system (f);
1522 x_free_frame_resources (f);
1528 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1529 /* --------------------------------------------------------------------------
1530 External: Position the window
1531 -------------------------------------------------------------------------- */
1533 NSView *view = FRAME_NS_VIEW (f);
1534 NSArray *screens = [NSScreen screens];
1535 NSScreen *fscreen = [screens objectAtIndex: 0];
1536 NSScreen *screen = [[view window] screen];
1538 NSTRACE ("x_set_offset");
1545 if (view != nil && screen && fscreen)
1547 f->left_pos = f->size_hint_flags & XNegative
1548 ? [screen visibleFrame].size.width + f->left_pos - FRAME_PIXEL_WIDTH (f)
1550 /* We use visibleFrame here to take menu bar into account.
1551 Ideally we should also adjust left/top with visibleFrame.origin. */
1553 f->top_pos = f->size_hint_flags & YNegative
1554 ? ([screen visibleFrame].size.height + f->top_pos
1555 - FRAME_PIXEL_HEIGHT (f) - FRAME_NS_TITLEBAR_HEIGHT (f)
1556 - FRAME_TOOLBAR_HEIGHT (f))
1558 #ifdef NS_IMPL_GNUSTEP
1559 if (f->left_pos < 100)
1560 f->left_pos = 100; /* don't overlap menu */
1562 /* Constrain the setFrameTopLeftPoint so we don't move behind the
1564 NSPoint pt = NSMakePoint (SCREENMAXBOUND (f->left_pos),
1565 SCREENMAXBOUND ([fscreen frame].size.height
1567 NSTRACE_POINT ("setFrameTopLeftPoint", pt);
1568 [[view window] setFrameTopLeftPoint: pt];
1569 f->size_hint_flags &= ~(XNegative|YNegative);
1577 x_set_window_size (struct frame *f,
1578 bool change_gravity,
1582 /* --------------------------------------------------------------------------
1583 Adjust window pixel size based on given character grid size
1584 Impl is a bit more complex than other terms, need to do some
1586 -------------------------------------------------------------------------- */
1588 EmacsView *view = FRAME_NS_VIEW (f);
1589 NSWindow *window = [view window];
1590 NSRect wr = [window frame];
1591 int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1592 int pixelwidth, pixelheight;
1593 int orig_height = wr.size.height;
1595 NSTRACE ("x_set_window_size");
1600 NSTRACE_RECT ("current", wr);
1601 NSTRACE_MSG ("Width:%d Height:%d Pixelwise:%d", width, height, pixelwise);
1602 NSTRACE_MSG ("Font %d x %d", FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f));
1608 pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
1609 pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
1613 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, width);
1614 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, height);
1617 /* If we have a toolbar, take its height into account. */
1618 if (tb && ! [view isFullscreen])
1620 /* NOTE: previously this would generate wrong result if toolbar not
1621 yet displayed and fixing toolbar_height=32 helped, but
1622 now (200903) seems no longer needed */
1623 FRAME_TOOLBAR_HEIGHT (f) =
1624 NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1625 - FRAME_NS_TITLEBAR_HEIGHT (f);
1627 /* Only breaks things here, removed by martin 2015-09-30. */
1628 #ifdef NS_IMPL_GNUSTEP
1629 FRAME_TOOLBAR_HEIGHT (f) -= 3;
1634 FRAME_TOOLBAR_HEIGHT (f) = 0;
1636 wr.size.width = pixelwidth + f->border_width;
1637 wr.size.height = pixelheight;
1638 if (! [view isFullscreen])
1639 wr.size.height += FRAME_NS_TITLEBAR_HEIGHT (f)
1640 + FRAME_TOOLBAR_HEIGHT (f);
1642 /* Do not try to constrain to this screen. We may have multiple
1643 screens, and want Emacs to span those. Constraining to screen
1644 prevents that, and that is not nice to the user. */
1645 if (f->output_data.ns->zooming)
1646 f->output_data.ns->zooming = 0;
1648 wr.origin.y += orig_height - wr.size.height;
1650 frame_size_history_add
1651 (f, Qx_set_window_size_1, width, height,
1652 list5 (Fcons (make_number (pixelwidth), make_number (pixelheight)),
1653 Fcons (make_number (wr.size.width), make_number (wr.size.height)),
1654 make_number (f->border_width),
1655 make_number (FRAME_NS_TITLEBAR_HEIGHT (f)),
1656 make_number (FRAME_TOOLBAR_HEIGHT (f))));
1658 [window setFrame: wr display: YES];
1660 /* This is a trick to compensate for Emacs' managing the scrollbar area
1661 as a fixed number of standard character columns. Instead of leaving
1662 blank space for the extra, we chopped it off above. Now for
1663 left-hand scrollbars, we shift all rendering to the left by the
1664 difference between the real width and Emacs' imagined one. For
1665 right-hand bars, don't worry about it since the extra is never used.
1666 (Obviously doesn't work for vertically split windows tho..) */
1668 NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1669 ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1670 - NS_SCROLL_BAR_WIDTH (f), 0)
1671 : NSMakePoint (0, 0);
1673 [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1674 [view setBoundsOrigin: origin];
1677 [view updateFrameSize: NO];
1683 ns_fullscreen_hook (struct frame *f)
1685 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1687 NSTRACE ("ns_fullscreen_hook");
1689 if (!FRAME_VISIBLE_P (f))
1692 if (! [view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH)
1694 /* Old style fs don't initiate correctly if created from
1695 init/default-frame alist, so use a timer (not nice...).
1697 [NSTimer scheduledTimerWithTimeInterval: 0.5 target: view
1698 selector: @selector (handleFS)
1699 userInfo: nil repeats: NO];
1708 /* ==========================================================================
1712 ========================================================================== */
1716 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1718 struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1719 if (idx < 1 || idx >= color_table->avail)
1721 return color_table->colors[idx];
1726 ns_index_color (NSColor *color, struct frame *f)
1728 struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1732 if (!color_table->colors)
1734 color_table->size = NS_COLOR_CAPACITY;
1735 color_table->avail = 1; /* skip idx=0 as marker */
1736 color_table->colors = xmalloc (color_table->size * sizeof (NSColor *));
1737 color_table->colors[0] = nil;
1738 color_table->empty_indices = [[NSMutableSet alloc] init];
1741 /* Do we already have this color? */
1742 for (i = 1; i < color_table->avail; i++)
1743 if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1746 if ([color_table->empty_indices count] > 0)
1748 NSNumber *index = [color_table->empty_indices anyObject];
1749 [color_table->empty_indices removeObject: index];
1750 idx = [index unsignedLongValue];
1754 if (color_table->avail == color_table->size)
1755 color_table->colors =
1756 xpalloc (color_table->colors, &color_table->size, 1,
1757 min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1758 idx = color_table->avail++;
1761 color_table->colors[idx] = color;
1763 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1769 ns_free_indexed_color (unsigned long idx, struct frame *f)
1771 struct ns_color_table *color_table;
1778 color_table = FRAME_DISPLAY_INFO (f)->color_table;
1780 if (idx <= 0 || idx >= color_table->size) {
1781 message1 ("ns_free_indexed_color: Color index out of range.\n");
1785 index = [NSNumber numberWithUnsignedInt: idx];
1786 if ([color_table->empty_indices containsObject: index]) {
1787 message1 ("ns_free_indexed_color: attempt to free already freed color.\n");
1791 color = color_table->colors[idx];
1793 color_table->colors[idx] = nil;
1794 [color_table->empty_indices addObject: index];
1795 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1800 ns_get_color (const char *name, NSColor **col)
1801 /* --------------------------------------------------------------------------
1803 -------------------------------------------------------------------------- */
1804 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1805 X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1806 See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1809 static char hex[20];
1811 float r = -1.0, g, b;
1812 NSString *nsname = [NSString stringWithUTF8String: name];
1814 NSTRACE ("ns_get_color(%s, **)", name);
1818 if ([nsname isEqualToString: @"ns_selection_bg_color"])
1820 #ifdef NS_IMPL_COCOA
1821 NSString *defname = [[NSUserDefaults standardUserDefaults]
1822 stringForKey: @"AppleHighlightColor"];
1827 if ((new = [NSColor selectedTextBackgroundColor]) != nil)
1829 *col = [new colorUsingDefaultColorSpace];
1834 nsname = NS_SELECTION_BG_COLOR_DEFAULT;
1836 name = [nsname UTF8String];
1838 else if ([nsname isEqualToString: @"ns_selection_fg_color"])
1840 /* NOTE: OSX applications normally don't set foreground selection, but
1841 text may be unreadable if we don't.
1843 if ((new = [NSColor selectedTextColor]) != nil)
1845 *col = [new colorUsingDefaultColorSpace];
1850 nsname = NS_SELECTION_FG_COLOR_DEFAULT;
1851 name = [nsname UTF8String];
1854 /* First, check for some sort of numeric specification. */
1857 if (name[0] == '0' || name[0] == '1' || name[0] == '.') /* RGB decimal */
1859 NSScanner *scanner = [NSScanner scannerWithString: nsname];
1860 [scanner scanFloat: &r];
1861 [scanner scanFloat: &g];
1862 [scanner scanFloat: &b];
1864 else if (!strncmp(name, "rgb:", 4)) /* A newer X11 format -- rgb:r/g/b */
1865 scaling = (snprintf (hex, sizeof hex, "%s", name + 4) - 2) / 3;
1866 else if (name[0] == '#') /* An old X11 format; convert to newer */
1868 int len = (strlen(name) - 1);
1869 int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1871 scaling = strlen(name+start) / 3;
1872 for (i = 0; i < 3; i++)
1873 sprintf (hex + i * (scaling + 1), "%.*s/", scaling,
1874 name + start + i * scaling);
1875 hex[3 * (scaling + 1) - 1] = '\0';
1881 float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1882 if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1892 *col = [NSColor colorForEmacsRed: r green: g blue: b alpha: 1.0];
1897 /* Otherwise, color is expected to be from a list */
1899 NSEnumerator *lenum, *cenum;
1903 #ifdef NS_IMPL_GNUSTEP
1904 /* XXX: who is wrong, the requestor or the implementation? */
1905 if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1907 nsname = @"highlightColor";
1910 lenum = [[NSColorList availableColorLists] objectEnumerator];
1911 while ( (clist = [lenum nextObject]) && new == nil)
1913 cenum = [[clist allKeys] objectEnumerator];
1914 while ( (name = [cenum nextObject]) && new == nil )
1916 if ([name compare: nsname
1917 options: NSCaseInsensitiveSearch] == NSOrderedSame )
1918 new = [clist colorWithKey: name];
1924 *col = [new colorUsingDefaultColorSpace];
1931 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1932 /* --------------------------------------------------------------------------
1933 Convert a Lisp string object to a NS color
1934 -------------------------------------------------------------------------- */
1936 NSTRACE ("ns_lisp_to_color");
1937 if (STRINGP (color))
1938 return ns_get_color (SSDATA (color), col);
1939 else if (SYMBOLP (color))
1940 return ns_get_color (SSDATA (SYMBOL_NAME (color)), col);
1946 ns_color_to_lisp (NSColor *col)
1947 /* --------------------------------------------------------------------------
1948 Convert a color to a lisp string with the RGB equivalent
1949 -------------------------------------------------------------------------- */
1951 EmacsCGFloat red, green, blue, alpha, gray;
1954 NSTRACE ("ns_color_to_lisp");
1957 if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1959 if ((str =[[col colorNameComponent] UTF8String]))
1962 return build_string ((char *)str);
1965 [[col colorUsingDefaultColorSpace]
1966 getRed: &red green: &green blue: &blue alpha: &alpha];
1967 if (red == green && red == blue)
1969 [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1970 getWhite: &gray alpha: &alpha];
1971 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1972 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1974 return build_string (buf);
1977 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1978 lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1981 return build_string (buf);
1986 ns_query_color(void *col, XColor *color_def, int setPixel)
1987 /* --------------------------------------------------------------------------
1988 Get ARGB values out of NSColor col and put them into color_def.
1989 If setPixel, set the pixel to a concatenated version.
1990 and set color_def pixel to the resulting index.
1991 -------------------------------------------------------------------------- */
1993 EmacsCGFloat r, g, b, a;
1995 [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1996 color_def->red = r * 65535;
1997 color_def->green = g * 65535;
1998 color_def->blue = b * 65535;
2000 if (setPixel == YES)
2002 = ARGB_TO_ULONG((int)(a*255),
2003 (int)(r*255), (int)(g*255), (int)(b*255));
2008 ns_defined_color (struct frame *f,
2013 /* --------------------------------------------------------------------------
2014 Return true if named color found, and set color_def rgb accordingly.
2015 If makeIndex and alloc are nonzero put the color in the color_table,
2016 and set color_def pixel to the resulting index.
2017 If makeIndex is zero, set color_def pixel to ARGB.
2018 Return false if not found
2019 -------------------------------------------------------------------------- */
2022 NSTRACE_WHEN (NSTRACE_GROUP_COLOR, "ns_defined_color");
2025 if (ns_get_color (name, &col) != 0) /* Color not found */
2030 if (makeIndex && alloc)
2031 color_def->pixel = ns_index_color (col, f);
2032 ns_query_color (col, color_def, !makeIndex);
2039 x_set_frame_alpha (struct frame *f)
2040 /* --------------------------------------------------------------------------
2041 change the entire-frame transparency
2042 -------------------------------------------------------------------------- */
2044 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2046 double alpha_min = 1.0;
2048 NSTRACE ("x_set_frame_alpha");
2050 if (dpyinfo->x_highlight_frame == f)
2051 alpha = f->alpha[0];
2053 alpha = f->alpha[1];
2055 if (FLOATP (Vframe_alpha_lower_limit))
2056 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
2057 else if (INTEGERP (Vframe_alpha_lower_limit))
2058 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
2062 else if (1.0 < alpha)
2064 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
2067 #ifdef NS_IMPL_COCOA
2069 EmacsView *view = FRAME_NS_VIEW (f);
2070 [[view window] setAlphaValue: alpha];
2076 /* ==========================================================================
2080 ========================================================================== */
2084 frame_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
2085 /* --------------------------------------------------------------------------
2086 Programmatically reposition mouse pointer in pixel coordinates
2087 -------------------------------------------------------------------------- */
2089 NSTRACE ("frame_set_mouse_pixel_position");
2092 /* FIXME: this does not work, and what about GNUstep? */
2093 #ifdef NS_IMPL_COCOA
2094 [FRAME_NS_VIEW (f) lockFocus];
2095 PSsetmouse ((float)pix_x, (float)pix_y);
2096 [FRAME_NS_VIEW (f) unlockFocus];
2102 note_mouse_movement (struct frame *frame, CGFloat x, CGFloat y)
2103 /* ------------------------------------------------------------------------
2104 Called by EmacsView on mouseMovement events. Passes on
2105 to emacs mainstream code if we moved off of a rect of interest
2106 known as last_mouse_glyph.
2107 ------------------------------------------------------------------------ */
2109 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
2112 // NSTRACE ("note_mouse_movement");
2114 dpyinfo->last_mouse_motion_frame = frame;
2115 r = &dpyinfo->last_mouse_glyph;
2117 /* Note, this doesn't get called for enter/leave, since we don't have a
2118 position. Those are taken care of in the corresponding NSView methods. */
2120 /* has movement gone beyond last rect we were tracking? */
2121 if (x < r->origin.x || x >= r->origin.x + r->size.width
2122 || y < r->origin.y || y >= r->origin.y + r->size.height)
2124 ns_update_begin (frame);
2125 frame->mouse_moved = 1;
2126 note_mouse_highlight (frame, x, y);
2127 remember_mouse_glyph (frame, x, y, r);
2128 ns_update_end (frame);
2137 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
2138 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
2140 /* --------------------------------------------------------------------------
2141 External (hook): inform emacs about mouse position and hit parts.
2142 If a scrollbar is being dragged, set bar_window, part, x, y, time.
2143 x & y should be position in the scrollbar (the whole bar, not the handle)
2144 and length of scrollbar respectively
2145 -------------------------------------------------------------------------- */
2149 Lisp_Object frame, tail;
2151 struct ns_display_info *dpyinfo;
2153 NSTRACE ("ns_mouse_position");
2157 fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
2161 dpyinfo = FRAME_DISPLAY_INFO (*fp);
2165 /* Clear the mouse-moved flag for every frame on this display. */
2166 FOR_EACH_FRAME (tail, frame)
2167 if (FRAME_NS_P (XFRAME (frame))
2168 && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
2169 XFRAME (frame)->mouse_moved = 0;
2171 dpyinfo->last_mouse_scroll_bar = nil;
2172 if (dpyinfo->last_mouse_frame
2173 && FRAME_LIVE_P (dpyinfo->last_mouse_frame))
2174 f = dpyinfo->last_mouse_frame;
2176 f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame : SELECTED_FRAME ();
2178 if (f && FRAME_NS_P (f))
2180 view = FRAME_NS_VIEW (*fp);
2182 position = [[view window] mouseLocationOutsideOfEventStream];
2183 position = [view convertPoint: position fromView: nil];
2184 remember_mouse_glyph (f, position.x, position.y,
2185 &dpyinfo->last_mouse_glyph);
2186 NSTRACE_POINT ("position", position);
2188 if (bar_window) *bar_window = Qnil;
2189 if (part) *part = scroll_bar_above_handle;
2191 if (x) XSETINT (*x, lrint (position.x));
2192 if (y) XSETINT (*y, lrint (position.y));
2194 *time = dpyinfo->last_mouse_movement_time;
2203 ns_frame_up_to_date (struct frame *f)
2204 /* --------------------------------------------------------------------------
2205 External (hook): Fix up mouse highlighting right after a full update.
2206 Can't use FRAME_MOUSE_UPDATE due to ns_frame_begin and ns_frame_end calls.
2207 -------------------------------------------------------------------------- */
2209 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_frame_up_to_date");
2213 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
2214 if (f == hlinfo->mouse_face_mouse_frame)
2218 note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
2219 hlinfo->mouse_face_mouse_x,
2220 hlinfo->mouse_face_mouse_y);
2229 ns_define_frame_cursor (struct frame *f, Cursor cursor)
2230 /* --------------------------------------------------------------------------
2231 External (RIF): set frame mouse pointer type.
2232 -------------------------------------------------------------------------- */
2234 NSTRACE ("ns_define_frame_cursor");
2235 if (FRAME_POINTER_TYPE (f) != cursor)
2237 EmacsView *view = FRAME_NS_VIEW (f);
2238 FRAME_POINTER_TYPE (f) = cursor;
2239 [[view window] invalidateCursorRectsForView: view];
2240 /* Redisplay assumes this function also draws the changed frame
2241 cursor, but this function doesn't, so do it explicitly. */
2242 x_update_cursor (f, 1);
2248 /* ==========================================================================
2252 ========================================================================== */
2256 ns_convert_key (unsigned code)
2257 /* --------------------------------------------------------------------------
2258 Internal call used by NSView-keyDown.
2259 -------------------------------------------------------------------------- */
2261 const unsigned last_keysym = ARRAYELTS (convert_ns_to_X_keysym);
2263 /* An array would be faster, but less easy to read. */
2264 for (keysym = 0; keysym < last_keysym; keysym += 2)
2265 if (code == convert_ns_to_X_keysym[keysym])
2266 return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
2268 /* if decide to use keyCode and Carbon table, use this line:
2269 return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
2274 x_get_keysym_name (int keysym)
2275 /* --------------------------------------------------------------------------
2276 Called by keyboard.c. Not sure if the return val is important, except
2278 -------------------------------------------------------------------------- */
2280 static char value[16];
2281 NSTRACE ("x_get_keysym_name");
2282 sprintf (value, "%d", keysym);
2288 /* ==========================================================================
2290 Block drawing operations
2292 ========================================================================== */
2296 ns_redraw_scroll_bars (struct frame *f)
2300 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
2301 NSTRACE ("ns_redraw_scroll_bars");
2302 for (i =[subviews count]-1; i >= 0; i--)
2304 view = [subviews objectAtIndex: i];
2305 if (![view isKindOfClass: [EmacsScroller class]]) continue;
2312 ns_clear_frame (struct frame *f)
2313 /* --------------------------------------------------------------------------
2314 External (hook): Erase the entire frame
2315 -------------------------------------------------------------------------- */
2317 NSView *view = FRAME_NS_VIEW (f);
2320 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_clear_frame");
2322 /* comes on initial frame because we have
2323 after-make-frame-functions = select-frame */
2324 if (!FRAME_DEFAULT_FACE (f))
2327 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2332 ns_focus (f, &r, 1);
2333 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
2337 /* as of 2006/11 or so this is now needed */
2338 ns_redraw_scroll_bars (f);
2344 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2345 /* --------------------------------------------------------------------------
2346 External (RIF): Clear section of frame
2347 -------------------------------------------------------------------------- */
2349 NSRect r = NSMakeRect (x, y, width, height);
2350 NSView *view = FRAME_NS_VIEW (f);
2351 struct face *face = FRAME_DEFAULT_FACE (f);
2356 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_clear_frame_area");
2358 r = NSIntersectionRect (r, [view frame]);
2359 ns_focus (f, &r, 1);
2360 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2369 ns_copy_bits (struct frame *f, NSRect src, NSRect dest)
2371 if (FRAME_NS_VIEW (f))
2373 hide_bell(); // Ensure the bell image isn't scrolled.
2375 ns_focus (f, &dest, 1);
2376 [FRAME_NS_VIEW (f) scrollRect: src
2377 by: NSMakeSize (dest.origin.x - src.origin.x,
2378 dest.origin.y - src.origin.y)];
2384 ns_scroll_run (struct window *w, struct run *run)
2385 /* --------------------------------------------------------------------------
2386 External (RIF): Insert or delete n lines at line vpos
2387 -------------------------------------------------------------------------- */
2389 struct frame *f = XFRAME (w->frame);
2390 int x, y, width, height, from_y, to_y, bottom_y;
2392 NSTRACE ("ns_scroll_run");
2394 /* begin copy from other terms */
2395 /* Get frame-relative bounding box of the text display area of W,
2396 without mode lines. Include in this box the left and right
2398 window_box (w, ANY_AREA, &x, &y, &width, &height);
2400 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2401 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2402 bottom_y = y + height;
2406 /* Scrolling up. Make sure we don't copy part of the mode
2407 line at the bottom. */
2408 if (from_y + run->height > bottom_y)
2409 height = bottom_y - from_y;
2411 height = run->height;
2415 /* Scrolling down. Make sure we don't copy over the mode line.
2417 if (to_y + run->height > bottom_y)
2418 height = bottom_y - to_y;
2420 height = run->height;
2422 /* end copy from other terms */
2432 NSRect srcRect = NSMakeRect (x, from_y, width, height);
2433 NSRect dstRect = NSMakeRect (x, to_y, width, height);
2435 ns_copy_bits (f, srcRect , dstRect);
2443 ns_after_update_window_line (struct window *w, struct glyph_row *desired_row)
2444 /* --------------------------------------------------------------------------
2445 External (RIF): preparatory to fringe update after text was updated
2446 -------------------------------------------------------------------------- */
2451 NSTRACE_WHEN (NSTRACE_GROUP_UPDATES, "ns_after_update_window_line");
2453 /* begin copy from other terms */
2456 if (!desired_row->mode_line_p && !w->pseudo_window_p)
2457 desired_row->redraw_fringe_bitmaps_p = 1;
2459 /* When a window has disappeared, make sure that no rest of
2460 full-width rows stays visible in the internal border. */
2461 if (windows_or_buffers_changed
2462 && desired_row->full_width_p
2463 && (f = XFRAME (w->frame),
2464 width = FRAME_INTERNAL_BORDER_WIDTH (f),
2466 && (height = desired_row->visible_height,
2469 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2472 ns_clear_frame_area (f, 0, y, width, height);
2473 ns_clear_frame_area (f,
2474 FRAME_PIXEL_WIDTH (f) - width,
2482 ns_shift_glyphs_for_insert (struct frame *f,
2483 int x, int y, int width, int height,
2485 /* --------------------------------------------------------------------------
2486 External (RIF): copy an area horizontally, don't worry about clearing src
2487 -------------------------------------------------------------------------- */
2489 NSRect srcRect = NSMakeRect (x, y, width, height);
2490 NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2492 NSTRACE ("ns_shift_glyphs_for_insert");
2494 ns_copy_bits (f, srcRect, dstRect);
2499 /* ==========================================================================
2501 Character encoding and metrics
2503 ========================================================================== */
2507 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2508 /* --------------------------------------------------------------------------
2509 External (RIF); compute left/right overhang of whole string and set in s
2510 -------------------------------------------------------------------------- */
2512 struct font *font = s->font;
2516 struct font_metrics metrics;
2517 unsigned int codes[2];
2518 codes[0] = *(s->char2b);
2519 codes[1] = *(s->char2b + s->nchars - 1);
2521 font->driver->text_extents (font, codes, 2, &metrics);
2522 s->left_overhang = -metrics.lbearing;
2524 = metrics.rbearing > metrics.width
2525 ? metrics.rbearing - metrics.width : 0;
2529 s->left_overhang = 0;
2530 if (EQ (font->driver->type, Qns))
2531 s->right_overhang = ((struct nsfont_info *)font)->ital ?
2532 FONT_HEIGHT (font) * 0.2 : 0;
2534 s->right_overhang = 0;
2540 /* ==========================================================================
2542 Fringe and cursor drawing
2544 ========================================================================== */
2547 extern int max_used_fringe_bitmap;
2549 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2550 struct draw_fringe_bitmap_params *p)
2551 /* --------------------------------------------------------------------------
2552 External (RIF); fringe-related
2553 -------------------------------------------------------------------------- */
2555 /* Fringe bitmaps comes in two variants, normal and periodic. A
2556 periodic bitmap is used to create a continuous pattern. Since a
2557 bitmap is rendered one text line at a time, the start offset (dh)
2558 of the bitmap varies. Concretely, this is used for the empty
2561 For a bitmap, "h + dh" is the full height and is always
2562 invariant. For a normal bitmap "dh" is zero.
2564 For example, when the period is three and the full height is 72
2565 the following combinations exists:
2571 struct frame *f = XFRAME (WINDOW_FRAME (w));
2572 struct face *face = p->face;
2573 static EmacsImage **bimgs = NULL;
2574 static int nBimgs = 0;
2576 NSTRACE_WHEN (NSTRACE_GROUP_FRINGE, "ns_draw_fringe_bitmap");
2577 NSTRACE_MSG ("which:%d cursor:%d overlay:%d width:%d height:%d period:%d",
2578 p->which, p->cursor_p, p->overlay_p, p->wd, p->h, p->dh);
2580 /* grow bimgs if needed */
2581 if (nBimgs < max_used_fringe_bitmap)
2583 bimgs = xrealloc (bimgs, max_used_fringe_bitmap * sizeof *bimgs);
2584 memset (bimgs + nBimgs, 0,
2585 (max_used_fringe_bitmap - nBimgs) * sizeof *bimgs);
2586 nBimgs = max_used_fringe_bitmap;
2589 /* Must clip because of partially visible lines. */
2590 ns_clip_to_row (w, row, ANY_AREA, YES);
2594 int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
2596 if (bx >= 0 && nx > 0)
2598 NSRect r = NSMakeRect (bx, by, nx, ny);
2600 [ns_lookup_indexed_color (face->background, f) set];
2607 NSRect r = NSMakeRect (p->x, p->y, p->wd, p->h);
2608 EmacsImage *img = bimgs[p->which - 1];
2612 // Note: For "periodic" images, allocate one EmacsImage for
2613 // the base image, and use it for all dh:s.
2614 unsigned short *bits = p->bits;
2615 int full_height = p->h + p->dh;
2617 unsigned char *cbits = xmalloc (full_height);
2619 for (i = 0; i < full_height; i++)
2621 img = [[EmacsImage alloc] initFromXBM: cbits width: 8
2624 bimgs[p->which - 1] = img;
2628 NSTRACE_RECT ("r", r);
2631 /* Since we composite the bitmap instead of just blitting it, we need
2632 to erase the whole background. */
2633 [ns_lookup_indexed_color(face->background, f) set];
2639 bm_color = ns_lookup_indexed_color(face->foreground, f);
2640 else if (p->overlay_p)
2641 bm_color = ns_lookup_indexed_color(face->background, f);
2643 bm_color = f->output_data.ns->cursor_color;
2644 [img setXBMColor: bm_color];
2647 #ifdef NS_IMPL_COCOA
2648 // Note: For periodic images, the full image height is "h + hd".
2649 // By using the height h, a suitable part of the image is used.
2650 NSRect fromRect = NSMakeRect(0, 0, p->wd, p->h);
2652 NSTRACE_RECT ("fromRect", fromRect);
2656 operation: NSCompositeSourceOver
2662 NSPoint pt = r.origin;
2664 [img compositeToPoint: pt operation: NSCompositeSourceOver];
2673 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2674 int x, int y, enum text_cursor_kinds cursor_type,
2675 int cursor_width, bool on_p, bool active_p)
2676 /* --------------------------------------------------------------------------
2677 External call (RIF): draw cursor.
2678 Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2679 -------------------------------------------------------------------------- */
2682 int fx, fy, h, cursor_height;
2683 struct frame *f = WINDOW_XFRAME (w);
2684 struct glyph *phys_cursor_glyph;
2685 struct glyph *cursor_glyph;
2687 NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2689 /* If cursor is out of bounds, don't draw garbage. This can happen
2690 in mini-buffer windows when switching between echo area glyphs
2693 NSTRACE ("ns_draw_window_cursor");
2698 w->phys_cursor_type = cursor_type;
2699 w->phys_cursor_on_p = on_p;
2701 if (cursor_type == NO_CURSOR)
2703 w->phys_cursor_width = 0;
2707 if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2709 if (glyph_row->exact_window_width_line_p
2710 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2712 glyph_row->cursor_in_fringe_p = 1;
2713 draw_fringe_bitmap (w, glyph_row, 0);
2718 /* We draw the cursor (with NSRectFill), then draw the glyph on top
2719 (other terminals do it the other way round). We must set
2720 w->phys_cursor_width to the cursor width. For bar cursors, that
2721 is CURSOR_WIDTH; for box cursors, it is the glyph width. */
2722 get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2724 /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2725 to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2726 if (cursor_type == BAR_CURSOR)
2728 if (cursor_width < 1)
2729 cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2730 w->phys_cursor_width = cursor_width;
2732 /* If we have an HBAR, "cursor_width" MAY specify height. */
2733 else if (cursor_type == HBAR_CURSOR)
2735 cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2736 if (cursor_height > glyph_row->height)
2737 cursor_height = glyph_row->height;
2738 if (h > cursor_height) // Cursor smaller than line height, move down
2739 fy += h - cursor_height;
2743 r.origin.x = fx, r.origin.y = fy;
2745 r.size.width = w->phys_cursor_width;
2747 /* TODO: only needed in rare cases with last-resort font in HELLO..
2748 should we do this more efficiently? */
2749 ns_clip_to_row (w, glyph_row, ANY_AREA, NO); /* do ns_focus(f, &r, 1); if remove */
2752 face = FACE_FROM_ID (f, phys_cursor_glyph->face_id);
2753 if (face && NS_FACE_BACKGROUND (face)
2754 == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2756 [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2757 hollow_color = FRAME_CURSOR_COLOR (f);
2760 [FRAME_CURSOR_COLOR (f) set];
2762 #ifdef NS_IMPL_COCOA
2763 /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2764 atomic. Cleaner ways of doing this should be investigated.
2765 One way would be to set a global variable DRAWING_CURSOR
2766 when making the call to draw_phys..(), don't focus in that
2767 case, then move the ns_unfocus() here after that call. */
2768 NSDisableScreenUpdates ();
2771 switch (cursor_type)
2773 case DEFAULT_CURSOR:
2776 case FILLED_BOX_CURSOR:
2779 case HOLLOW_BOX_CURSOR:
2782 NSRectFill (NSInsetRect (r, 1, 1));
2783 [FRAME_CURSOR_COLOR (f) set];
2790 /* If the character under cursor is R2L, draw the bar cursor
2791 on the right of its glyph, rather than on the left. */
2792 cursor_glyph = get_phys_cursor_glyph (w);
2793 if ((cursor_glyph->resolved_level & 1) != 0)
2794 s.origin.x += cursor_glyph->pixel_width - s.size.width;
2801 /* draw the character under the cursor */
2802 if (cursor_type != NO_CURSOR)
2803 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2805 #ifdef NS_IMPL_COCOA
2806 NSEnableScreenUpdates ();
2813 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2814 /* --------------------------------------------------------------------------
2815 External (RIF): Draw a vertical line.
2816 -------------------------------------------------------------------------- */
2818 struct frame *f = XFRAME (WINDOW_FRAME (w));
2820 NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2822 NSTRACE ("ns_draw_vertical_window_border");
2824 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2826 [ns_lookup_indexed_color(face->foreground, f) set];
2828 ns_focus (f, &r, 1);
2835 ns_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
2836 /* --------------------------------------------------------------------------
2837 External (RIF): Draw a window divider.
2838 -------------------------------------------------------------------------- */
2840 struct frame *f = XFRAME (WINDOW_FRAME (w));
2842 NSRect r = NSMakeRect (x0, y0, x1-x0, y1-y0);
2844 NSTRACE ("ns_draw_window_divider");
2846 face = FACE_FROM_ID (f, WINDOW_DIVIDER_FACE_ID);
2848 [ns_lookup_indexed_color(face->foreground, f) set];
2850 ns_focus (f, &r, 1);
2856 ns_show_hourglass (struct frame *f)
2858 /* TODO: add NSProgressIndicator to all frames. */
2862 ns_hide_hourglass (struct frame *f)
2864 /* TODO: remove NSProgressIndicator from all frames. */
2867 /* ==========================================================================
2869 Glyph drawing operations
2871 ========================================================================== */
2874 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2875 /* --------------------------------------------------------------------------
2876 Wrapper utility to account for internal border width on full-width lines,
2877 and allow top full-width rows to hit the frame top. nr should be pointer
2878 to two successive NSRects. Number of rects actually used is returned.
2879 -------------------------------------------------------------------------- */
2881 int n = get_glyph_string_clip_rects (s, nr, 2);
2885 /* --------------------------------------------------------------------
2886 Draw a wavy line under glyph string s. The wave fills wave_height
2893 wave_height = 3 | * * * *
2894 --------------------------------------------------------------------- */
2897 ns_draw_underwave (struct glyph_string *s, EmacsCGFloat width, EmacsCGFloat x)
2899 int wave_height = 3, wave_length = 2;
2900 int y, dx, dy, odd, xmax;
2905 dy = wave_height - 1;
2906 y = s->ybase - wave_height + 3;
2909 /* Find and set clipping rectangle */
2910 waveClip = NSMakeRect (x, y, width, wave_height);
2911 [[NSGraphicsContext currentContext] saveGraphicsState];
2912 NSRectClip (waveClip);
2914 /* Draw the waves */
2915 a.x = x - ((int)(x) % dx) + (EmacsCGFloat) 0.5;
2917 odd = (int)(a.x/dx) % 2;
2918 a.y = b.y = y + 0.5;
2927 [NSBezierPath strokeLineFromPoint:a toPoint:b];
2928 a.x = b.x, a.y = b.y;
2929 b.x += dx, b.y = y + 0.5 + odd*dy;
2933 /* Restore previous clipping rectangle(s) */
2934 [[NSGraphicsContext currentContext] restoreGraphicsState];
2940 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
2941 NSColor *defaultCol, CGFloat width, CGFloat x)
2942 /* --------------------------------------------------------------------------
2943 Draw underline, overline, and strike-through on glyph string s.
2944 -------------------------------------------------------------------------- */
2946 if (s->for_overlaps)
2950 if (face->underline_p)
2952 if (s->face->underline_type == FACE_UNDER_WAVE)
2954 if (face->underline_defaulted_p)
2957 [ns_lookup_indexed_color (face->underline_color, s->f) set];
2959 ns_draw_underwave (s, width, x);
2961 else if (s->face->underline_type == FACE_UNDER_LINE)
2965 unsigned long thickness, position;
2967 /* If the prev was underlined, match its appearance. */
2968 if (s->prev && s->prev->face->underline_p
2969 && s->prev->face->underline_type == FACE_UNDER_LINE
2970 && s->prev->underline_thickness > 0)
2972 thickness = s->prev->underline_thickness;
2973 position = s->prev->underline_position;
2978 unsigned long descent;
2981 descent = s->y + s->height - s->ybase;
2983 /* Use underline thickness of font, defaulting to 1. */
2984 thickness = (font && font->underline_thickness > 0)
2985 ? font->underline_thickness : 1;
2987 /* Determine the offset of underlining from the baseline. */
2988 if (x_underline_at_descent_line)
2989 position = descent - thickness;
2990 else if (x_use_underline_position_properties
2991 && font && font->underline_position >= 0)
2992 position = font->underline_position;
2994 position = lround (font->descent / 2);
2996 position = underline_minimum_offset;
2998 position = max (position, underline_minimum_offset);
3000 /* Ensure underlining is not cropped. */
3001 if (descent <= position)
3003 position = descent - 1;
3006 else if (descent < position + thickness)
3010 s->underline_thickness = thickness;
3011 s->underline_position = position;
3013 r = NSMakeRect (x, s->ybase + position, width, thickness);
3015 if (face->underline_defaulted_p)
3018 [ns_lookup_indexed_color (face->underline_color, s->f) set];
3022 /* Do overline. We follow other terms in using a thickness of 1
3023 and ignoring overline_margin. */
3024 if (face->overline_p)
3027 r = NSMakeRect (x, s->y, width, 1);
3029 if (face->overline_color_defaulted_p)
3032 [ns_lookup_indexed_color (face->overline_color, s->f) set];
3036 /* Do strike-through. We follow other terms for thickness and
3037 vertical position.*/
3038 if (face->strike_through_p)
3043 dy = lrint ((s->height - 1) / 2);
3044 r = NSMakeRect (x, s->y + dy, width, 1);
3046 if (face->strike_through_color_defaulted_p)
3049 [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
3055 ns_draw_box (NSRect r, CGFloat thickness, NSColor *col,
3056 char left_p, char right_p)
3057 /* --------------------------------------------------------------------------
3058 Draw an unfilled rect inside r, optionally leaving left and/or right open.
3059 Note we can't just use an NSDrawRect command, because of the possibility
3060 of some sides not being drawn, and because the rect will be filled.
3061 -------------------------------------------------------------------------- */
3067 s.size.height = thickness;
3069 s.origin.y += r.size.height - thickness;
3072 s.size.height = r.size.height;
3073 s.origin.y = r.origin.y;
3075 /* left, right (optional) */
3076 s.size.width = thickness;
3081 s.origin.x += r.size.width - thickness;
3088 ns_draw_relief (NSRect r, int thickness, char raised_p,
3089 char top_p, char bottom_p, char left_p, char right_p,
3090 struct glyph_string *s)
3091 /* --------------------------------------------------------------------------
3092 Draw a relief rect inside r, optionally leaving some sides open.
3093 Note we can't just use an NSDrawBezel command, because of the possibility
3094 of some sides not being drawn, and because the rect will be filled.
3095 -------------------------------------------------------------------------- */
3097 static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
3098 NSColor *newBaseCol = nil;
3101 NSTRACE ("ns_draw_relief");
3105 if (s->face->use_box_color_for_shadows_p)
3107 newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
3109 /* else if (s->first_glyph->type == IMAGE_GLYPH
3111 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
3113 newBaseCol = IMAGE_BACKGROUND (s->img, s->f, 0);
3117 newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
3120 if (newBaseCol == nil)
3121 newBaseCol = [NSColor grayColor];
3123 if (newBaseCol != baseCol) /* TODO: better check */
3126 baseCol = [newBaseCol retain];
3128 lightCol = [[baseCol highlightWithLevel: 0.2] retain];
3130 darkCol = [[baseCol shadowWithLevel: 0.3] retain];
3133 [(raised_p ? lightCol : darkCol) set];
3135 /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
3138 sr.size.height = thickness;
3139 if (top_p) NSRectFill (sr);
3142 sr.size.height = r.size.height;
3143 sr.size.width = thickness;
3144 if (left_p) NSRectFill (sr);
3146 [(raised_p ? darkCol : lightCol) set];
3149 sr.size.width = r.size.width;
3150 sr.size.height = thickness;
3151 sr.origin.y += r.size.height - thickness;
3152 if (bottom_p) NSRectFill (sr);
3155 sr.size.height = r.size.height;
3156 sr.origin.y = r.origin.y;
3157 sr.size.width = thickness;
3158 sr.origin.x += r.size.width - thickness;
3159 if (right_p) NSRectFill (sr);
3164 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
3165 /* --------------------------------------------------------------------------
3166 Function modeled after x_draw_glyph_string_box ().
3167 Sets up parameters for drawing.
3168 -------------------------------------------------------------------------- */
3170 int right_x, last_x;
3171 char left_p, right_p;
3172 struct glyph *last_glyph;
3177 if (s->hl == DRAW_MOUSE_FACE)
3179 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3181 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3186 thickness = face->box_line_width;
3188 NSTRACE ("ns_dumpglyphs_box_or_relief");
3190 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
3191 ? WINDOW_RIGHT_EDGE_X (s->w)
3192 : window_box_right (s->w, s->area));
3193 last_glyph = (s->cmp || s->img
3194 ? s->first_glyph : s->first_glyph + s->nchars-1);
3196 right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
3197 ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
3199 left_p = (s->first_glyph->left_box_line_p
3200 || (s->hl == DRAW_MOUSE_FACE
3201 && (s->prev == NULL || s->prev->hl != s->hl)));
3202 right_p = (last_glyph->right_box_line_p
3203 || (s->hl == DRAW_MOUSE_FACE
3204 && (s->next == NULL || s->next->hl != s->hl)));
3206 r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
3208 /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
3209 if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
3211 ns_draw_box (r, abs (thickness),
3212 ns_lookup_indexed_color (face->box_color, s->f),
3217 ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
3218 1, 1, left_p, right_p, s);
3224 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
3225 /* --------------------------------------------------------------------------
3226 Modeled after x_draw_glyph_string_background, which draws BG in
3227 certain cases. Others are left to the text rendering routine.
3228 -------------------------------------------------------------------------- */
3230 NSTRACE ("ns_maybe_dumpglyphs_background");
3232 if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
3234 int box_line_width = max (s->face->box_line_width, 0);
3235 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
3236 /* When xdisp.c ignores FONT_HEIGHT, we cannot trust font
3237 dimensions, since the actual glyphs might be much
3238 smaller. So in that case we always clear the rectangle
3239 with background color. */
3240 || FONT_TOO_HIGH (s->font)
3241 || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
3244 if (s->hl == DRAW_MOUSE_FACE)
3246 face = FACE_FROM_ID (s->f,
3247 MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3249 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3252 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3254 [(NS_FACE_BACKGROUND (face) != 0
3255 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
3256 : FRAME_BACKGROUND_COLOR (s->f)) set];
3259 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (s->f);
3260 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
3263 if (s->hl != DRAW_CURSOR)
3265 NSRect r = NSMakeRect (s->x, s->y + box_line_width,
3266 s->background_width,
3267 s->height-2*box_line_width);
3271 s->background_filled_p = 1;
3278 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
3279 /* --------------------------------------------------------------------------
3280 Renders an image and associated borders.
3281 -------------------------------------------------------------------------- */
3283 EmacsImage *img = s->img->pixmap;
3284 int box_line_vwidth = max (s->face->box_line_width, 0);
3285 int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
3286 int bg_x, bg_y, bg_height;
3293 NSTRACE ("ns_dumpglyphs_image");
3295 if (s->face->box != FACE_NO_BOX
3296 && s->first_glyph->left_box_line_p && s->slice.x == 0)
3297 x += abs (s->face->box_line_width);
3300 bg_y = s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
3301 bg_height = s->height;
3302 /* other terms have this, but was causing problems w/tabbar mode */
3303 /* - 2 * box_line_vwidth; */
3305 if (s->slice.x == 0) x += s->img->hmargin;
3306 if (s->slice.y == 0) y += s->img->vmargin;
3308 /* Draw BG: if we need larger area than image itself cleared, do that,
3309 otherwise, since we composite the image under NS (instead of mucking
3310 with its background color), we must clear just the image area. */
3311 if (s->hl == DRAW_MOUSE_FACE)
3313 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3315 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3318 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3320 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
3322 if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
3323 || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
3325 br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
3326 s->background_filled_p = 1;
3330 br = NSMakeRect (x, y, s->slice.width, s->slice.height);
3335 /* Draw the image.. do we need to draw placeholder if img ==nil? */
3338 #ifdef NS_IMPL_COCOA
3339 NSRect dr = NSMakeRect (x, y, s->slice.width, s->slice.height);
3340 NSRect ir = NSMakeRect (s->slice.x, s->slice.y,
3341 s->slice.width, s->slice.height);
3344 operation: NSCompositeSourceOver
3349 [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3350 operation: NSCompositeSourceOver];
3354 if (s->hl == DRAW_CURSOR)
3356 [FRAME_CURSOR_COLOR (s->f) set];
3357 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3358 tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3360 /* Currently on NS img->mask is always 0. Since
3361 get_window_cursor_type specifies a hollow box cursor when on
3362 a non-masked image we never reach this clause. But we put it
3363 in in anticipation of better support for image masks on
3365 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3369 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3372 /* Draw underline, overline, strike-through. */
3373 ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3375 /* Draw relief, if requested */
3376 if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3378 if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3380 th = tool_bar_button_relief >= 0 ?
3381 tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3382 raised_p = (s->hl == DRAW_IMAGE_RAISED);
3386 th = abs (s->img->relief);
3387 raised_p = (s->img->relief > 0);
3390 r.origin.x = x - th;
3391 r.origin.y = y - th;
3392 r.size.width = s->slice.width + 2*th-1;
3393 r.size.height = s->slice.height + 2*th-1;
3394 ns_draw_relief (r, th, raised_p,
3396 s->slice.y + s->slice.height == s->img->height,
3398 s->slice.x + s->slice.width == s->img->width, s);
3401 /* If there is no mask, the background won't be seen,
3402 so draw a rectangle on the image for the cursor.
3403 Do this for all images, getting transparency right is not reliable. */
3404 if (s->hl == DRAW_CURSOR)
3406 int thickness = abs (s->img->relief);
3407 if (thickness == 0) thickness = 1;
3408 ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3414 ns_dumpglyphs_stretch (struct glyph_string *s)
3419 NSColor *fgCol, *bgCol;
3421 if (!s->background_filled_p)
3423 n = ns_get_glyph_string_clip_rect (s, r);
3424 *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3426 ns_focus (s->f, r, n);
3428 if (s->hl == DRAW_MOUSE_FACE)
3430 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3432 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3435 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3437 bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3438 fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3440 for (i = 0; i < n; ++i)
3442 if (!s->row->full_width_p)
3444 int overrun, leftoverrun;
3446 /* truncate to avoid overwriting fringe and/or scrollbar */
3447 overrun = max (0, (s->x + s->background_width)
3448 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3449 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3450 r[i].size.width -= overrun;
3452 /* truncate to avoid overwriting to left of the window box */
3453 leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3454 + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3456 if (leftoverrun > 0)
3458 r[i].origin.x += leftoverrun;
3459 r[i].size.width -= leftoverrun;
3462 /* XXX: Try to work between problem where a stretch glyph on
3463 a partially-visible bottom row will clear part of the
3464 modeline, and another where list-buffers headers and similar
3465 rows erroneously have visible_height set to 0. Not sure
3466 where this is coming from as other terms seem not to show. */
3467 r[i].size.height = min (s->height, s->row->visible_height);
3472 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3473 overwriting cursor (usually when cursor on a tab) */
3474 if (s->hl == DRAW_CURSOR)
3479 width = s->w->phys_cursor_width;
3480 r[i].size.width -= width;
3481 r[i].origin.x += width;
3485 /* Draw overlining, etc. on the cursor. */
3486 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3487 ns_draw_text_decoration (s, face, bgCol, width, x);
3489 ns_draw_text_decoration (s, face, fgCol, width, x);
3496 /* Draw overlining, etc. on the stretch glyph (or the part
3497 of the stretch glyph after the cursor). */
3498 ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3502 s->background_filled_p = 1;
3508 ns_draw_composite_glyph_string_foreground (struct glyph_string *s)
3511 struct font *font = s->font;
3513 /* If first glyph of S has a left box line, start drawing the text
3514 of S to the right of that box line. */
3515 if (s->face && s->face->box != FACE_NO_BOX
3516 && s->first_glyph->left_box_line_p)
3517 x = s->x + eabs (s->face->box_line_width);
3521 /* S is a glyph string for a composition. S->cmp_from is the index
3522 of the first character drawn for glyphs of this composition.
3523 S->cmp_from == 0 means we are drawing the very first character of
3524 this composition. */
3526 /* Draw a rectangle for the composition if the font for the very
3527 first character of the composition could not be loaded. */
3528 if (s->font_not_found_p)
3530 if (s->cmp_from == 0)
3532 NSRect r = NSMakeRect (s->x, s->y, s->width-1, s->height -1);
3533 ns_draw_box (r, 1, FRAME_CURSOR_COLOR (s->f), 1, 1);
3536 else if (! s->first_glyph->u.cmp.automatic)
3540 for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
3541 /* TAB in a composition means display glyphs with padding
3542 space on the left or right. */
3543 if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
3545 int xx = x + s->cmp->offsets[j * 2];
3546 int yy = y - s->cmp->offsets[j * 2 + 1];
3548 font->driver->draw (s, j, j + 1, xx, yy, false);
3549 if (s->face->overstrike)
3550 font->driver->draw (s, j, j + 1, xx + 1, yy, false);
3555 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
3560 for (i = j = s->cmp_from; i < s->cmp_to; i++)
3562 glyph = LGSTRING_GLYPH (gstring, i);
3563 if (NILP (LGLYPH_ADJUSTMENT (glyph)))
3564 width += LGLYPH_WIDTH (glyph);
3567 int xoff, yoff, wadjust;
3571 font->driver->draw (s, j, i, x, y, false);
3572 if (s->face->overstrike)
3573 font->driver->draw (s, j, i, x + 1, y, false);
3576 xoff = LGLYPH_XOFF (glyph);
3577 yoff = LGLYPH_YOFF (glyph);
3578 wadjust = LGLYPH_WADJUST (glyph);
3579 font->driver->draw (s, i, i + 1, x + xoff, y + yoff, false);
3580 if (s->face->overstrike)
3581 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff,
3590 font->driver->draw (s, j, i, x, y, false);
3591 if (s->face->overstrike)
3592 font->driver->draw (s, j, i, x + 1, y, false);
3598 ns_draw_glyph_string (struct glyph_string *s)
3599 /* --------------------------------------------------------------------------
3600 External (RIF): Main draw-text call.
3601 -------------------------------------------------------------------------- */
3603 /* TODO (optimize): focus for box and contents draw */
3606 char box_drawn_p = 0;
3607 struct font *font = s->face->font;
3608 if (! font) font = FRAME_FONT (s->f);
3610 NSTRACE_WHEN (NSTRACE_GROUP_GLYPHS, "ns_draw_glyph_string");
3612 if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3615 struct glyph_string *next;
3617 for (width = 0, next = s->next;
3618 next && width < s->right_overhang;
3619 width += next->width, next = next->next)
3620 if (next->first_glyph->type != IMAGE_GLYPH)
3622 if (next->first_glyph->type != STRETCH_GLYPH)
3624 n = ns_get_glyph_string_clip_rect (s->next, r);
3625 ns_focus (s->f, r, n);
3626 ns_maybe_dumpglyphs_background (s->next, 1);
3631 ns_dumpglyphs_stretch (s->next);
3633 next->num_clips = 0;
3637 if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3638 && (s->first_glyph->type == CHAR_GLYPH
3639 || s->first_glyph->type == COMPOSITE_GLYPH))
3641 n = ns_get_glyph_string_clip_rect (s, r);
3642 ns_focus (s->f, r, n);
3643 ns_maybe_dumpglyphs_background (s, 1);
3644 ns_dumpglyphs_box_or_relief (s);
3649 switch (s->first_glyph->type)
3653 n = ns_get_glyph_string_clip_rect (s, r);
3654 ns_focus (s->f, r, n);
3655 ns_dumpglyphs_image (s, r[0]);
3660 ns_dumpglyphs_stretch (s);
3664 case COMPOSITE_GLYPH:
3665 n = ns_get_glyph_string_clip_rect (s, r);
3666 ns_focus (s->f, r, n);
3668 if (s->for_overlaps || (s->cmp_from > 0
3669 && ! s->first_glyph->u.cmp.automatic))
3670 s->background_filled_p = 1;
3672 ns_maybe_dumpglyphs_background
3673 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3675 flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3676 (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3677 (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3678 NS_DUMPGLYPH_NORMAL));
3680 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3682 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3683 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3684 NS_FACE_FOREGROUND (s->face) = tmp;
3688 BOOL isComposite = s->first_glyph->type == COMPOSITE_GLYPH;
3691 ns_draw_composite_glyph_string_foreground (s);
3694 (s, s->cmp_from, s->nchars, s->x, s->ybase,
3695 (flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3696 || flags == NS_DUMPGLYPH_MOUSEFACE);
3700 NSColor *col = (NS_FACE_FOREGROUND (s->face) != 0
3701 ? ns_lookup_indexed_color (NS_FACE_FOREGROUND (s->face),
3703 : FRAME_FOREGROUND_COLOR (s->f));
3706 /* Draw underline, overline, strike-through. */
3707 ns_draw_text_decoration (s, s->face, col, s->width, s->x);
3710 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3712 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3713 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3714 NS_FACE_FOREGROUND (s->face) = tmp;
3720 case GLYPHLESS_GLYPH:
3721 n = ns_get_glyph_string_clip_rect (s, r);
3722 ns_focus (s->f, r, n);
3724 if (s->for_overlaps || (s->cmp_from > 0
3725 && ! s->first_glyph->u.cmp.automatic))
3726 s->background_filled_p = 1;
3728 ns_maybe_dumpglyphs_background
3729 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3731 /* Not yet implemented. */
3740 /* Draw box if not done already. */
3741 if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3743 n = ns_get_glyph_string_clip_rect (s, r);
3744 ns_focus (s->f, r, n);
3745 ns_dumpglyphs_box_or_relief (s);
3754 /* ==========================================================================
3758 ========================================================================== */
3762 ns_send_appdefined (int value)
3763 /* --------------------------------------------------------------------------
3764 Internal: post an appdefined event which EmacsApp-sendEvent will
3765 recognize and take as a command to halt the event loop.
3766 -------------------------------------------------------------------------- */
3768 NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_send_appdefined(%d)", value);
3770 #ifdef NS_IMPL_GNUSTEP
3771 // GNUstep needs postEvent to happen on the main thread.
3772 if (! [[NSThread currentThread] isMainThread])
3774 EmacsApp *app = (EmacsApp *)NSApp;
3775 app->nextappdefined = value;
3776 [app performSelectorOnMainThread:@selector (sendFromMainThread:)
3783 /* Only post this event if we haven't already posted one. This will end
3784 the [NXApp run] main loop after having processed all events queued at
3787 #ifdef NS_IMPL_COCOA
3788 if (! send_appdefined)
3790 /* OSX 10.10.1 swallows the AppDefined event we are sending ourselves
3791 in certain situations (rapid incoming events).
3792 So check if we have one, if not add one. */
3793 NSEvent *appev = [NSApp nextEventMatchingMask:NSApplicationDefinedMask
3794 untilDate:[NSDate distantPast]
3795 inMode:NSDefaultRunLoopMode
3797 if (! appev) send_appdefined = YES;
3801 if (send_appdefined)
3805 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
3806 send_appdefined = NO;
3808 /* Don't need wakeup timer any more */
3811 [timed_entry invalidate];
3812 [timed_entry release];
3816 nxev = [NSEvent otherEventWithType: NSApplicationDefined
3817 location: NSMakePoint (0, 0)
3820 windowNumber: [[NSApp mainWindow] windowNumber]
3821 context: [NSApp context]
3826 /* Post an application defined event on the event queue. When this is
3827 received the [NXApp run] will return, thus having processed all
3828 events which are currently queued. */
3829 [NSApp postEvent: nxev atStart: NO];
3833 #ifdef HAVE_NATIVE_FS
3837 Lisp_Object frame, tail;
3839 if (ns_last_use_native_fullscreen == ns_use_native_fullscreen)
3842 ns_last_use_native_fullscreen = ns_use_native_fullscreen;
3844 FOR_EACH_FRAME (tail, frame)
3846 struct frame *f = XFRAME (frame);
3849 EmacsView *view = FRAME_NS_VIEW (f);
3850 [view updateCollectionBehavior];
3856 /* GNUstep does not have cancelTracking. */
3857 #ifdef NS_IMPL_COCOA
3858 /* Check if menu open should be canceled or continued as normal. */
3860 ns_check_menu_open (NSMenu *menu)
3862 /* Click in menu bar? */
3863 NSArray *a = [[NSApp mainMenu] itemArray];
3867 if (menu == nil) // Menu tracking ended.
3869 if (menu_will_open_state == MENU_OPENING)
3870 menu_will_open_state = MENU_NONE;
3874 for (i = 0; ! found && i < [a count]; i++)
3875 found = menu == [[a objectAtIndex:i] submenu];
3878 if (menu_will_open_state == MENU_NONE && emacs_event)
3880 NSEvent *theEvent = [NSApp currentEvent];
3881 struct frame *emacsframe = SELECTED_FRAME ();
3883 [menu cancelTracking];
3884 menu_will_open_state = MENU_PENDING;
3885 emacs_event->kind = MENU_BAR_ACTIVATE_EVENT;
3886 EV_TRAILER (theEvent);
3888 CGEventRef ourEvent = CGEventCreate (NULL);
3889 menu_mouse_point = CGEventGetLocation (ourEvent);
3890 CFRelease (ourEvent);
3892 else if (menu_will_open_state == MENU_OPENING)
3894 menu_will_open_state = MENU_NONE;
3899 /* Redo saved menu click if state is MENU_PENDING. */
3901 ns_check_pending_open_menu ()
3903 if (menu_will_open_state == MENU_PENDING)
3905 CGEventSourceRef source
3906 = CGEventSourceCreate (kCGEventSourceStateHIDSystemState);
3908 CGEventRef event = CGEventCreateMouseEvent (source,
3909 kCGEventLeftMouseDown,
3911 kCGMouseButtonLeft);
3912 CGEventSetType (event, kCGEventLeftMouseDown);
3913 CGEventPost (kCGHIDEventTap, event);
3917 menu_will_open_state = MENU_OPENING;
3920 #endif /* NS_IMPL_COCOA */
3923 unwind_apploopnr (Lisp_Object not_used)
3926 n_emacs_events_pending = 0;
3927 ns_finish_events ();
3932 ns_read_socket (struct terminal *terminal, struct input_event *hold_quit)
3933 /* --------------------------------------------------------------------------
3934 External (hook): Post an event to ourself and keep reading events until
3935 we read it back again. In effect process all events which were waiting.
3936 From 21+ we have to manage the event buffer ourselves.
3937 -------------------------------------------------------------------------- */
3939 struct input_event ev;
3942 NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_read_socket");
3944 #ifdef HAVE_NATIVE_FS
3948 if ([NSApp modalWindow] != nil)
3951 if (hold_event_q.nr > 0)
3954 for (i = 0; i < hold_event_q.nr; ++i)
3955 kbd_buffer_store_event_hold (&hold_event_q.q[i], hold_quit);
3956 hold_event_q.nr = 0;
3961 n_emacs_events_pending = 0;
3962 ns_init_events (&ev);
3963 q_event_ptr = hold_quit;
3965 /* we manage autorelease pools by allocate/reallocate each time around
3966 the loop; strict nesting is occasionally violated but seems not to
3967 matter.. earlier methods using full nesting caused major memory leaks */
3968 [outerpool release];
3969 outerpool = [[NSAutoreleasePool alloc] init];
3971 /* If have pending open-file requests, attend to the next one of those. */
3972 if (ns_pending_files && [ns_pending_files count] != 0
3973 && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3975 [ns_pending_files removeObjectAtIndex: 0];
3977 /* Deal with pending service requests. */
3978 else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3980 NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3981 withArg: [ns_pending_service_args objectAtIndex: 0]])
3983 [ns_pending_service_names removeObjectAtIndex: 0];
3984 [ns_pending_service_args removeObjectAtIndex: 0];
3988 ptrdiff_t specpdl_count = SPECPDL_INDEX ();
3989 /* Run and wait for events. We must always send one NX_APPDEFINED event
3990 to ourself, otherwise [NXApp run] will never exit. */
3991 send_appdefined = YES;
3992 ns_send_appdefined (-1);
3994 if (++apploopnr != 1)
3998 record_unwind_protect (unwind_apploopnr, Qt);
4000 unbind_to (specpdl_count, Qnil); /* calls unwind_apploopnr */
4003 nevents = n_emacs_events_pending;
4004 n_emacs_events_pending = 0;
4005 ns_finish_events ();
4014 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
4015 fd_set *exceptfds, struct timespec const *timeout,
4016 sigset_t const *sigmask)
4017 /* --------------------------------------------------------------------------
4018 Replacement for select, checking for events
4019 -------------------------------------------------------------------------- */
4023 struct input_event event;
4026 NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "ns_select");
4028 #ifdef HAVE_NATIVE_FS
4032 if (hold_event_q.nr > 0)
4034 /* We already have events pending. */
4040 for (k = 0; k < nfds+1; k++)
4042 if (readfds && FD_ISSET(k, readfds)) ++nr;
4043 if (writefds && FD_ISSET(k, writefds)) ++nr;
4047 || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0))
4048 return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
4050 [outerpool release];
4051 outerpool = [[NSAutoreleasePool alloc] init];
4054 send_appdefined = YES;
4057 pthread_mutex_lock (&select_mutex);
4062 select_readfds = *readfds;
4063 select_valid += SELECT_HAVE_READ;
4067 select_writefds = *writefds;
4068 select_valid += SELECT_HAVE_WRITE;
4073 select_timeout = *timeout;
4074 select_valid += SELECT_HAVE_TMO;
4077 pthread_mutex_unlock (&select_mutex);
4079 /* Inform fd_handler that select should be called */
4081 emacs_write_sig (selfds[1], &c, 1);
4083 else if (nr == 0 && timeout)
4085 /* No file descriptor, just a timeout, no need to wake fd_handler */
4086 double time = timespectod (*timeout);
4087 timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
4090 @selector (timeout_handler:)
4095 else /* No timeout and no file descriptors, can this happen? */
4097 /* Send appdefined so we exit from the loop */
4098 ns_send_appdefined (-1);
4102 ns_init_events (&event);
4103 if (++apploopnr != 1)
4109 ptrdiff_t specpdl_count = SPECPDL_INDEX ();
4110 record_unwind_protect (unwind_apploopnr, Qt);
4112 unbind_to (specpdl_count, Qnil); /* calls unwind_apploopnr */
4115 ns_finish_events ();
4116 if (nr > 0 && readfds)
4119 emacs_write_sig (selfds[1], &c, 1);
4123 t = last_appdefined_event_data;
4125 if (t != NO_APPDEFINED_DATA)
4127 last_appdefined_event_data = NO_APPDEFINED_DATA;
4131 /* The NX_APPDEFINED event we received was a timeout. */
4136 /* The NX_APPDEFINED event we received was the result of
4137 at least one real input event arriving. */
4143 /* Received back from select () in fd_handler; copy the results */
4144 pthread_mutex_lock (&select_mutex);
4145 if (readfds) *readfds = select_readfds;
4146 if (writefds) *writefds = select_writefds;
4147 pthread_mutex_unlock (&select_mutex);
4162 /* ==========================================================================
4166 ========================================================================== */
4170 ns_set_vertical_scroll_bar (struct window *window,
4171 int portion, int whole, int position)
4172 /* --------------------------------------------------------------------------
4173 External (hook): Update or add scrollbar
4174 -------------------------------------------------------------------------- */
4178 struct frame *f = XFRAME (WINDOW_FRAME (window));
4179 EmacsView *view = FRAME_NS_VIEW (f);
4181 int window_y, window_height;
4182 int top, left, height, width;
4183 BOOL update_p = YES;
4185 /* optimization; display engine sends WAY too many of these.. */
4186 if (!NILP (window->vertical_scroll_bar))
4188 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4189 if ([bar checkSamePosition: position portion: portion whole: whole])
4191 if (view->scrollbarsNeedingUpdate == 0)
4193 if (!windows_or_buffers_changed)
4197 view->scrollbarsNeedingUpdate--;
4202 NSTRACE ("ns_set_vertical_scroll_bar");
4204 /* Get dimensions. */
4205 window_box (window, ANY_AREA, 0, &window_y, 0, &window_height);
4207 height = window_height;
4208 width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
4209 left = WINDOW_SCROLL_BAR_AREA_X (window);
4211 r = NSMakeRect (left, top, width, height);
4212 /* the parent view is flipped, so we need to flip y value */
4214 r.origin.y = (v.size.height - r.size.height - r.origin.y);
4216 XSETWINDOW (win, window);
4219 /* we want at least 5 lines to display a scrollbar */
4220 if (WINDOW_TOTAL_LINES (window) < 5)
4222 if (!NILP (window->vertical_scroll_bar))
4224 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4225 [bar removeFromSuperview];
4226 wset_vertical_scroll_bar (window, Qnil);
4229 ns_clear_frame_area (f, left, top, width, height);
4234 if (NILP (window->vertical_scroll_bar))
4236 if (width > 0 && height > 0)
4237 ns_clear_frame_area (f, left, top, width, height);
4239 bar = [[EmacsScroller alloc] initFrame: r window: win];
4240 wset_vertical_scroll_bar (window, make_save_ptr (bar));
4246 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4247 oldRect = [bar frame];
4248 r.size.width = oldRect.size.width;
4249 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4251 if (oldRect.origin.x != r.origin.x)
4252 ns_clear_frame_area (f, left, top, width, height);
4258 [bar setPosition: position portion: portion whole: whole];
4264 ns_set_horizontal_scroll_bar (struct window *window,
4265 int portion, int whole, int position)
4266 /* --------------------------------------------------------------------------
4267 External (hook): Update or add scrollbar
4268 -------------------------------------------------------------------------- */
4272 struct frame *f = XFRAME (WINDOW_FRAME (window));
4273 EmacsView *view = FRAME_NS_VIEW (f);
4275 int top, height, left, width;
4276 int window_x, window_width;
4277 BOOL update_p = YES;
4279 /* optimization; display engine sends WAY too many of these.. */
4280 if (!NILP (window->horizontal_scroll_bar))
4282 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4283 if ([bar checkSamePosition: position portion: portion whole: whole])
4285 if (view->scrollbarsNeedingUpdate == 0)
4287 if (!windows_or_buffers_changed)
4291 view->scrollbarsNeedingUpdate--;
4296 NSTRACE ("ns_set_horizontal_scroll_bar");
4298 /* Get dimensions. */
4299 window_box (window, ANY_AREA, 0, &window_x, &window_width, 0);
4301 width = window_width;
4302 height = WINDOW_CONFIG_SCROLL_BAR_LINES (window) * FRAME_LINE_HEIGHT (f);
4303 top = WINDOW_SCROLL_BAR_AREA_Y (window);
4305 r = NSMakeRect (left, top, width, height);
4306 /* the parent view is flipped, so we need to flip y value */
4308 /* ??????? PXW/scrollbars !!!!!!!!!!!!!!!!!!!! */
4309 r.origin.y = (v.size.height - r.size.height - r.origin.y);
4311 XSETWINDOW (win, window);
4314 if (WINDOW_TOTAL_COLS (window) < 5)
4316 if (!NILP (window->horizontal_scroll_bar))
4318 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4319 [bar removeFromSuperview];
4320 wset_horizontal_scroll_bar (window, Qnil);
4322 ns_clear_frame_area (f, left, top, width, height);
4327 if (NILP (window->horizontal_scroll_bar))
4329 if (width > 0 && height > 0)
4330 ns_clear_frame_area (f, left, top, width, height);
4332 bar = [[EmacsScroller alloc] initFrame: r window: win];
4333 wset_horizontal_scroll_bar (window, make_save_ptr (bar));
4339 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4340 oldRect = [bar frame];
4341 r.size.width = oldRect.size.width;
4342 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4344 if (oldRect.origin.x != r.origin.x)
4345 ns_clear_frame_area (f, left, top, width, height);
4352 [bar setPosition: position portion: portion whole: whole];
4358 ns_condemn_scroll_bars (struct frame *f)
4359 /* --------------------------------------------------------------------------
4360 External (hook): arrange for all frame's scrollbars to be removed
4361 at next call to judge_scroll_bars, except for those redeemed.
4362 -------------------------------------------------------------------------- */
4366 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
4368 NSTRACE ("ns_condemn_scroll_bars");
4370 for (i =[subviews count]-1; i >= 0; i--)
4372 view = [subviews objectAtIndex: i];
4373 if ([view isKindOfClass: [EmacsScroller class]])
4380 ns_redeem_scroll_bar (struct window *window)
4381 /* --------------------------------------------------------------------------
4382 External (hook): arrange to spare this window's scrollbar
4383 at next call to judge_scroll_bars.
4384 -------------------------------------------------------------------------- */
4387 NSTRACE ("ns_redeem_scroll_bar");
4388 if (!NILP (window->vertical_scroll_bar))
4390 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4394 if (!NILP (window->horizontal_scroll_bar))
4396 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4403 ns_judge_scroll_bars (struct frame *f)
4404 /* --------------------------------------------------------------------------
4405 External (hook): destroy all scrollbars on frame that weren't
4406 redeemed after call to condemn_scroll_bars.
4407 -------------------------------------------------------------------------- */
4411 EmacsView *eview = FRAME_NS_VIEW (f);
4412 NSArray *subviews = [[eview superview] subviews];
4415 NSTRACE ("ns_judge_scroll_bars");
4416 for (i = [subviews count]-1; i >= 0; --i)
4418 view = [subviews objectAtIndex: i];
4419 if (![view isKindOfClass: [EmacsScroller class]]) continue;
4425 [eview updateFrameSize: NO];
4428 /* ==========================================================================
4432 ========================================================================== */
4435 x_display_pixel_height (struct ns_display_info *dpyinfo)
4437 NSArray *screens = [NSScreen screens];
4438 NSEnumerator *enumerator = [screens objectEnumerator];
4443 while ((screen = [enumerator nextObject]) != nil)
4444 frame = NSUnionRect (frame, [screen frame]);
4446 return NSHeight (frame);
4450 x_display_pixel_width (struct ns_display_info *dpyinfo)
4452 NSArray *screens = [NSScreen screens];
4453 NSEnumerator *enumerator = [screens objectEnumerator];
4458 while ((screen = [enumerator nextObject]) != nil)
4459 frame = NSUnionRect (frame, [screen frame]);
4461 return NSWidth (frame);
4465 static Lisp_Object ns_string_to_lispmod (const char *s)
4466 /* --------------------------------------------------------------------------
4467 Convert modifier name to lisp symbol
4468 -------------------------------------------------------------------------- */
4470 if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
4472 else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
4474 else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
4476 else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
4478 else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
4480 else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
4488 ns_default (const char *parameter, Lisp_Object *result,
4489 Lisp_Object yesval, Lisp_Object noval,
4490 BOOL is_float, BOOL is_modstring)
4491 /* --------------------------------------------------------------------------
4492 Check a parameter value in user's preferences
4493 -------------------------------------------------------------------------- */
4495 const char *value = ns_get_defaults_value (parameter);
4501 if (c_strcasecmp (value, "YES") == 0)
4503 else if (c_strcasecmp (value, "NO") == 0)
4505 else if (is_float && (f = strtod (value, &pos), pos != value))
4506 *result = make_float (f);
4507 else if (is_modstring && value)
4508 *result = ns_string_to_lispmod (value);
4509 else fprintf (stderr,
4510 "Bad value for default \"%s\": \"%s\"\n", parameter, value);
4516 ns_initialize_display_info (struct ns_display_info *dpyinfo)
4517 /* --------------------------------------------------------------------------
4518 Initialize global info and storage for display.
4519 -------------------------------------------------------------------------- */
4521 NSScreen *screen = [NSScreen mainScreen];
4522 NSWindowDepth depth = [screen depth];
4524 dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
4525 dpyinfo->resy = 72.27;
4526 dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
4527 NSColorSpaceFromDepth (depth)]
4528 && ![NSCalibratedWhiteColorSpace isEqualToString:
4529 NSColorSpaceFromDepth (depth)];
4530 dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
4531 dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
4532 dpyinfo->color_table->colors = NULL;
4533 dpyinfo->root_window = 42; /* a placeholder.. */
4534 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
4535 dpyinfo->n_fonts = 0;
4536 dpyinfo->smallest_font_height = 1;
4537 dpyinfo->smallest_char_width = 1;
4539 reset_mouse_highlight (&dpyinfo->mouse_highlight);
4543 /* This and next define (many of the) public functions in this file. */
4544 /* x_... are generic versions in xdisp.c that we, and other terms, get away
4545 with using despite presence in the "system dependent" redisplay
4546 interface. In addition, many of the ns_ methods have code that is
4547 shared with all terms, indicating need for further refactoring. */
4548 extern frame_parm_handler ns_frame_parm_handlers[];
4549 static struct redisplay_interface ns_redisplay_interface =
4551 ns_frame_parm_handlers,
4555 x_clear_end_of_line,
4557 ns_after_update_window_line,
4558 ns_update_window_begin,
4559 ns_update_window_end,
4560 0, /* flush_display */
4561 x_clear_window_mouse_face,
4562 x_get_glyph_overhangs,
4563 x_fix_overlapping_area,
4564 ns_draw_fringe_bitmap,
4565 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
4566 0, /* destroy_fringe_bitmap */
4567 ns_compute_glyph_string_overhangs,
4568 ns_draw_glyph_string,
4569 ns_define_frame_cursor,
4570 ns_clear_frame_area,
4571 ns_draw_window_cursor,
4572 ns_draw_vertical_window_border,
4573 ns_draw_window_divider,
4574 ns_shift_glyphs_for_insert,
4581 ns_delete_display (struct ns_display_info *dpyinfo)
4587 /* This function is called when the last frame on a display is deleted. */
4589 ns_delete_terminal (struct terminal *terminal)
4591 struct ns_display_info *dpyinfo = terminal->display_info.ns;
4593 NSTRACE ("ns_delete_terminal");
4595 /* Protect against recursive calls. delete_frame in
4596 delete_terminal calls us back when it deletes our last frame. */
4597 if (!terminal->name)
4602 x_destroy_all_bitmaps (dpyinfo);
4603 ns_delete_display (dpyinfo);
4608 static struct terminal *
4609 ns_create_terminal (struct ns_display_info *dpyinfo)
4610 /* --------------------------------------------------------------------------
4611 Set up use of NS before we make the first connection.
4612 -------------------------------------------------------------------------- */
4614 struct terminal *terminal;
4616 NSTRACE ("ns_create_terminal");
4618 terminal = create_terminal (output_ns, &ns_redisplay_interface);
4620 terminal->display_info.ns = dpyinfo;
4621 dpyinfo->terminal = terminal;
4623 terminal->clear_frame_hook = ns_clear_frame;
4624 terminal->ring_bell_hook = ns_ring_bell;
4625 terminal->update_begin_hook = ns_update_begin;
4626 terminal->update_end_hook = ns_update_end;
4627 terminal->read_socket_hook = ns_read_socket;
4628 terminal->frame_up_to_date_hook = ns_frame_up_to_date;
4629 terminal->mouse_position_hook = ns_mouse_position;
4630 terminal->frame_rehighlight_hook = ns_frame_rehighlight;
4631 terminal->frame_raise_lower_hook = ns_frame_raise_lower;
4632 terminal->fullscreen_hook = ns_fullscreen_hook;
4633 terminal->menu_show_hook = ns_menu_show;
4634 terminal->popup_dialog_hook = ns_popup_dialog;
4635 terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
4636 terminal->set_horizontal_scroll_bar_hook = ns_set_horizontal_scroll_bar;
4637 terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
4638 terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
4639 terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
4640 terminal->delete_frame_hook = x_destroy_window;
4641 terminal->delete_terminal_hook = ns_delete_terminal;
4642 /* Other hooks are NULL by default. */
4648 struct ns_display_info *
4649 ns_term_init (Lisp_Object display_name)
4650 /* --------------------------------------------------------------------------
4651 Start the Application and get things rolling.
4652 -------------------------------------------------------------------------- */
4654 struct terminal *terminal;
4655 struct ns_display_info *dpyinfo;
4656 static int ns_initialized = 0;
4659 if (ns_initialized) return x_display_list;
4664 NSTRACE ("ns_term_init");
4666 [outerpool release];
4667 outerpool = [[NSAutoreleasePool alloc] init];
4669 /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4670 /*GSDebugAllocationActive (YES); */
4674 Fset_input_interrupt_mode (Qnil);
4676 if (selfds[0] == -1)
4678 if (emacs_pipe (selfds) != 0)
4680 fprintf (stderr, "Failed to create pipe: %s\n",
4681 emacs_strerror (errno));
4685 fcntl (selfds[0], F_SETFL, O_NONBLOCK|fcntl (selfds[0], F_GETFL));
4686 FD_ZERO (&select_readfds);
4687 FD_ZERO (&select_writefds);
4688 pthread_mutex_init (&select_mutex, NULL);
4691 ns_pending_files = [[NSMutableArray alloc] init];
4692 ns_pending_service_names = [[NSMutableArray alloc] init];
4693 ns_pending_service_args = [[NSMutableArray alloc] init];
4695 /* Start app and create the main menu, window, view.
4696 Needs to be here because ns_initialize_display_info () uses AppKit classes.
4697 The view will then ask the NSApp to stop and return to Emacs. */
4698 [EmacsApp sharedApplication];
4701 [NSApp setDelegate: NSApp];
4703 /* Start the select thread. */
4704 [NSThread detachNewThreadSelector:@selector (fd_handler:)
4708 /* debugging: log all notifications */
4709 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
4710 selector: @selector (logNotification:)
4711 name: nil object: nil]; */
4713 dpyinfo = xzalloc (sizeof *dpyinfo);
4715 ns_initialize_display_info (dpyinfo);
4716 terminal = ns_create_terminal (dpyinfo);
4718 terminal->kboard = allocate_kboard (Qns);
4719 /* Don't let the initial kboard remain current longer than necessary.
4720 That would cause problems if a file loaded on startup tries to
4721 prompt in the mini-buffer. */
4722 if (current_kboard == initial_kboard)
4723 current_kboard = terminal->kboard;
4724 terminal->kboard->reference_count++;
4726 dpyinfo->next = x_display_list;
4727 x_display_list = dpyinfo;
4729 dpyinfo->name_list_element = Fcons (display_name, Qnil);
4731 terminal->name = xlispstrdup (display_name);
4735 if (!inhibit_x_resources)
4737 ns_default ("GSFontAntiAlias", &ns_antialias_text,
4740 /* this is a standard variable */
4741 ns_default ("AppleAntiAliasingThreshold", &tmp,
4742 make_float (10.0), make_float (6.0), YES, NO);
4743 ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4746 NSTRACE_MSG ("Colors");
4749 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4753 Lisp_Object color_file, color_map, color;
4757 color_file = Fexpand_file_name (build_string ("rgb.txt"),
4758 Fsymbol_value (intern ("data-directory")));
4760 color_map = Fx_load_color_file (color_file);
4761 if (NILP (color_map))
4762 fatal ("Could not read %s.\n", SDATA (color_file));
4764 cl = [[NSColorList alloc] initWithName: @"Emacs"];
4765 for ( ; CONSP (color_map); color_map = XCDR (color_map))
4767 color = XCAR (color_map);
4768 name = SSDATA (XCAR (color));
4769 c = XINT (XCDR (color));
4771 [NSColor colorForEmacsRed: RED_FROM_ULONG (c) / 255.0
4772 green: GREEN_FROM_ULONG (c) / 255.0
4773 blue: BLUE_FROM_ULONG (c) / 255.0
4775 forKey: [NSString stringWithUTF8String: name]];
4777 [cl writeToFile: nil];
4781 NSTRACE_MSG ("Versions");
4784 #ifdef NS_IMPL_GNUSTEP
4785 Vwindow_system_version = build_string (gnustep_base_version);
4787 /*PSnextrelease (128, c); */
4788 char c[DBL_BUFSIZE_BOUND];
4789 int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4790 Vwindow_system_version = make_unibyte_string (c, len);
4794 delete_keyboard_wait_descriptor (0);
4796 ns_app_name = [[NSProcessInfo processInfo] processName];
4798 /* Set up OS X app menu */
4800 NSTRACE_MSG ("Menu init");
4802 #ifdef NS_IMPL_COCOA
4806 /* set up the application menu */
4807 svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4808 [svcsMenu setAutoenablesItems: NO];
4809 appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4810 [appMenu setAutoenablesItems: NO];
4811 mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4812 dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4814 [appMenu insertItemWithTitle: @"About Emacs"
4815 action: @selector (orderFrontStandardAboutPanel:)
4818 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4819 [appMenu insertItemWithTitle: @"Preferences..."
4820 action: @selector (showPreferencesWindow:)
4823 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4824 item = [appMenu insertItemWithTitle: @"Services"
4825 action: @selector (menuDown:)
4828 [appMenu setSubmenu: svcsMenu forItem: item];
4829 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4830 [appMenu insertItemWithTitle: @"Hide Emacs"
4831 action: @selector (hide:)
4834 item = [appMenu insertItemWithTitle: @"Hide Others"
4835 action: @selector (hideOtherApplications:)
4838 [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4839 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4840 [appMenu insertItemWithTitle: @"Quit Emacs"
4841 action: @selector (terminate:)
4845 item = [mainMenu insertItemWithTitle: ns_app_name
4846 action: @selector (menuDown:)
4849 [mainMenu setSubmenu: appMenu forItem: item];
4850 [dockMenu insertItemWithTitle: @"New Frame"
4851 action: @selector (newFrame:)
4855 [NSApp setMainMenu: mainMenu];
4856 [NSApp setAppleMenu: appMenu];
4857 [NSApp setServicesMenu: svcsMenu];
4858 /* Needed at least on Cocoa, to get dock menu to show windows */
4859 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4861 [[NSNotificationCenter defaultCenter]
4862 addObserver: mainMenu
4863 selector: @selector (trackingNotification:)
4864 name: NSMenuDidBeginTrackingNotification object: mainMenu];
4865 [[NSNotificationCenter defaultCenter]
4866 addObserver: mainMenu
4867 selector: @selector (trackingNotification:)
4868 name: NSMenuDidEndTrackingNotification object: mainMenu];
4870 #endif /* MAC OS X menu setup */
4872 /* Register our external input/output types, used for determining
4873 applicable services and also drag/drop eligibility. */
4875 NSTRACE_MSG ("Input/output types");
4877 ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
4878 ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
4880 ns_drag_types = [[NSArray arrayWithObjects:
4882 NSTabularTextPboardType,
4883 NSFilenamesPboardType,
4884 NSURLPboardType, nil] retain];
4886 /* If fullscreen is in init/default-frame-alist, focus isn't set
4887 right for fullscreen windows, so set this. */
4888 [NSApp activateIgnoringOtherApps:YES];
4890 NSTRACE_MSG ("Call NSApp run");
4893 ns_do_open_file = YES;
4895 #ifdef NS_IMPL_GNUSTEP
4896 /* GNUstep steals SIGCHLD for use in NSTask, but we don't use NSTask.
4897 We must re-catch it so subprocess works. */
4898 catch_child_signal ();
4901 NSTRACE_MSG ("ns_term_init done");
4910 ns_term_shutdown (int sig)
4912 [[NSUserDefaults standardUserDefaults] synchronize];
4914 /* code not reached in emacs.c after this is called by shut_down_emacs: */
4915 if (STRINGP (Vauto_save_list_file_name))
4916 unlink (SSDATA (Vauto_save_list_file_name));
4918 if (sig == 0 || sig == SIGTERM)
4920 [NSApp terminate: NSApp];
4922 else // force a stack trace to happen
4929 /* ==========================================================================
4931 EmacsApp implementation
4933 ========================================================================== */
4936 @implementation EmacsApp
4940 NSTRACE ("[EmacsApp init]");
4942 if ((self = [super init]))
4944 #ifdef NS_IMPL_COCOA
4945 self->isFirst = YES;
4947 #ifdef NS_IMPL_GNUSTEP
4948 self->applicationDidFinishLaunchingCalled = NO;
4955 #ifdef NS_IMPL_COCOA
4958 NSTRACE ("[EmacsApp run]");
4960 #ifndef NSAppKitVersionNumber10_9
4961 #define NSAppKitVersionNumber10_9 1265
4964 if ((int)NSAppKitVersionNumber != NSAppKitVersionNumber10_9)
4970 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
4972 if (isFirst) [self finishLaunching];
4975 shouldKeepRunning = YES;
4979 pool = [[NSAutoreleasePool alloc] init];
4982 [self nextEventMatchingMask:NSAnyEventMask
4983 untilDate:[NSDate distantFuture]
4984 inMode:NSDefaultRunLoopMode
4987 [self sendEvent:event];
4988 [self updateWindows];
4989 } while (shouldKeepRunning);
4994 - (void)stop: (id)sender
4996 NSTRACE ("[EmacsApp stop:]");
4998 shouldKeepRunning = NO;
4999 // Stop possible dialog also. Noop if no dialog present.
5000 // The file dialog still leaks 7k - 10k on 10.9 though.
5001 [super stop:sender];
5003 #endif /* NS_IMPL_COCOA */
5005 - (void)logNotification: (NSNotification *)notification
5007 NSTRACE ("[EmacsApp logNotification:]");
5009 const char *name = [[notification name] UTF8String];
5010 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
5011 && !strstr (name, "WindowNumber"))
5012 NSLog (@"notification: '%@'", [notification name]);
5016 - (void)sendEvent: (NSEvent *)theEvent
5017 /* --------------------------------------------------------------------------
5018 Called when NSApp is running for each event received. Used to stop
5019 the loop when we choose, since there's no way to just run one iteration.
5020 -------------------------------------------------------------------------- */
5022 int type = [theEvent type];
5023 NSWindow *window = [theEvent window];
5025 NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "[EmacsApp sendEvent:]");
5026 NSTRACE_MSG ("Type: %d", type);
5028 #ifdef NS_IMPL_GNUSTEP
5029 // Keyboard events aren't propagated to file dialogs for some reason.
5030 if ([NSApp modalWindow] != nil &&
5031 (type == NSKeyDown || type == NSKeyUp || type == NSFlagsChanged))
5033 [[NSApp modalWindow] sendEvent: theEvent];
5038 if (represented_filename != nil && represented_frame)
5040 NSString *fstr = represented_filename;
5041 NSView *view = FRAME_NS_VIEW (represented_frame);
5042 #ifdef NS_IMPL_COCOA
5043 /* work around a bug observed on 10.3 and later where
5044 setTitleWithRepresentedFilename does not clear out previous state
5045 if given filename does not exist */
5046 if (! [[NSFileManager defaultManager] fileExistsAtPath: fstr])
5047 [[view window] setRepresentedFilename: @""];
5049 [[view window] setRepresentedFilename: fstr];
5050 [represented_filename release];
5051 represented_filename = nil;
5052 represented_frame = NULL;
5055 if (type == NSApplicationDefined)
5057 switch ([theEvent data2])
5059 #ifdef NS_IMPL_COCOA
5060 case NSAPP_DATA2_RUNASSCRIPT:
5065 case NSAPP_DATA2_RUNFILEDIALOG:
5066 ns_run_file_dialog ();
5072 if (type == NSCursorUpdate && window == nil)
5074 fprintf (stderr, "Dropping external cursor update event.\n");
5078 if (type == NSApplicationDefined)
5080 /* Events posted by ns_send_appdefined interrupt the run loop here.
5081 But, if a modal window is up, an appdefined can still come through,
5082 (e.g., from a makeKeyWindow event) but stopping self also stops the
5083 modal loop. Just defer it until later. */
5084 if ([NSApp modalWindow] == nil)
5086 last_appdefined_event_data = [theEvent data1];
5091 send_appdefined = YES;
5096 #ifdef NS_IMPL_COCOA
5097 /* If no dialog and none of our frames have focus and it is a move, skip it.
5098 It is a mouse move in an auxiliary menu, i.e. on the top right on OSX,
5099 such as Wifi, sound, date or similar.
5100 This prevents "spooky" highlighting in the frame under the menu. */
5101 if (type == NSMouseMoved && [NSApp modalWindow] == nil)
5103 struct ns_display_info *di;
5104 BOOL has_focus = NO;
5105 for (di = x_display_list; ! has_focus && di; di = di->next)
5106 has_focus = di->x_focus_frame != 0;
5112 NSTRACE_UNSILENCE();
5114 [super sendEvent: theEvent];
5118 - (void)showPreferencesWindow: (id)sender
5120 struct frame *emacsframe = SELECTED_FRAME ();
5121 NSEvent *theEvent = [NSApp currentEvent];
5125 emacs_event->kind = NS_NONKEY_EVENT;
5126 emacs_event->code = KEY_NS_SHOW_PREFS;
5127 emacs_event->modifiers = 0;
5128 EV_TRAILER (theEvent);
5132 - (void)newFrame: (id)sender
5134 NSTRACE ("[EmacsApp newFrame:]");
5136 struct frame *emacsframe = SELECTED_FRAME ();
5137 NSEvent *theEvent = [NSApp currentEvent];
5141 emacs_event->kind = NS_NONKEY_EVENT;
5142 emacs_event->code = KEY_NS_NEW_FRAME;
5143 emacs_event->modifiers = 0;
5144 EV_TRAILER (theEvent);
5148 /* Open a file (used by below, after going into queue read by ns_read_socket) */
5149 - (BOOL) openFile: (NSString *)fileName
5151 NSTRACE ("[EmacsApp openFile:]");
5153 struct frame *emacsframe = SELECTED_FRAME ();
5154 NSEvent *theEvent = [NSApp currentEvent];
5159 emacs_event->kind = NS_NONKEY_EVENT;
5160 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
5161 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
5162 ns_input_line = Qnil; /* can be start or cons start,end */
5163 emacs_event->modifiers =0;
5164 EV_TRAILER (theEvent);
5170 /* **************************************************************************
5172 EmacsApp delegate implementation
5174 ************************************************************************** */
5176 - (void)applicationDidFinishLaunching: (NSNotification *)notification
5177 /* --------------------------------------------------------------------------
5178 When application is loaded, terminate event loop in ns_term_init
5179 -------------------------------------------------------------------------- */
5181 NSTRACE ("[EmacsApp applicationDidFinishLaunching:]");
5183 #ifdef NS_IMPL_GNUSTEP
5184 ((EmacsApp *)self)->applicationDidFinishLaunchingCalled = YES;
5186 [NSApp setServicesProvider: NSApp];
5188 [self antialiasThresholdDidChange:nil];
5189 #ifdef NS_IMPL_COCOA
5190 [[NSNotificationCenter defaultCenter]
5192 selector:@selector(antialiasThresholdDidChange:)
5193 name:NSAntialiasThresholdChangedNotification
5197 ns_send_appdefined (-2);
5200 - (void)antialiasThresholdDidChange:(NSNotification *)notification
5202 #ifdef NS_IMPL_COCOA
5203 macfont_update_antialias_threshold ();
5208 /* Termination sequences:
5211 MenuBar | File | Exit:
5212 Select Quit from App menubar:
5214 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5217 Select Quit from Dock menu:
5220 Cancel -> Nothing else
5224 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
5229 - (void) terminate: (id)sender
5231 NSTRACE ("[EmacsApp terminate:]");
5233 struct frame *emacsframe = SELECTED_FRAME ();
5238 emacs_event->kind = NS_NONKEY_EVENT;
5239 emacs_event->code = KEY_NS_POWER_OFF;
5240 emacs_event->arg = Qt; /* mark as non-key event */
5241 EV_TRAILER ((id)nil);
5245 runAlertPanel(NSString *title,
5246 NSString *msgFormat,
5247 NSString *defaultButton,
5248 NSString *alternateButton)
5250 #if !defined (NS_IMPL_COCOA) || \
5251 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
5252 return NSRunAlertPanel(title, msgFormat, defaultButton, alternateButton, nil)
5253 == NSAlertDefaultReturn;
5255 NSAlert *alert = [[NSAlert alloc] init];
5256 [alert setAlertStyle: NSCriticalAlertStyle];
5257 [alert setMessageText: msgFormat];
5258 [alert addButtonWithTitle: defaultButton];
5259 [alert addButtonWithTitle: alternateButton];
5260 NSInteger ret = [alert runModal];
5262 return ret == NSAlertFirstButtonReturn;
5267 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
5269 NSTRACE ("[EmacsApp applicationShouldTerminate:]");
5273 if (NILP (ns_confirm_quit)) // || ns_shutdown_properly --> TO DO
5274 return NSTerminateNow;
5276 ret = runAlertPanel(ns_app_name,
5277 @"Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?",
5278 @"Save Buffers and Exit", @"Cancel");
5281 return NSTerminateNow;
5283 return NSTerminateCancel;
5284 return NSTerminateNow; /* just in case */
5288 not_in_argv (NSString *arg)
5291 const char *a = [arg UTF8String];
5292 for (k = 1; k < initial_argc; ++k)
5293 if (strcmp (a, initial_argv[k]) == 0) return 0;
5297 /* Notification from the Workspace to open a file */
5298 - (BOOL)application: sender openFile: (NSString *)file
5300 if (ns_do_open_file || not_in_argv (file))
5301 [ns_pending_files addObject: file];
5306 /* Open a file as a temporary file */
5307 - (BOOL)application: sender openTempFile: (NSString *)file
5309 if (ns_do_open_file || not_in_argv (file))
5310 [ns_pending_files addObject: file];
5315 /* Notification from the Workspace to open a file noninteractively (?) */
5316 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
5318 if (ns_do_open_file || not_in_argv (file))
5319 [ns_pending_files addObject: file];
5323 /* Notification from the Workspace to open multiple files */
5324 - (void)application: sender openFiles: (NSArray *)fileList
5326 NSEnumerator *files = [fileList objectEnumerator];
5328 /* Don't open files from the command line unconditionally,
5329 Cocoa parses the command line wrong, --option value tries to open value
5330 if --option is the last option. */
5331 while ((file = [files nextObject]) != nil)
5332 if (ns_do_open_file || not_in_argv (file))
5333 [ns_pending_files addObject: file];
5335 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
5340 /* Handle dock menu requests. */
5341 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
5347 /* TODO: these may help w/IO switching btwn terminal and NSApp */
5348 - (void)applicationWillBecomeActive: (NSNotification *)notification
5350 NSTRACE ("[EmacsApp applicationWillBecomeActive:]");
5351 //ns_app_active=YES;
5354 - (void)applicationDidBecomeActive: (NSNotification *)notification
5356 NSTRACE ("[EmacsApp applicationDidBecomeActive:]");
5358 #ifdef NS_IMPL_GNUSTEP
5359 if (! applicationDidFinishLaunchingCalled)
5360 [self applicationDidFinishLaunching:notification];
5362 //ns_app_active=YES;
5364 ns_update_auto_hide_menu_bar ();
5365 // No constraining takes place when the application is not active.
5366 ns_constrain_all_frames ();
5368 - (void)applicationDidResignActive: (NSNotification *)notification
5370 NSTRACE ("[EmacsApp applicationDidResignActive:]");
5373 ns_send_appdefined (-1);
5378 /* ==========================================================================
5380 EmacsApp aux handlers for managing event loop
5382 ========================================================================== */
5385 - (void)timeout_handler: (NSTimer *)timedEntry
5386 /* --------------------------------------------------------------------------
5387 The timeout specified to ns_select has passed.
5388 -------------------------------------------------------------------------- */
5390 /*NSTRACE ("timeout_handler"); */
5391 ns_send_appdefined (-2);
5394 #ifdef NS_IMPL_GNUSTEP
5395 - (void)sendFromMainThread:(id)unused
5397 ns_send_appdefined (nextappdefined);
5401 - (void)fd_handler:(id)unused
5402 /* --------------------------------------------------------------------------
5403 Check data waiting on file descriptors and terminate if so
5404 -------------------------------------------------------------------------- */
5407 int waiting = 1, nfds;
5410 fd_set readfds, writefds, *wfds;
5411 struct timespec timeout, *tmo;
5412 NSAutoreleasePool *pool = nil;
5414 /* NSTRACE ("fd_handler"); */
5419 pool = [[NSAutoreleasePool alloc] init];
5425 FD_SET (selfds[0], &fds);
5426 result = select (selfds[0]+1, &fds, NULL, NULL, NULL);
5427 if (result > 0 && read (selfds[0], &c, 1) == 1 && c == 'g')
5432 pthread_mutex_lock (&select_mutex);
5435 if (select_valid & SELECT_HAVE_READ)
5436 readfds = select_readfds;
5440 if (select_valid & SELECT_HAVE_WRITE)
5442 writefds = select_writefds;
5447 if (select_valid & SELECT_HAVE_TMO)
5449 timeout = select_timeout;
5455 pthread_mutex_unlock (&select_mutex);
5457 FD_SET (selfds[0], &readfds);
5458 if (selfds[0] >= nfds) nfds = selfds[0]+1;
5460 result = pselect (nfds, &readfds, wfds, NULL, tmo, NULL);
5463 ns_send_appdefined (-2);
5464 else if (result > 0)
5466 if (FD_ISSET (selfds[0], &readfds))
5468 if (read (selfds[0], &c, 1) == 1 && c == 's')
5473 pthread_mutex_lock (&select_mutex);
5474 if (select_valid & SELECT_HAVE_READ)
5475 select_readfds = readfds;
5476 if (select_valid & SELECT_HAVE_WRITE)
5477 select_writefds = writefds;
5478 if (select_valid & SELECT_HAVE_TMO)
5479 select_timeout = timeout;
5480 pthread_mutex_unlock (&select_mutex);
5482 ns_send_appdefined (result);
5492 /* ==========================================================================
5496 ========================================================================== */
5498 /* called from system: queue for next pass through event loop */
5499 - (void)requestService: (NSPasteboard *)pboard
5500 userData: (NSString *)userData
5501 error: (NSString **)error
5503 [ns_pending_service_names addObject: userData];
5504 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
5505 SSDATA (ns_string_from_pasteboard (pboard))]];
5509 /* called from ns_read_socket to clear queue */
5510 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
5512 struct frame *emacsframe = SELECTED_FRAME ();
5513 NSEvent *theEvent = [NSApp currentEvent];
5515 NSTRACE ("[EmacsApp fulfillService:withArg:]");
5520 emacs_event->kind = NS_NONKEY_EVENT;
5521 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
5522 ns_input_spi_name = build_string ([name UTF8String]);
5523 ns_input_spi_arg = build_string ([arg UTF8String]);
5524 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5525 EV_TRAILER (theEvent);
5535 /* ==========================================================================
5537 EmacsView implementation
5539 ========================================================================== */
5542 @implementation EmacsView
5544 /* needed to inform when window closed from LISP */
5545 - (void) setWindowClosing: (BOOL)closing
5547 NSTRACE ("[EmacsView setWindowClosing:%d]", closing);
5549 windowClosing = closing;
5555 NSTRACE ("[EmacsView dealloc]");
5557 if (fs_state == FULLSCREEN_BOTH)
5558 [nonfs_window release];
5563 /* called on font panel selection */
5564 - (void)changeFont: (id)sender
5566 NSEvent *e = [[self window] currentEvent];
5567 struct face *face = FRAME_DEFAULT_FACE (emacsframe);
5568 struct font *font = face->font;
5573 NSTRACE ("[EmacsView changeFont:]");
5578 #ifdef NS_IMPL_GNUSTEP
5579 nsfont = ((struct nsfont_info *)font)->nsfont;
5581 #ifdef NS_IMPL_COCOA
5582 nsfont = (NSFont *) macfont_get_nsctfont (font);
5585 if ((newFont = [sender convertFont: nsfont]))
5587 SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
5589 emacs_event->kind = NS_NONKEY_EVENT;
5590 emacs_event->modifiers = 0;
5591 emacs_event->code = KEY_NS_CHANGE_FONT;
5593 size = [newFont pointSize];
5594 ns_input_fontsize = make_number (lrint (size));
5595 ns_input_font = build_string ([[newFont familyName] UTF8String]);
5601 - (BOOL)acceptsFirstResponder
5603 NSTRACE ("[EmacsView acceptsFirstResponder]");
5608 - (void)resetCursorRects
5610 NSRect visible = [self visibleRect];
5611 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
5612 NSTRACE ("[EmacsView resetCursorRects]");
5614 if (currentCursor == nil)
5615 currentCursor = [NSCursor arrowCursor];
5617 if (!NSIsEmptyRect (visible))
5618 [self addCursorRect: visible cursor: currentCursor];
5619 [currentCursor setOnMouseEntered: YES];
5624 /*****************************************************************************/
5625 /* Keyboard handling. */
5628 - (void)keyDown: (NSEvent *)theEvent
5630 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5632 unsigned fnKeysym = 0;
5633 static NSMutableArray *nsEvArray;
5635 unsigned int flags = [theEvent modifierFlags];
5637 NSTRACE ("[EmacsView keyDown:]");
5639 /* Rhapsody and OS X give up and down events for the arrow keys */
5640 if (ns_fake_keydown == YES)
5641 ns_fake_keydown = NO;
5642 else if ([theEvent type] != NSKeyDown)
5648 if (![[self window] isKeyWindow]
5649 && [[theEvent window] isKindOfClass: [EmacsWindow class]]
5650 /* we must avoid an infinite loop here. */
5651 && (EmacsView *)[[theEvent window] delegate] != self)
5653 /* XXX: There is an occasional condition in which, when Emacs display
5654 updates a different frame from the current one, and temporarily
5655 selects it, then processes some interrupt-driven input
5656 (dispnew.c:3878), OS will send the event to the correct NSWindow, but
5657 for some reason that window has its first responder set to the NSView
5658 most recently updated (I guess), which is not the correct one. */
5659 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
5663 if (nsEvArray == nil)
5664 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
5666 [NSCursor setHiddenUntilMouseMoves: YES];
5668 if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
5670 clear_mouse_face (hlinfo);
5671 hlinfo->mouse_face_hidden = 1;
5674 if (!processingCompose)
5676 /* When using screen sharing, no left or right information is sent,
5677 so use Left key in those cases. */
5678 int is_left_key, is_right_key;
5680 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
5681 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
5683 /* (Carbon way: [theEvent keyCode]) */
5685 /* is it a "function key"? */
5686 /* Note: Sometimes a plain key will have the NSNumericPadKeyMask
5687 flag set (this is probably a bug in the OS).
5689 if (code < 0x00ff && (flags&NSNumericPadKeyMask))
5691 fnKeysym = ns_convert_key ([theEvent keyCode] | NSNumericPadKeyMask);
5695 fnKeysym = ns_convert_key (code);
5700 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
5701 because Emacs treats Delete and KP-Delete same (in simple.el). */
5702 if ((fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
5703 #ifdef NS_IMPL_GNUSTEP
5704 /* GNUstep uses incompatible keycodes, even for those that are
5705 supposed to be hardware independent. Just check for delete.
5706 Keypad delete does not have keysym 0xFFFF.
5707 See http://savannah.gnu.org/bugs/?25395
5709 || (fnKeysym == 0xFFFF && code == 127)
5712 code = 0xFF08; /* backspace */
5717 /* are there modifiers? */
5718 emacs_event->modifiers = 0;
5720 if (flags & NSHelpKeyMask)
5721 emacs_event->modifiers |= hyper_modifier;
5723 if (flags & NSShiftKeyMask)
5724 emacs_event->modifiers |= shift_modifier;
5726 is_right_key = (flags & NSRightCommandKeyMask) == NSRightCommandKeyMask;
5727 is_left_key = (flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask
5728 || (! is_right_key && (flags & NSCommandKeyMask) == NSCommandKeyMask);
5731 emacs_event->modifiers |= parse_solitary_modifier
5732 (EQ (ns_right_command_modifier, Qleft)
5733 ? ns_command_modifier
5734 : ns_right_command_modifier);
5738 emacs_event->modifiers |= parse_solitary_modifier
5739 (ns_command_modifier);
5741 /* if super (default), take input manager's word so things like
5742 dvorak / qwerty layout work */
5743 if (EQ (ns_command_modifier, Qsuper)
5745 && [[theEvent characters] length] != 0)
5747 /* XXX: the code we get will be unshifted, so if we have
5748 a shift modifier, must convert ourselves */
5749 if (!(flags & NSShiftKeyMask))
5750 code = [[theEvent characters] characterAtIndex: 0];
5752 /* this is ugly and also requires linking w/Carbon framework
5753 (for LMGetKbdType) so for now leave this rare (?) case
5754 undealt with.. in future look into CGEvent methods */
5757 long smv = GetScriptManagerVariable (smKeyScript);
5758 Handle uchrHandle = GetResource
5759 ('uchr', GetScriptVariable (smv, smScriptKeys));
5761 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
5762 [[theEvent characters] characterAtIndex: 0],
5763 kUCKeyActionDisplay,
5764 (flags & ~NSCommandKeyMask) >> 8,
5765 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
5766 &dummy, 1, &dummy, &code);
5773 is_right_key = (flags & NSRightControlKeyMask) == NSRightControlKeyMask;
5774 is_left_key = (flags & NSLeftControlKeyMask) == NSLeftControlKeyMask
5775 || (! is_right_key && (flags & NSControlKeyMask) == NSControlKeyMask);
5778 emacs_event->modifiers |= parse_solitary_modifier
5779 (EQ (ns_right_control_modifier, Qleft)
5780 ? ns_control_modifier
5781 : ns_right_control_modifier);
5784 emacs_event->modifiers |= parse_solitary_modifier
5785 (ns_control_modifier);
5787 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
5788 emacs_event->modifiers |=
5789 parse_solitary_modifier (ns_function_modifier);
5791 left_is_none = NILP (ns_alternate_modifier)
5792 || EQ (ns_alternate_modifier, Qnone);
5794 is_right_key = (flags & NSRightAlternateKeyMask)
5795 == NSRightAlternateKeyMask;
5796 is_left_key = (flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask
5798 && (flags & NSAlternateKeyMask) == NSAlternateKeyMask);
5802 if ((NILP (ns_right_alternate_modifier)
5803 || EQ (ns_right_alternate_modifier, Qnone)
5804 || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
5806 { /* accept pre-interp alt comb */
5807 if ([[theEvent characters] length] > 0)
5808 code = [[theEvent characters] characterAtIndex: 0];
5809 /*HACK: clear lone shift modifier to stop next if from firing */
5810 if (emacs_event->modifiers == shift_modifier)
5811 emacs_event->modifiers = 0;
5814 emacs_event->modifiers |= parse_solitary_modifier
5815 (EQ (ns_right_alternate_modifier, Qleft)
5816 ? ns_alternate_modifier
5817 : ns_right_alternate_modifier);
5820 if (is_left_key) /* default = meta */
5822 if (left_is_none && !fnKeysym)
5823 { /* accept pre-interp alt comb */
5824 if ([[theEvent characters] length] > 0)
5825 code = [[theEvent characters] characterAtIndex: 0];
5826 /*HACK: clear lone shift modifier to stop next if from firing */
5827 if (emacs_event->modifiers == shift_modifier)
5828 emacs_event->modifiers = 0;
5831 emacs_event->modifiers |=
5832 parse_solitary_modifier (ns_alternate_modifier);
5836 fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
5837 code, fnKeysym, flags, emacs_event->modifiers);
5839 /* if it was a function key or had modifiers, pass it directly to emacs */
5840 if (fnKeysym || (emacs_event->modifiers
5841 && (emacs_event->modifiers != shift_modifier)
5842 && [[theEvent charactersIgnoringModifiers] length] > 0))
5843 /*[[theEvent characters] length] */
5845 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5847 code |= (1<<28)|(3<<16);
5848 else if (code == 0x7f)
5849 code |= (1<<28)|(3<<16);
5851 emacs_event->kind = code > 0xFF
5852 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5854 emacs_event->code = code;
5855 EV_TRAILER (theEvent);
5856 processingCompose = NO;
5862 if (NS_KEYLOG && !processingCompose)
5863 fprintf (stderr, "keyDown: Begin compose sequence.\n");
5865 processingCompose = YES;
5866 [nsEvArray addObject: theEvent];
5867 [self interpretKeyEvents: nsEvArray];
5868 [nsEvArray removeObject: theEvent];
5872 #ifdef NS_IMPL_COCOA
5873 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
5874 decided not to send key-down for.
5875 See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
5876 This only applies on Tiger and earlier.
5877 If it matches one of these, send it on to keyDown. */
5878 -(void)keyUp: (NSEvent *)theEvent
5880 int flags = [theEvent modifierFlags];
5881 int code = [theEvent keyCode];
5883 NSTRACE ("[EmacsView keyUp:]");
5885 if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
5886 code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
5889 fprintf (stderr, "keyUp: passed test");
5890 ns_fake_keydown = YES;
5891 [self keyDown: theEvent];
5897 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
5900 /* <NSTextInput>: called when done composing;
5901 NOTE: also called when we delete over working text, followed immed.
5902 by doCommandBySelector: deleteBackward: */
5903 - (void)insertText: (id)aString
5906 int len = [(NSString *)aString length];
5909 NSTRACE ("[EmacsView insertText:]");
5912 NSLog (@"insertText '%@'\tlen = %d", aString, len);
5913 processingCompose = NO;
5918 /* first, clear any working text */
5919 if (workingText != nil)
5920 [self deleteWorkingText];
5922 /* now insert the string as keystrokes */
5923 for (i =0; i<len; i++)
5925 code = [aString characterAtIndex: i];
5926 /* TODO: still need this? */
5928 code = '~'; /* 0x7E */
5929 if (code != 32) /* Space */
5930 emacs_event->modifiers = 0;
5932 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5933 emacs_event->code = code;
5934 EV_TRAILER ((id)nil);
5939 /* <NSTextInput>: inserts display of composing characters */
5940 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
5942 NSString *str = [aString respondsToSelector: @selector (string)] ?
5943 [aString string] : aString;
5945 NSTRACE ("[EmacsView setMarkedText:selectedRange:]");
5948 NSLog (@"setMarkedText '%@' len =%lu range %lu from %lu",
5949 str, (unsigned long)[str length],
5950 (unsigned long)selRange.length,
5951 (unsigned long)selRange.location);
5953 if (workingText != nil)
5954 [self deleteWorkingText];
5955 if ([str length] == 0)
5961 processingCompose = YES;
5962 workingText = [str copy];
5963 ns_working_text = build_string ([workingText UTF8String]);
5965 emacs_event->kind = NS_TEXT_EVENT;
5966 emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
5967 EV_TRAILER ((id)nil);
5971 /* delete display of composing characters [not in <NSTextInput>] */
5972 - (void)deleteWorkingText
5974 NSTRACE ("[EmacsView deleteWorkingText]");
5976 if (workingText == nil)
5979 NSLog(@"deleteWorkingText len =%lu\n", (unsigned long)[workingText length]);
5980 [workingText release];
5982 processingCompose = NO;
5987 emacs_event->kind = NS_TEXT_EVENT;
5988 emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
5989 EV_TRAILER ((id)nil);
5993 - (BOOL)hasMarkedText
5995 NSTRACE ("[EmacsView hasMarkedText]");
5997 return workingText != nil;
6001 - (NSRange)markedRange
6003 NSTRACE ("[EmacsView markedRange]");
6005 NSRange rng = workingText != nil
6006 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
6008 NSLog (@"markedRange request");
6015 NSTRACE ("[EmacsView unmarkText]");
6018 NSLog (@"unmark (accept) text");
6019 [self deleteWorkingText];
6020 processingCompose = NO;
6024 /* used to position char selection windows, etc. */
6025 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
6029 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
6031 NSTRACE ("[EmacsView firstRectForCharacterRange:]");
6034 NSLog (@"firstRectForCharRange request");
6036 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
6037 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
6038 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
6039 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
6040 +FRAME_LINE_HEIGHT (emacsframe));
6042 pt = [self convertPoint: pt toView: nil];
6043 pt = [[self window] convertBaseToScreen: pt];
6049 - (NSInteger)conversationIdentifier
6051 return (NSInteger)self;
6055 - (void)doCommandBySelector: (SEL)aSelector
6057 NSTRACE ("[EmacsView doCommandBySelector:]");
6060 NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
6062 processingCompose = NO;
6063 if (aSelector == @selector (deleteBackward:))
6065 /* happens when user backspaces over an ongoing composition:
6066 throw a 'delete' into the event queue */
6069 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
6070 emacs_event->code = 0xFF08;
6071 EV_TRAILER ((id)nil);
6075 - (NSArray *)validAttributesForMarkedText
6077 static NSArray *arr = nil;
6078 if (arr == nil) arr = [NSArray new];
6079 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
6083 - (NSRange)selectedRange
6086 NSLog (@"selectedRange request");
6087 return NSMakeRange (NSNotFound, 0);
6090 #if defined (NS_IMPL_COCOA) || GNUSTEP_GUI_MAJOR_VERSION > 0 || \
6091 GNUSTEP_GUI_MINOR_VERSION > 22
6092 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
6094 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
6098 NSLog (@"characterIndexForPoint request");
6102 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
6104 static NSAttributedString *str = nil;
6105 if (str == nil) str = [NSAttributedString new];
6107 NSLog (@"attributedSubstringFromRange request");
6111 /* End <NSTextInput> impl. */
6112 /*****************************************************************************/
6115 /* This is what happens when the user presses a mouse button. */
6116 - (void)mouseDown: (NSEvent *)theEvent
6118 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6119 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
6121 NSTRACE ("[EmacsView mouseDown:]");
6123 [self deleteWorkingText];
6128 dpyinfo->last_mouse_frame = emacsframe;
6129 /* appears to be needed to prevent spurious movement events generated on
6131 emacsframe->mouse_moved = 0;
6133 if ([theEvent type] == NSScrollWheel)
6135 CGFloat delta = [theEvent deltaY];
6136 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
6139 delta = [theEvent deltaX];
6142 NSTRACE_MSG ("deltaIsZero");
6145 emacs_event->kind = HORIZ_WHEEL_EVENT;
6148 emacs_event->kind = WHEEL_EVENT;
6150 emacs_event->code = 0;
6151 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
6152 ((delta > 0) ? up_modifier : down_modifier);
6156 emacs_event->kind = MOUSE_CLICK_EVENT;
6157 emacs_event->code = EV_BUTTON (theEvent);
6158 emacs_event->modifiers = EV_MODIFIERS (theEvent)
6159 | EV_UDMODIFIERS (theEvent);
6161 XSETINT (emacs_event->x, lrint (p.x));
6162 XSETINT (emacs_event->y, lrint (p.y));
6163 EV_TRAILER (theEvent);
6167 - (void)rightMouseDown: (NSEvent *)theEvent
6169 NSTRACE ("[EmacsView rightMouseDown:]");
6170 [self mouseDown: theEvent];
6174 - (void)otherMouseDown: (NSEvent *)theEvent
6176 NSTRACE ("[EmacsView otherMouseDown:]");
6177 [self mouseDown: theEvent];
6181 - (void)mouseUp: (NSEvent *)theEvent
6183 NSTRACE ("[EmacsView mouseUp:]");
6184 [self mouseDown: theEvent];
6188 - (void)rightMouseUp: (NSEvent *)theEvent
6190 NSTRACE ("[EmacsView rightMouseUp:]");
6191 [self mouseDown: theEvent];
6195 - (void)otherMouseUp: (NSEvent *)theEvent
6197 NSTRACE ("[EmacsView otherMouseUp:]");
6198 [self mouseDown: theEvent];
6202 - (void) scrollWheel: (NSEvent *)theEvent
6204 NSTRACE ("[EmacsView scrollWheel:]");
6205 [self mouseDown: theEvent];
6209 /* Tell emacs the mouse has moved. */
6210 - (void)mouseMoved: (NSEvent *)e
6212 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
6213 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6217 NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "[EmacsView mouseMoved:]");
6219 dpyinfo->last_mouse_movement_time = EV_TIMESTAMP (e);
6220 pt = [self convertPoint: [e locationInWindow] fromView: nil];
6221 dpyinfo->last_mouse_motion_x = pt.x;
6222 dpyinfo->last_mouse_motion_y = pt.y;
6224 /* update any mouse face */
6225 if (hlinfo->mouse_face_hidden)
6227 hlinfo->mouse_face_hidden = 0;
6228 clear_mouse_face (hlinfo);
6231 /* tooltip handling */
6232 previous_help_echo_string = help_echo_string;
6233 help_echo_string = Qnil;
6235 if (!NILP (Vmouse_autoselect_window))
6237 NSTRACE_MSG ("mouse_autoselect_window");
6238 static Lisp_Object last_mouse_window;
6240 = window_from_coordinates (emacsframe, pt.x, pt.y, 0, 0);
6242 if (WINDOWP (window)
6243 && !EQ (window, last_mouse_window)
6244 && !EQ (window, selected_window)
6245 && (focus_follows_mouse
6246 || (EQ (XWINDOW (window)->frame,
6247 XWINDOW (selected_window)->frame))))
6249 NSTRACE_MSG ("in_window");
6250 emacs_event->kind = SELECT_WINDOW_EVENT;
6251 emacs_event->frame_or_window = window;
6254 /* Remember the last window where we saw the mouse. */
6255 last_mouse_window = window;
6258 if (!note_mouse_movement (emacsframe, pt.x, pt.y))
6259 help_echo_string = previous_help_echo_string;
6261 XSETFRAME (frame, emacsframe);
6262 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
6264 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
6265 (note_mouse_highlight), which is called through the
6266 note_mouse_movement () call above */
6267 any_help_event_p = YES;
6268 gen_help_event (help_echo_string, frame, help_echo_window,
6269 help_echo_object, help_echo_pos);
6272 if (emacsframe->mouse_moved && send_appdefined)
6273 ns_send_appdefined (-1);
6277 - (void)mouseDragged: (NSEvent *)e
6279 NSTRACE ("[EmacsView mouseDragged:]");
6280 [self mouseMoved: e];
6284 - (void)rightMouseDragged: (NSEvent *)e
6286 NSTRACE ("[EmacsView rightMouseDragged:]");
6287 [self mouseMoved: e];
6291 - (void)otherMouseDragged: (NSEvent *)e
6293 NSTRACE ("[EmacsView otherMouseDragged:]");
6294 [self mouseMoved: e];
6298 - (BOOL)windowShouldClose: (id)sender
6300 NSEvent *e =[[self window] currentEvent];
6302 NSTRACE ("[EmacsView windowShouldClose:]");
6303 windowClosing = YES;
6306 emacs_event->kind = DELETE_WINDOW_EVENT;
6307 emacs_event->modifiers = 0;
6308 emacs_event->code = 0;
6310 /* Don't close this window, let this be done from lisp code. */
6314 - (void) updateFrameSize: (BOOL) delay;
6316 NSWindow *window = [self window];
6317 NSRect wr = [window frame];
6319 int oldc = cols, oldr = rows;
6320 int oldw = FRAME_PIXEL_WIDTH (emacsframe);
6321 int oldh = FRAME_PIXEL_HEIGHT (emacsframe);
6324 NSTRACE ("[EmacsView updateFrameSize:]");
6325 NSTRACE_SIZE ("Original size", NSMakeSize (oldw, oldh));
6326 NSTRACE_RECT ("Original frame", wr);
6327 NSTRACE_MSG ("Original columns: %d", cols);
6328 NSTRACE_MSG ("Original rows: %d", rows);
6330 if (! [self isFullscreen])
6332 #ifdef NS_IMPL_GNUSTEP
6333 // GNUstep does not always update the tool bar height. Force it.
6334 if (toolbar && [toolbar isVisible])
6335 update_frame_tool_bar (emacsframe);
6338 extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6339 + FRAME_TOOLBAR_HEIGHT (emacsframe);
6342 if (wait_for_tool_bar)
6344 if (FRAME_TOOLBAR_HEIGHT (emacsframe) == 0)
6346 NSTRACE_MSG ("Waiting for toolbar");
6349 wait_for_tool_bar = NO;
6352 neww = (int)wr.size.width - emacsframe->border_width;
6353 newh = (int)wr.size.height - extra;
6355 NSTRACE_SIZE ("New size", NSMakeSize (neww, newh));
6356 NSTRACE_MSG ("tool_bar_height: %d", emacsframe->tool_bar_height);
6358 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, neww);
6359 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, newh);
6361 if (cols < MINWIDTH)
6364 if (rows < MINHEIGHT)
6367 NSTRACE_MSG ("New columns: %d", cols);
6368 NSTRACE_MSG ("New rows: %d", rows);
6370 if (oldr != rows || oldc != cols || neww != oldw || newh != oldh)
6372 NSView *view = FRAME_NS_VIEW (emacsframe);
6374 change_frame_size (emacsframe,
6375 FRAME_PIXEL_TO_TEXT_WIDTH (emacsframe, neww),
6376 FRAME_PIXEL_TO_TEXT_HEIGHT (emacsframe, newh),
6378 SET_FRAME_GARBAGED (emacsframe);
6379 cancel_mouse_face (emacsframe);
6381 wr = NSMakeRect (0, 0, neww, newh);
6383 [view setFrame: wr];
6385 // to do: consider using [NSNotificationCenter postNotificationName:].
6386 [self windowDidMove: // Update top/left.
6387 [NSNotification notificationWithName:NSWindowDidMoveNotification
6388 object:[view window]]];
6392 NSTRACE_MSG ("No change");
6396 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
6397 /* normalize frame to gridded text size */
6401 NSTRACE ("[EmacsView windowWillResize:toSize: " NSTRACE_FMT_SIZE "]",
6402 NSTRACE_ARG_SIZE (frameSize));
6403 NSTRACE_RECT ("[sender frame]", [sender frame]);
6404 NSTRACE_FSTYPE ("fs_state", fs_state);
6406 if (fs_state == FULLSCREEN_MAXIMIZED
6407 && (maximized_width != (int)frameSize.width
6408 || maximized_height != (int)frameSize.height))
6409 [self setFSValue: FULLSCREEN_NONE];
6410 else if (fs_state == FULLSCREEN_WIDTH
6411 && maximized_width != (int)frameSize.width)
6412 [self setFSValue: FULLSCREEN_NONE];
6413 else if (fs_state == FULLSCREEN_HEIGHT
6414 && maximized_height != (int)frameSize.height)
6415 [self setFSValue: FULLSCREEN_NONE];
6417 if (fs_state == FULLSCREEN_NONE)
6418 maximized_width = maximized_height = -1;
6420 if (! [self isFullscreen])
6422 extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6423 + FRAME_TOOLBAR_HEIGHT (emacsframe);
6426 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, frameSize.width);
6427 if (cols < MINWIDTH)
6430 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe,
6431 frameSize.height - extra);
6432 if (rows < MINHEIGHT)
6434 #ifdef NS_IMPL_COCOA
6436 /* this sets window title to have size in it; the wm does this under GS */
6437 NSRect r = [[self window] frame];
6438 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
6446 else if (fs_state == FULLSCREEN_NONE && ! maximizing_resize)
6449 NSWindow *window = [self window];
6452 char *t = strdup ([[[self window] title] UTF8String]);
6453 char *pos = strstr (t, " — ");
6458 size_title = xmalloc (strlen (old_title) + 40);
6459 esprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
6460 [window setTitle: [NSString stringWithUTF8String: size_title]];
6465 #endif /* NS_IMPL_COCOA */
6467 NSTRACE_MSG ("cols: %d rows: %d", cols, rows);
6469 /* Restrict the new size to the text gird.
6471 Don't restrict the width if the user only adjusted the height, and
6472 vice versa. (Without this, the frame would shrink, and move
6473 slightly, if the window was resized by dragging one of its
6475 if (!frame_resize_pixelwise)
6477 NSRect r = [[self window] frame];
6479 if (r.size.width != frameSize.width)
6482 FRAME_TEXT_COLS_TO_PIXEL_WIDTH (emacsframe, cols);
6485 if (r.size.height != frameSize.height)
6488 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows) + extra;
6492 NSTRACE_RETURN_SIZE (frameSize);
6498 - (void)windowDidResize: (NSNotification *)notification
6500 NSTRACE ("[EmacsView windowDidResize:]");
6501 if (!FRAME_LIVE_P (emacsframe))
6503 NSTRACE_MSG ("Ignored (frame dead)");
6506 if (emacsframe->output_data.ns->in_animation)
6508 NSTRACE_MSG ("Ignored (in animation)");
6512 if (! [self fsIsNative])
6514 NSWindow *theWindow = [notification object];
6515 /* We can get notification on the non-FS window when in
6517 if ([self window] != theWindow) return;
6520 NSTRACE_RECT ("frame", [[notification object] frame]);
6522 #ifdef NS_IMPL_GNUSTEP
6523 NSWindow *theWindow = [notification object];
6525 /* In GNUstep, at least currently, it's possible to get a didResize
6526 without getting a willResize.. therefore we need to act as if we got
6527 the willResize now */
6528 NSSize sz = [theWindow frame].size;
6529 sz = [self windowWillResize: theWindow toSize: sz];
6530 #endif /* NS_IMPL_GNUSTEP */
6532 if (cols > 0 && rows > 0)
6534 [self updateFrameSize: YES];
6537 ns_send_appdefined (-1);
6540 #ifdef NS_IMPL_COCOA
6541 - (void)viewDidEndLiveResize
6543 NSTRACE ("[EmacsView viewDidEndLiveResize]");
6545 [super viewDidEndLiveResize];
6548 [[self window] setTitle: [NSString stringWithUTF8String: old_title]];
6552 maximizing_resize = NO;
6554 #endif /* NS_IMPL_COCOA */
6557 - (void)windowDidBecomeKey: (NSNotification *)notification
6558 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6560 [self windowDidBecomeKey];
6564 - (void)windowDidBecomeKey /* for direct calls */
6566 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6567 struct frame *old_focus = dpyinfo->x_focus_frame;
6569 NSTRACE ("[EmacsView windowDidBecomeKey]");
6571 if (emacsframe != old_focus)
6572 dpyinfo->x_focus_frame = emacsframe;
6574 ns_frame_rehighlight (emacsframe);
6578 emacs_event->kind = FOCUS_IN_EVENT;
6579 EV_TRAILER ((id)nil);
6584 - (void)windowDidResignKey: (NSNotification *)notification
6585 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6587 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6588 BOOL is_focus_frame = dpyinfo->x_focus_frame == emacsframe;
6589 NSTRACE ("[EmacsView windowDidResignKey:]");
6592 dpyinfo->x_focus_frame = 0;
6594 emacsframe->mouse_moved = 0;
6595 ns_frame_rehighlight (emacsframe);
6597 /* FIXME: for some reason needed on second and subsequent clicks away
6598 from sole-frame Emacs to get hollow box to show */
6599 if (!windowClosing && [[self window] isVisible] == YES)
6601 x_update_cursor (emacsframe, 1);
6602 x_set_frame_alpha (emacsframe);
6605 if (any_help_event_p)
6608 XSETFRAME (frame, emacsframe);
6609 help_echo_string = Qnil;
6610 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
6613 if (emacs_event && is_focus_frame)
6615 [self deleteWorkingText];
6616 emacs_event->kind = FOCUS_OUT_EVENT;
6617 EV_TRAILER ((id)nil);
6622 - (void)windowWillMiniaturize: sender
6624 NSTRACE ("[EmacsView windowWillMiniaturize:]");
6628 - (void)setFrame:(NSRect)frameRect;
6630 NSTRACE ("[EmacsView setFrame:" NSTRACE_FMT_RECT "]",
6631 NSTRACE_ARG_RECT (frameRect));
6633 [super setFrame:(NSRect)frameRect];
6649 - initFrameFromEmacs: (struct frame *)f
6657 NSTRACE ("[EmacsView initFrameFromEmacs:]");
6658 NSTRACE_MSG ("cols:%d lines:%d", f->text_cols, f->text_lines);
6661 processingCompose = NO;
6662 scrollbarsNeedingUpdate = 0;
6663 fs_state = FULLSCREEN_NONE;
6664 fs_before_fs = next_maximized = -1;
6665 #ifdef HAVE_NATIVE_FS
6666 fs_is_native = ns_use_native_fullscreen;
6670 maximized_width = maximized_height = -1;
6673 ns_userRect = NSMakeRect (0, 0, 0, 0);
6674 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
6675 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
6676 [self initWithFrame: r];
6677 [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
6679 FRAME_NS_VIEW (f) = self;
6681 #ifdef NS_IMPL_COCOA
6683 maximizing_resize = NO;
6686 win = [[EmacsWindow alloc]
6687 initWithContentRect: r
6688 styleMask: (NSResizableWindowMask |
6689 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6690 NSTitledWindowMask |
6692 NSMiniaturizableWindowMask |
6693 NSClosableWindowMask)
6694 backing: NSBackingStoreBuffered
6697 #ifdef HAVE_NATIVE_FS
6698 [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
6702 bwidth = f->border_width = wr.size.width - r.size.width;
6703 tibar_height = FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
6705 [win setAcceptsMouseMovedEvents: YES];
6706 [win setDelegate: self];
6707 #if !defined (NS_IMPL_COCOA) || \
6708 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6709 [win useOptimizedDrawing: YES];
6712 [[win contentView] addSubview: self];
6715 [self registerForDraggedTypes: ns_drag_types];
6718 name = [NSString stringWithUTF8String:
6719 NILP (tem) ? "Emacs" : SSDATA (tem)];
6720 [win setTitle: name];
6722 /* toolbar support */
6723 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
6724 [NSString stringWithFormat: @"Emacs Frame %d",
6726 [win setToolbar: toolbar];
6727 [toolbar setVisible: NO];
6729 /* Don't set frame garbaged until tool bar is up to date?
6730 This avoids an extra clear and redraw (flicker) at frame creation. */
6731 if (FRAME_EXTERNAL_TOOL_BAR (f)) wait_for_tool_bar = YES;
6732 else wait_for_tool_bar = NO;
6735 #ifdef NS_IMPL_COCOA
6737 NSButton *toggleButton;
6738 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
6739 [toggleButton setTarget: self];
6740 [toggleButton setAction: @selector (toggleToolbar: )];
6743 FRAME_TOOLBAR_HEIGHT (f) = 0;
6747 [win setMiniwindowTitle:
6748 [NSString stringWithUTF8String: SSDATA (tem)]];
6751 NSScreen *screen = [win screen];
6755 NSPoint pt = NSMakePoint
6756 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
6757 IN_BOUND (-SCREENMAX,
6758 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX));
6760 [win setFrameTopLeftPoint: pt];
6762 NSTRACE_RECT ("new frame", [win frame]);
6766 [win makeFirstResponder: self];
6768 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6769 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
6770 [win setBackgroundColor: col];
6771 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6772 [win setOpaque: NO];
6774 #if !defined (NS_IMPL_COCOA) || \
6775 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6776 [self allocateGState];
6778 [NSApp registerServicesMenuSendTypes: ns_send_types
6786 - (void)windowDidMove: sender
6788 NSWindow *win = [self window];
6789 NSRect r = [win frame];
6790 NSArray *screens = [NSScreen screens];
6791 NSScreen *screen = [screens objectAtIndex: 0];
6793 NSTRACE ("[EmacsView windowDidMove:]");
6795 if (!emacsframe->output_data.ns)
6799 emacsframe->left_pos = r.origin.x;
6800 emacsframe->top_pos =
6801 [screen frame].size.height - (r.origin.y + r.size.height);
6806 /* Called AFTER method below, but before our windowWillResize call there leads
6807 to windowDidResize -> x_set_window_size. Update emacs' notion of frame
6808 location so set_window_size moves the frame. */
6809 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
6811 NSTRACE (("[EmacsView windowShouldZoom:toFrame:" NSTRACE_FMT_RECT "]"
6812 NSTRACE_FMT_RETURN "YES"),
6813 NSTRACE_ARG_RECT (newFrame));
6815 emacsframe->output_data.ns->zooming = 1;
6820 /* Override to do something slightly nonstandard, but nice. First click on
6821 zoom button will zoom vertically. Second will zoom completely. Third
6822 returns to original. */
6823 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
6824 defaultFrame:(NSRect)defaultFrame
6826 // TODO: Rename to "currentFrame" and assign "result" properly in
6828 NSRect result = [sender frame];
6830 NSTRACE (("[EmacsView windowWillUseStandardFrame:defaultFrame:"
6831 NSTRACE_FMT_RECT "]"),
6832 NSTRACE_ARG_RECT (defaultFrame));
6833 NSTRACE_FSTYPE ("fs_state", fs_state);
6834 NSTRACE_FSTYPE ("fs_before_fs", fs_before_fs);
6835 NSTRACE_FSTYPE ("next_maximized", next_maximized);
6836 NSTRACE_RECT ("ns_userRect", ns_userRect);
6837 NSTRACE_RECT ("[sender frame]", [sender frame]);
6839 if (fs_before_fs != -1) /* Entering fullscreen */
6841 NSTRACE_MSG ("Entering fullscreen");
6842 result = defaultFrame;
6846 // Save the window size and position (frame) before the resize.
6847 if (fs_state != FULLSCREEN_MAXIMIZED
6848 && fs_state != FULLSCREEN_WIDTH)
6850 ns_userRect.size.width = result.size.width;
6851 ns_userRect.origin.x = result.origin.x;
6854 if (fs_state != FULLSCREEN_MAXIMIZED
6855 && fs_state != FULLSCREEN_HEIGHT)
6857 ns_userRect.size.height = result.size.height;
6858 ns_userRect.origin.y = result.origin.y;
6861 NSTRACE_RECT ("ns_userRect (2)", ns_userRect);
6863 if (next_maximized == FULLSCREEN_HEIGHT
6864 || (next_maximized == -1
6865 && abs ((int)(defaultFrame.size.height - result.size.height))
6866 > FRAME_LINE_HEIGHT (emacsframe)))
6869 NSTRACE_MSG ("FULLSCREEN_HEIGHT");
6870 maximized_height = result.size.height = defaultFrame.size.height;
6871 maximized_width = -1;
6872 result.origin.y = defaultFrame.origin.y;
6873 if (ns_userRect.size.height != 0)
6875 result.origin.x = ns_userRect.origin.x;
6876 result.size.width = ns_userRect.size.width;
6878 [self setFSValue: FULLSCREEN_HEIGHT];
6879 #ifdef NS_IMPL_COCOA
6880 maximizing_resize = YES;
6883 else if (next_maximized == FULLSCREEN_WIDTH)
6885 NSTRACE_MSG ("FULLSCREEN_WIDTH");
6886 maximized_width = result.size.width = defaultFrame.size.width;
6887 maximized_height = -1;
6888 result.origin.x = defaultFrame.origin.x;
6889 if (ns_userRect.size.width != 0)
6891 result.origin.y = ns_userRect.origin.y;
6892 result.size.height = ns_userRect.size.height;
6894 [self setFSValue: FULLSCREEN_WIDTH];
6896 else if (next_maximized == FULLSCREEN_MAXIMIZED
6897 || (next_maximized == -1
6898 && abs ((int)(defaultFrame.size.width - result.size.width))
6899 > FRAME_COLUMN_WIDTH (emacsframe)))
6901 NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
6903 result = defaultFrame; /* second click */
6904 maximized_width = result.size.width;
6905 maximized_height = result.size.height;
6906 [self setFSValue: FULLSCREEN_MAXIMIZED];
6907 #ifdef NS_IMPL_COCOA
6908 maximizing_resize = YES;
6914 NSTRACE_MSG ("Restore");
6915 result = ns_userRect.size.height ? ns_userRect : result;
6916 NSTRACE_RECT ("restore (2)", result);
6917 ns_userRect = NSMakeRect (0, 0, 0, 0);
6918 #ifdef NS_IMPL_COCOA
6919 maximizing_resize = fs_state != FULLSCREEN_NONE;
6921 [self setFSValue: FULLSCREEN_NONE];
6922 maximized_width = maximized_height = -1;
6926 if (fs_before_fs == -1) next_maximized = -1;
6928 NSTRACE_RECT ("Final ns_userRect", ns_userRect);
6929 NSTRACE_MSG ("Final maximized_width: %d", maximized_width);
6930 NSTRACE_MSG ("Final maximized_height: %d", maximized_height);
6931 NSTRACE_FSTYPE ("Final next_maximized", next_maximized);
6933 [self windowWillResize: sender toSize: result.size];
6935 NSTRACE_RETURN_RECT (result);
6941 - (void)windowDidDeminiaturize: sender
6943 NSTRACE ("[EmacsView windowDidDeminiaturize:]");
6944 if (!emacsframe->output_data.ns)
6947 SET_FRAME_ICONIFIED (emacsframe, 0);
6948 SET_FRAME_VISIBLE (emacsframe, 1);
6949 windows_or_buffers_changed = 63;
6953 emacs_event->kind = DEICONIFY_EVENT;
6954 EV_TRAILER ((id)nil);
6959 - (void)windowDidExpose: sender
6961 NSTRACE ("[EmacsView windowDidExpose:]");
6962 if (!emacsframe->output_data.ns)
6965 SET_FRAME_VISIBLE (emacsframe, 1);
6966 SET_FRAME_GARBAGED (emacsframe);
6968 if (send_appdefined)
6969 ns_send_appdefined (-1);
6973 - (void)windowDidMiniaturize: sender
6975 NSTRACE ("[EmacsView windowDidMiniaturize:]");
6976 if (!emacsframe->output_data.ns)
6979 SET_FRAME_ICONIFIED (emacsframe, 1);
6980 SET_FRAME_VISIBLE (emacsframe, 0);
6984 emacs_event->kind = ICONIFY_EVENT;
6985 EV_TRAILER ((id)nil);
6989 #ifdef HAVE_NATIVE_FS
6990 - (NSApplicationPresentationOptions)window:(NSWindow *)window
6991 willUseFullScreenPresentationOptions:
6992 (NSApplicationPresentationOptions)proposedOptions
6994 return proposedOptions|NSApplicationPresentationAutoHideToolbar;
6998 - (void)windowWillEnterFullScreen:(NSNotification *)notification
7000 NSTRACE ("[EmacsView windowWillEnterFullScreen:]");
7001 [self windowWillEnterFullScreen];
7003 - (void)windowWillEnterFullScreen /* provided for direct calls */
7005 NSTRACE ("[EmacsView windowWillEnterFullScreen]");
7006 fs_before_fs = fs_state;
7009 - (void)windowDidEnterFullScreen:(NSNotification *)notification
7011 NSTRACE ("[EmacsView windowDidEnterFullScreen:]");
7012 [self windowDidEnterFullScreen];
7015 - (void)windowDidEnterFullScreen /* provided for direct calls */
7017 NSTRACE ("[EmacsView windowDidEnterFullScreen]");
7018 [self setFSValue: FULLSCREEN_BOTH];
7019 if (! [self fsIsNative])
7021 [self windowDidBecomeKey];
7022 [nonfs_window orderOut:self];
7026 BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (emacsframe) ? YES : NO;
7027 #ifdef NS_IMPL_COCOA
7028 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
7029 unsigned val = (unsigned)[NSApp presentationOptions];
7031 // OSX 10.7 bug fix, the menu won't appear without this.
7032 // val is non-zero on other OSX versions.
7035 NSApplicationPresentationOptions options
7036 = NSApplicationPresentationAutoHideDock
7037 | NSApplicationPresentationAutoHideMenuBar
7038 | NSApplicationPresentationFullScreen
7039 | NSApplicationPresentationAutoHideToolbar;
7041 [NSApp setPresentationOptions: options];
7045 [toolbar setVisible:tbar_visible];
7049 - (void)windowWillExitFullScreen:(NSNotification *)notification
7051 NSTRACE ("[EmacsView windowWillExitFullScreen:]");
7052 [self windowWillExitFullScreen];
7055 - (void)windowWillExitFullScreen /* provided for direct calls */
7057 NSTRACE ("[EmacsView windowWillExitFullScreen]");
7058 if (!FRAME_LIVE_P (emacsframe))
7060 NSTRACE_MSG ("Ignored (frame dead)");
7063 if (next_maximized != -1)
7064 fs_before_fs = next_maximized;
7067 - (void)windowDidExitFullScreen:(NSNotification *)notification
7069 NSTRACE ("[EmacsView windowDidExitFullScreen:]");
7070 [self windowDidExitFullScreen];
7073 - (void)windowDidExitFullScreen /* provided for direct calls */
7075 NSTRACE ("[EmacsView windowDidExitFullScreen]");
7076 if (!FRAME_LIVE_P (emacsframe))
7078 NSTRACE_MSG ("Ignored (frame dead)");
7081 [self setFSValue: fs_before_fs];
7083 #ifdef HAVE_NATIVE_FS
7084 [self updateCollectionBehavior];
7086 if (FRAME_EXTERNAL_TOOL_BAR (emacsframe))
7088 [toolbar setVisible:YES];
7089 update_frame_tool_bar (emacsframe);
7090 [self updateFrameSize:YES];
7091 [[self window] display];
7094 [toolbar setVisible:NO];
7096 if (next_maximized != -1)
7097 [[self window] performZoom:self];
7102 return fs_is_native;
7105 - (BOOL)isFullscreen
7111 res = (nonfs_window != nil);
7115 #ifdef HAVE_NATIVE_FS
7116 res = (([[self window] styleMask] & NSFullScreenWindowMask) != 0);
7122 NSTRACE ("[EmacsView isFullscreen] " NSTRACE_FMT_RETURN " %d",
7128 #ifdef HAVE_NATIVE_FS
7129 - (void)updateCollectionBehavior
7131 NSTRACE ("[EmacsView updateCollectionBehavior]");
7133 if (! [self isFullscreen])
7135 NSWindow *win = [self window];
7136 NSWindowCollectionBehavior b = [win collectionBehavior];
7137 if (ns_use_native_fullscreen)
7138 b |= NSWindowCollectionBehaviorFullScreenPrimary;
7140 b &= ~NSWindowCollectionBehaviorFullScreenPrimary;
7142 [win setCollectionBehavior: b];
7143 fs_is_native = ns_use_native_fullscreen;
7148 - (void)toggleFullScreen: (id)sender
7156 NSTRACE ("[EmacsView toggleFullScreen:]");
7160 #ifdef HAVE_NATIVE_FS
7161 [[self window] toggleFullScreen:sender];
7167 onFirstScreen = [[w screen] isEqual:[[NSScreen screens] objectAtIndex:0]];
7170 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
7171 (FRAME_DEFAULT_FACE (f)),
7174 if (fs_state != FULLSCREEN_BOTH)
7176 NSScreen *screen = [w screen];
7178 #if defined (NS_IMPL_COCOA) && \
7179 MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7180 /* Hide ghost menu bar on secondary monitor? */
7181 if (! onFirstScreen)
7182 onFirstScreen = [NSScreen screensHaveSeparateSpaces];
7184 /* Hide dock and menubar if we are on the primary screen. */
7187 #ifdef NS_IMPL_COCOA
7188 NSApplicationPresentationOptions options
7189 = NSApplicationPresentationAutoHideDock
7190 | NSApplicationPresentationAutoHideMenuBar;
7192 [NSApp setPresentationOptions: options];
7194 [NSMenu setMenuBarVisible:NO];
7198 fw = [[EmacsFSWindow alloc]
7199 initWithContentRect:[w contentRectForFrameRect:wr]
7200 styleMask:NSBorderlessWindowMask
7201 backing:NSBackingStoreBuffered
7205 [fw setContentView:[w contentView]];
7206 [fw setTitle:[w title]];
7207 [fw setDelegate:self];
7208 [fw setAcceptsMouseMovedEvents: YES];
7209 #if !defined (NS_IMPL_COCOA) || \
7210 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
7211 [fw useOptimizedDrawing: YES];
7213 [fw setBackgroundColor: col];
7214 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
7217 f->border_width = 0;
7218 FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
7219 tobar_height = FRAME_TOOLBAR_HEIGHT (f);
7220 FRAME_TOOLBAR_HEIGHT (f) = 0;
7224 [self windowWillEnterFullScreen];
7225 [fw makeKeyAndOrderFront:NSApp];
7226 [fw makeFirstResponder:self];
7228 r = [fw frameRectForContentRect:[screen frame]];
7229 [fw setFrame: r display:YES animate:ns_use_fullscreen_animation];
7230 [self windowDidEnterFullScreen];
7241 #ifdef NS_IMPL_COCOA
7242 [NSApp setPresentationOptions: NSApplicationPresentationDefault];
7244 [NSMenu setMenuBarVisible:YES];
7248 [w setContentView:[fw contentView]];
7249 [w setBackgroundColor: col];
7250 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
7253 f->border_width = bwidth;
7254 FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
7255 if (FRAME_EXTERNAL_TOOL_BAR (f))
7256 FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
7258 // to do: consider using [NSNotificationCenter postNotificationName:] to send notifications.
7260 [self windowWillExitFullScreen];
7261 [fw setFrame: [w frame] display:YES animate:ns_use_fullscreen_animation];
7263 [w makeKeyAndOrderFront:NSApp];
7264 [self windowDidExitFullScreen];
7265 [self updateFrameSize:YES];
7271 NSTRACE ("[EmacsView handleFS]");
7273 if (fs_state != emacsframe->want_fullscreen)
7275 if (fs_state == FULLSCREEN_BOTH)
7277 NSTRACE_MSG ("fs_state == FULLSCREEN_BOTH");
7278 [self toggleFullScreen:self];
7281 switch (emacsframe->want_fullscreen)
7283 case FULLSCREEN_BOTH:
7284 NSTRACE_MSG ("FULLSCREEN_BOTH");
7285 [self toggleFullScreen:self];
7287 case FULLSCREEN_WIDTH:
7288 NSTRACE_MSG ("FULLSCREEN_WIDTH");
7289 next_maximized = FULLSCREEN_WIDTH;
7290 if (fs_state != FULLSCREEN_BOTH)
7291 [[self window] performZoom:self];
7293 case FULLSCREEN_HEIGHT:
7294 NSTRACE_MSG ("FULLSCREEN_HEIGHT");
7295 next_maximized = FULLSCREEN_HEIGHT;
7296 if (fs_state != FULLSCREEN_BOTH)
7297 [[self window] performZoom:self];
7299 case FULLSCREEN_MAXIMIZED:
7300 NSTRACE_MSG ("FULLSCREEN_MAXIMIZED");
7301 next_maximized = FULLSCREEN_MAXIMIZED;
7302 if (fs_state != FULLSCREEN_BOTH)
7303 [[self window] performZoom:self];
7305 case FULLSCREEN_NONE:
7306 NSTRACE_MSG ("FULLSCREEN_NONE");
7307 if (fs_state != FULLSCREEN_BOTH)
7309 next_maximized = FULLSCREEN_NONE;
7310 [[self window] performZoom:self];
7315 emacsframe->want_fullscreen = FULLSCREEN_NONE;
7320 - (void) setFSValue: (int)value
7322 NSTRACE ("[EmacsView setFSValue:" NSTRACE_FMT_FSTYPE "]",
7323 NSTRACE_ARG_FSTYPE(value));
7325 Lisp_Object lval = Qnil;
7328 case FULLSCREEN_BOTH:
7331 case FULLSCREEN_WIDTH:
7334 case FULLSCREEN_HEIGHT:
7337 case FULLSCREEN_MAXIMIZED:
7341 store_frame_param (emacsframe, Qfullscreen, lval);
7345 - (void)mouseEntered: (NSEvent *)theEvent
7347 NSTRACE ("[EmacsView mouseEntered:]");
7349 FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7350 = EV_TIMESTAMP (theEvent);
7354 - (void)mouseExited: (NSEvent *)theEvent
7356 Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
7358 NSTRACE ("[EmacsView mouseExited:]");
7363 FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
7364 = EV_TIMESTAMP (theEvent);
7366 if (emacsframe == hlinfo->mouse_face_mouse_frame)
7368 clear_mouse_face (hlinfo);
7369 hlinfo->mouse_face_mouse_frame = 0;
7376 NSTRACE ("[EmacsView menuDown:]");
7377 if (context_menu_value == -1)
7378 context_menu_value = [sender tag];
7381 NSInteger tag = [sender tag];
7382 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
7383 emacsframe->menu_bar_vector,
7387 ns_send_appdefined (-1);
7392 - (EmacsToolbar *)toolbar
7398 /* this gets called on toolbar button click */
7399 - toolbarClicked: (id)item
7402 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
7404 NSTRACE ("[EmacsView toolbarClicked:]");
7409 /* send first event (for some reason two needed) */
7410 theEvent = [[self window] currentEvent];
7411 emacs_event->kind = TOOL_BAR_EVENT;
7412 XSETFRAME (emacs_event->arg, emacsframe);
7413 EV_TRAILER (theEvent);
7415 emacs_event->kind = TOOL_BAR_EVENT;
7416 /* XSETINT (emacs_event->code, 0); */
7417 emacs_event->arg = AREF (emacsframe->tool_bar_items,
7418 idx + TOOL_BAR_ITEM_KEY);
7419 emacs_event->modifiers = EV_MODIFIERS (theEvent);
7420 EV_TRAILER (theEvent);
7425 - toggleToolbar: (id)sender
7427 NSTRACE ("[EmacsView toggleToolbar:]");
7432 emacs_event->kind = NS_NONKEY_EVENT;
7433 emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
7434 EV_TRAILER ((id)nil);
7439 - (void)drawRect: (NSRect)rect
7441 int x = NSMinX (rect), y = NSMinY (rect);
7442 int width = NSWidth (rect), height = NSHeight (rect);
7444 NSTRACE ("[EmacsView drawRect:" NSTRACE_FMT_RECT "]",
7445 NSTRACE_ARG_RECT(rect));
7447 if (!emacsframe || !emacsframe->output_data.ns)
7450 ns_clear_frame_area (emacsframe, x, y, width, height);
7452 expose_frame (emacsframe, x, y, width, height);
7456 drawRect: may be called (at least in OS X 10.5) for invisible
7457 views as well for some reason. Thus, do not infer visibility
7460 emacsframe->async_visible = 1;
7461 emacsframe->async_iconified = 0;
7466 /* NSDraggingDestination protocol methods. Actually this is not really a
7467 protocol, but a category of Object. O well... */
7469 -(NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
7471 NSTRACE ("[EmacsView draggingEntered:]");
7472 return NSDragOperationGeneric;
7476 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
7482 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
7487 NSEvent *theEvent = [[self window] currentEvent];
7489 NSDragOperation op = [sender draggingSourceOperationMask];
7492 NSTRACE ("[EmacsView performDragOperation:]");
7497 position = [self convertPoint: [sender draggingLocation] fromView: nil];
7498 x = lrint (position.x); y = lrint (position.y);
7500 pb = [sender draggingPasteboard];
7501 type = [pb availableTypeFromArray: ns_drag_types];
7503 if (! (op & (NSDragOperationMove|NSDragOperationDelete)) &&
7504 // URL drags contain all operations (0xf), don't allow all to be set.
7507 if (op & NSDragOperationLink)
7508 modifiers |= NSControlKeyMask;
7509 if (op & NSDragOperationCopy)
7510 modifiers |= NSAlternateKeyMask;
7511 if (op & NSDragOperationGeneric)
7512 modifiers |= NSCommandKeyMask;
7515 modifiers = EV_MODIFIERS2 (modifiers);
7520 else if ([type isEqualToString: NSFilenamesPboardType])
7523 NSEnumerator *fenum;
7526 if (!(files = [pb propertyListForType: type]))
7529 fenum = [files objectEnumerator];
7530 while ( (file = [fenum nextObject]) )
7532 emacs_event->kind = DRAG_N_DROP_EVENT;
7533 XSETINT (emacs_event->x, x);
7534 XSETINT (emacs_event->y, y);
7535 ns_input_file = append2 (ns_input_file,
7536 build_string ([file UTF8String]));
7537 emacs_event->modifiers = modifiers;
7538 emacs_event->arg = list2 (Qfile, build_string ([file UTF8String]));
7539 EV_TRAILER (theEvent);
7543 else if ([type isEqualToString: NSURLPboardType])
7545 NSURL *url = [NSURL URLFromPasteboard: pb];
7546 if (url == nil) return NO;
7548 emacs_event->kind = DRAG_N_DROP_EVENT;
7549 XSETINT (emacs_event->x, x);
7550 XSETINT (emacs_event->y, y);
7551 emacs_event->modifiers = modifiers;
7552 emacs_event->arg = list2 (Qurl,
7553 build_string ([[url absoluteString]
7555 EV_TRAILER (theEvent);
7557 if ([url isFileURL] != NO)
7559 NSString *file = [url path];
7560 ns_input_file = append2 (ns_input_file,
7561 build_string ([file UTF8String]));
7565 else if ([type isEqualToString: NSStringPboardType]
7566 || [type isEqualToString: NSTabularTextPboardType])
7570 if (! (data = [pb stringForType: type]))
7573 emacs_event->kind = DRAG_N_DROP_EVENT;
7574 XSETINT (emacs_event->x, x);
7575 XSETINT (emacs_event->y, y);
7576 emacs_event->modifiers = modifiers;
7577 emacs_event->arg = list2 (Qnil, build_string ([data UTF8String]));
7578 EV_TRAILER (theEvent);
7583 fprintf (stderr, "Invalid data type in dragging pasteboard");
7589 - (id) validRequestorForSendType: (NSString *)typeSent
7590 returnType: (NSString *)typeReturned
7592 NSTRACE ("[EmacsView validRequestorForSendType:returnType:]");
7593 if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
7594 && typeReturned == nil)
7596 if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
7600 return [super validRequestorForSendType: typeSent
7601 returnType: typeReturned];
7605 /* The next two methods are part of NSServicesRequests informal protocol,
7606 supposedly called when a services menu item is chosen from this app.
7607 But this should not happen because we override the services menu with our
7608 own entries which call ns-perform-service.
7609 Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
7610 So let's at least stub them out until further investigation can be done. */
7612 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
7614 /* we could call ns_string_from_pasteboard(pboard) here but then it should
7615 be written into the buffer in place of the existing selection..
7616 ordinary service calls go through functions defined in ns-win.el */
7620 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
7622 NSArray *typesDeclared;
7625 NSTRACE ("[EmacsView writeSelectionToPasteboard:types:]");
7627 /* We only support NSStringPboardType */
7628 if ([types containsObject:NSStringPboardType] == NO) {
7632 val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7633 if (CONSP (val) && SYMBOLP (XCAR (val)))
7636 if (CONSP (val) && NILP (XCDR (val)))
7639 if (! STRINGP (val))
7642 typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
7643 [pb declareTypes:typesDeclared owner:nil];
7644 ns_string_to_pasteboard (pb, val);
7649 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
7650 (gives a miniaturized version of the window); currently we use the latter for
7651 frames whose active buffer doesn't correspond to any file
7652 (e.g., '*scratch*') */
7653 - setMiniwindowImage: (BOOL) setMini
7655 id image = [[self window] miniwindowImage];
7656 NSTRACE ("[EmacsView setMiniwindowImage:%d]", setMini);
7658 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
7659 about "AppleDockIconEnabled" notwithstanding, however the set message
7660 below has its effect nonetheless. */
7661 if (image != emacsframe->output_data.ns->miniimage)
7663 if (image && [image isKindOfClass: [EmacsImage class]])
7665 [[self window] setMiniwindowImage:
7666 setMini ? emacsframe->output_data.ns->miniimage : nil];
7673 - (void) setRows: (int) r andColumns: (int) c
7675 NSTRACE ("[EmacsView setRows:%d andColumns:%d]", r, c);
7680 - (int) fullscreenState
7685 @end /* EmacsView */
7689 /* ==========================================================================
7691 EmacsWindow implementation
7693 ========================================================================== */
7695 @implementation EmacsWindow
7697 #ifdef NS_IMPL_COCOA
7698 - (id)accessibilityAttributeValue:(NSString *)attribute
7700 Lisp_Object str = Qnil;
7701 struct frame *f = SELECTED_FRAME ();
7702 struct buffer *curbuf = XBUFFER (XWINDOW (f->selected_window)->contents);
7704 NSTRACE ("[EmacsWindow accessibilityAttributeValue:]");
7706 if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
7707 return NSAccessibilityTextFieldRole;
7709 if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]
7710 && curbuf && ! NILP (BVAR (curbuf, mark_active)))
7712 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7714 else if (curbuf && [attribute isEqualToString:NSAccessibilityValueAttribute])
7716 if (! NILP (BVAR (curbuf, mark_active)))
7717 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7721 ptrdiff_t start_byte = BUF_BEGV_BYTE (curbuf);
7722 ptrdiff_t byte_range = BUF_ZV_BYTE (curbuf) - start_byte;
7723 ptrdiff_t range = BUF_ZV (curbuf) - BUF_BEGV (curbuf);
7725 if (! NILP (BVAR (curbuf, enable_multibyte_characters)))
7726 str = make_uninit_multibyte_string (range, byte_range);
7728 str = make_uninit_string (range);
7729 /* To check: This returns emacs-utf-8, which is a superset of utf-8.
7730 Is this a problem? */
7731 memcpy (SDATA (str), BYTE_POS_ADDR (start_byte), byte_range);
7738 if (CONSP (str) && SYMBOLP (XCAR (str)))
7741 if (CONSP (str) && NILP (XCDR (str)))
7746 const char *utfStr = SSDATA (str);
7747 NSString *nsStr = [NSString stringWithUTF8String: utfStr];
7752 return [super accessibilityAttributeValue:attribute];
7754 #endif /* NS_IMPL_COCOA */
7756 /* Constrain size and placement of a frame.
7758 By returning the original "frameRect", the frame is not
7759 constrained. This can lead to unwanted situations where, for
7760 example, the menu bar covers the frame.
7762 The default implementation (accessed using "super") constrains the
7763 frame to the visible area of SCREEN, minus the menu bar (if
7764 present) and the Dock. Note that default implementation also calls
7765 windowWillResize, with the frame it thinks should have. (This can
7766 make the frame exit maximized mode.)
7768 Note that this should work in situations where multiple monitors
7769 are present. Common configurations are side-by-side monitors and a
7770 monitor on top of another (e.g. when a laptop is placed under a
7772 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
7774 NSTRACE ("[EmacsWindow constrainFrameRect:" NSTRACE_FMT_RECT " toScreen:]",
7775 NSTRACE_ARG_RECT (frameRect));
7777 #ifdef NS_IMPL_COCOA
7778 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7779 // If separate spaces is on, it is like each screen is independent. There is
7780 // no spanning of frames across screens.
7781 if ([NSScreen screensHaveSeparateSpaces])
7783 NSTRACE_MSG ("Screens have separate spaces");
7784 frameRect = [super constrainFrameRect:frameRect toScreen:screen];
7785 NSTRACE_RETURN_RECT (frameRect);
7791 return constrain_frame_rect(frameRect,
7792 [(EmacsView *)[self delegate] isFullscreen]);
7796 - (void)performZoom:(id)sender
7798 NSTRACE ("[EmacsWindow performZoom:]");
7800 return [super performZoom:sender];
7803 - (void)zoom:(id)sender
7805 NSTRACE ("[EmacsWindow zoom:]");
7807 ns_update_auto_hide_menu_bar();
7809 // Below are three zoom implementations. In the final commit, the
7810 // idea is that the last should be included.
7813 // Native zoom done using the standard zoom animation. Size of the
7814 // resulting frame reduced to accommodate the Dock and, if present,
7816 [super zoom:sender];
7819 // Native zoom done using the standard zoom animation, plus an
7820 // explicit resize to cover the full screen.
7821 [super zoom:sender];
7823 // After the native zoom, resize the resulting frame to fill the
7824 // entire screen, except the menu-bar.
7826 // This works for all practical purposes. (The only minor oddity is
7827 // when transiting from full-height frame to a maximized, the
7828 // animation reduces the height of the frame slightly (to the 4
7829 // pixels needed to accommodate the Doc) before it snaps back into
7830 // full height. The user would need a very trained eye to spot
7832 NSScreen * screen = [self screen];
7835 int fs_state = [(EmacsView *)[self delegate] fullscreenState];
7837 NSTRACE_FSTYPE ("fullscreenState", fs_state);
7839 NSRect sr = [screen frame];
7840 NSRect wr = [self frame];
7841 NSTRACE_RECT ("Rect after zoom", wr);
7845 if (fs_state == FULLSCREEN_MAXIMIZED
7846 || fs_state == FULLSCREEN_HEIGHT)
7849 newWr.size.height = sr.size.height - ns_menu_bar_height(screen);
7852 if (fs_state == FULLSCREEN_MAXIMIZED
7853 || fs_state == FULLSCREEN_WIDTH)
7856 newWr.size.width = sr.size.width;
7859 if (newWr.size.width != wr.size.width
7860 || newWr.size.height != wr.size.height
7861 || newWr.origin.x != wr.origin.x
7862 || newWr.origin.y != wr.origin.y)
7864 NSTRACE_MSG ("New frame different");
7865 [self setFrame: newWr display: NO];
7869 // Non-native zoom which is done instantaneously. The resulting frame
7870 // covers the entire screen, except the menu-bar, if present.
7871 NSScreen * screen = [self screen];
7874 NSRect sr = [screen frame];
7875 sr.size.height -= ns_menu_bar_height (screen);
7877 sr = [[self delegate] windowWillUseStandardFrame:self
7879 [self setFrame: sr display: NO];
7884 - (void)setFrame:(NSRect)windowFrame
7885 display:(BOOL)displayViews
7887 NSTRACE ("[EmacsWindow setFrame:" NSTRACE_FMT_RECT " display:%d]",
7888 NSTRACE_ARG_RECT (windowFrame), displayViews);
7890 [super setFrame:windowFrame display:displayViews];
7893 - (void)setFrame:(NSRect)windowFrame
7894 display:(BOOL)displayViews
7895 animate:(BOOL)performAnimation
7897 NSTRACE ("[EmacsWindow setFrame:" NSTRACE_FMT_RECT
7898 " display:%d performAnimation:%d]",
7899 NSTRACE_ARG_RECT (windowFrame), displayViews, performAnimation);
7901 [super setFrame:windowFrame display:displayViews animate:performAnimation];
7904 - (void)setFrameTopLeftPoint:(NSPoint)point
7906 NSTRACE ("[EmacsWindow setFrameTopLeftPoint:" NSTRACE_FMT_POINT "]",
7907 NSTRACE_ARG_POINT (point));
7909 [super setFrameTopLeftPoint:point];
7911 @end /* EmacsWindow */
7914 @implementation EmacsFSWindow
7916 - (BOOL)canBecomeKeyWindow
7921 - (BOOL)canBecomeMainWindow
7928 /* ==========================================================================
7930 EmacsScroller implementation
7932 ========================================================================== */
7935 @implementation EmacsScroller
7937 /* for repeat button push */
7938 #define SCROLL_BAR_FIRST_DELAY 0.5
7939 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
7941 + (CGFloat) scrollerWidth
7943 /* TODO: if we want to allow variable widths, this is the place to do it,
7944 however neither GNUstep nor Cocoa support it very well */
7946 #if !defined (NS_IMPL_COCOA) || \
7947 MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
7948 r = [NSScroller scrollerWidth];
7950 r = [NSScroller scrollerWidthForControlSize: NSRegularControlSize
7951 scrollerStyle: NSScrollerStyleLegacy];
7957 - initFrame: (NSRect )r window: (Lisp_Object)nwin
7959 NSTRACE ("[EmacsScroller initFrame: window:]");
7961 r.size.width = [EmacsScroller scrollerWidth];
7962 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
7963 [self setContinuous: YES];
7964 [self setEnabled: YES];
7966 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
7967 locked against the top and bottom edges, and right edge on OS X, where
7968 scrollers are on right. */
7969 #ifdef NS_IMPL_GNUSTEP
7970 [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
7972 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
7975 window = XWINDOW (nwin);
7977 pixel_height = NSHeight (r);
7978 if (pixel_height == 0) pixel_height = 1;
7979 min_portion = 20 / pixel_height;
7981 frame = XFRAME (window->frame);
7982 if (FRAME_LIVE_P (frame))
7985 EmacsView *view = FRAME_NS_VIEW (frame);
7986 NSView *sview = [[view window] contentView];
7987 NSArray *subs = [sview subviews];
7989 /* disable optimization stopping redraw of other scrollbars */
7990 view->scrollbarsNeedingUpdate = 0;
7991 for (i =[subs count]-1; i >= 0; i--)
7992 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
7993 view->scrollbarsNeedingUpdate++;
7994 [sview addSubview: self];
7997 /* [self setFrame: r]; */
8003 - (void)setFrame: (NSRect)newRect
8005 NSTRACE ("[EmacsScroller setFrame:]");
8007 /* block_input (); */
8008 pixel_height = NSHeight (newRect);
8009 if (pixel_height == 0) pixel_height = 1;
8010 min_portion = 20 / pixel_height;
8011 [super setFrame: newRect];
8012 /* unblock_input (); */
8018 NSTRACE ("[EmacsScroller dealloc]");
8020 wset_vertical_scroll_bar (window, Qnil);
8028 NSTRACE ("[EmacsScroller condemn]");
8036 NSTRACE ("[EmacsScroller reprieve]");
8044 NSTRACE ("[EmacsScroller judge]");
8045 bool ret = condemned;
8050 /* ensure other scrollbar updates after deletion */
8051 view = (EmacsView *)FRAME_NS_VIEW (frame);
8053 view->scrollbarsNeedingUpdate++;
8055 wset_vertical_scroll_bar (window, Qnil);
8057 [self removeFromSuperview];
8065 - (void)resetCursorRects
8067 NSRect visible = [self visibleRect];
8068 NSTRACE ("[EmacsScroller resetCursorRects]");
8070 if (!NSIsEmptyRect (visible))
8071 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
8072 [[NSCursor arrowCursor] setOnMouseEntered: YES];
8076 - (int) checkSamePosition: (int) position portion: (int) portion
8079 return em_position ==position && em_portion ==portion && em_whole ==whole
8080 && portion != whole; /* needed for resize empty buf */
8084 - setPosition: (int)position portion: (int)portion whole: (int)whole
8086 NSTRACE ("[EmacsScroller setPosition:portion:whole:]");
8088 em_position = position;
8089 em_portion = portion;
8092 if (portion >= whole)
8094 #ifdef NS_IMPL_COCOA
8095 [self setKnobProportion: 1.0];
8096 [self setDoubleValue: 1.0];
8098 [self setFloatValue: 0.0 knobProportion: 1.0];
8105 portion = max ((float)whole*min_portion/pixel_height, portion);
8106 pos = (float)position / (whole - portion);
8107 por = (CGFloat)portion/whole;
8108 #ifdef NS_IMPL_COCOA
8109 [self setKnobProportion: por];
8110 [self setDoubleValue: pos];
8112 [self setFloatValue: pos knobProportion: por];
8119 /* set up emacs_event */
8120 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
8124 NSTRACE ("[EmacsScroller sendScrollEventAtLoc:fromEvent:]");
8129 emacs_event->part = last_hit_part;
8130 emacs_event->code = 0;
8131 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
8132 XSETWINDOW (win, window);
8133 emacs_event->frame_or_window = win;
8134 emacs_event->timestamp = EV_TIMESTAMP (e);
8135 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
8136 emacs_event->arg = Qnil;
8137 XSETINT (emacs_event->x, loc * pixel_height);
8138 XSETINT (emacs_event->y, pixel_height-20);
8142 n_emacs_events_pending++;
8143 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
8146 hold_event (emacs_event);
8147 EVENT_INIT (*emacs_event);
8148 ns_send_appdefined (-1);
8152 /* called manually thru timer to implement repeated button action w/hold-down */
8153 - repeatScroll: (NSTimer *)scrollEntry
8155 NSEvent *e = [[self window] currentEvent];
8156 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
8157 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
8159 NSTRACE ("[EmacsScroller repeatScroll:]");
8161 /* clear timer if need be */
8162 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
8164 [scroll_repeat_entry invalidate];
8165 [scroll_repeat_entry release];
8166 scroll_repeat_entry = nil;
8172 = [[NSTimer scheduledTimerWithTimeInterval:
8173 SCROLL_BAR_CONTINUOUS_DELAY
8175 selector: @selector (repeatScroll:)
8181 [self sendScrollEventAtLoc: 0 fromEvent: e];
8186 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
8187 mouseDragged events without going into a modal loop. */
8188 - (void)mouseDown: (NSEvent *)e
8191 /* hitPart is only updated AFTER event is passed on */
8192 NSScrollerPart part = [self testPart: [e locationInWindow]];
8193 CGFloat inc = 0.0, loc, kloc, pos;
8196 NSTRACE ("[EmacsScroller mouseDown:]");
8200 case NSScrollerDecrementPage:
8201 last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
8202 case NSScrollerIncrementPage:
8203 last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
8204 case NSScrollerDecrementLine:
8205 last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
8206 case NSScrollerIncrementLine:
8207 last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
8208 case NSScrollerKnob:
8209 last_hit_part = scroll_bar_handle; break;
8210 case NSScrollerKnobSlot: /* GNUstep-only */
8211 last_hit_part = scroll_bar_move_ratio; break;
8212 default: /* NSScrollerNoPart? */
8213 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
8220 pos = 0; /* ignored */
8222 /* set a timer to repeat, as we can't let superclass do this modally */
8224 = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
8226 selector: @selector (repeatScroll:)
8233 /* handle, or on GNUstep possibly slot */
8234 NSEvent *fake_event;
8236 /* compute float loc in slot and mouse offset on knob */
8237 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
8239 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
8245 else if (loc >= NSHeight (sr))
8247 loc = NSHeight (sr);
8255 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
8257 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
8259 last_mouse_offset = kloc;
8261 /* if knob, tell emacs a location offset by knob pos
8262 (to indicate top of handle) */
8263 if (part == NSScrollerKnob)
8264 pos = (loc - last_mouse_offset) / NSHeight (sr);
8266 /* else this is a slot click on GNUstep: go straight there */
8267 pos = loc / NSHeight (sr);
8269 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
8270 fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
8271 location: [e locationInWindow]
8272 modifierFlags: [e modifierFlags]
8273 timestamp: [e timestamp]
8274 windowNumber: [e windowNumber]
8275 context: [e context]
8276 eventNumber: [e eventNumber]
8277 clickCount: [e clickCount]
8278 pressure: [e pressure]];
8279 [super mouseUp: fake_event];
8282 if (part != NSScrollerKnob)
8283 [self sendScrollEventAtLoc: pos fromEvent: e];
8287 /* Called as we manually track scroller drags, rather than superclass. */
8288 - (void)mouseDragged: (NSEvent *)e
8293 NSTRACE ("[EmacsScroller mouseDragged:]");
8295 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
8297 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
8303 else if (loc >= NSHeight (sr) + last_mouse_offset)
8305 loc = NSHeight (sr) + last_mouse_offset;
8308 pos = (loc - last_mouse_offset) / NSHeight (sr);
8309 [self sendScrollEventAtLoc: pos fromEvent: e];
8313 - (void)mouseUp: (NSEvent *)e
8315 NSTRACE ("[EmacsScroller mouseUp:]");
8317 if (scroll_repeat_entry)
8319 [scroll_repeat_entry invalidate];
8320 [scroll_repeat_entry release];
8321 scroll_repeat_entry = nil;
8323 last_hit_part = scroll_bar_above_handle;
8327 /* treat scrollwheel events in the bar as though they were in the main window */
8328 - (void) scrollWheel: (NSEvent *)theEvent
8330 NSTRACE ("[EmacsScroller scrollWheel:]");
8332 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
8333 [view mouseDown: theEvent];
8336 @end /* EmacsScroller */
8339 #ifdef NS_IMPL_GNUSTEP
8340 /* Dummy class to get rid of startup warnings. */
8341 @implementation EmacsDocument
8347 /* ==========================================================================
8349 Font-related functions; these used to be in nsfaces.m
8351 ========================================================================== */
8355 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
8357 struct font *font = XFONT_OBJECT (font_object);
8358 EmacsView *view = FRAME_NS_VIEW (f);
8359 int font_ascent, font_descent;
8362 fontset = fontset_from_font (font_object);
8363 FRAME_FONTSET (f) = fontset;
8365 if (FRAME_FONT (f) == font)
8366 /* This font is already set in frame F. There's nothing more to
8370 FRAME_FONT (f) = font;
8372 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
8373 FRAME_COLUMN_WIDTH (f) = font->average_width;
8374 get_font_ascent_descent (font, &font_ascent, &font_descent);
8375 FRAME_LINE_HEIGHT (f) = font_ascent + font_descent;
8377 /* Compute the scroll bar width in character columns. */
8378 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
8380 int wid = FRAME_COLUMN_WIDTH (f);
8381 FRAME_CONFIG_SCROLL_BAR_COLS (f)
8382 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
8386 int wid = FRAME_COLUMN_WIDTH (f);
8387 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
8390 /* Compute the scroll bar height in character lines. */
8391 if (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) > 0)
8393 int height = FRAME_LINE_HEIGHT (f);
8394 FRAME_CONFIG_SCROLL_BAR_LINES (f)
8395 = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + height - 1) / height;
8399 int height = FRAME_LINE_HEIGHT (f);
8400 FRAME_CONFIG_SCROLL_BAR_LINES (f) = (14 + height - 1) / height;
8403 /* Now make the frame display the given font. */
8404 if (FRAME_NS_WINDOW (f) != 0 && ! [view isFullscreen])
8405 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
8406 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 3,
8413 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
8414 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
8418 ns_xlfd_to_fontname (const char *xlfd)
8419 /* --------------------------------------------------------------------------
8420 Convert an X font name (XLFD) to an NS font name.
8421 Only family is used.
8422 The string returned is temporarily allocated.
8423 -------------------------------------------------------------------------- */
8425 char *name = xmalloc (180);
8429 if (!strncmp (xlfd, "--", 2))
8430 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
8432 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
8434 /* stopgap for malformed XLFD input */
8435 if (strlen (name) == 0)
8436 strcpy (name, "Monaco");
8438 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
8439 also uppercase after '-' or ' ' */
8440 name[0] = c_toupper (name[0]);
8441 for (len =strlen (name), i =0; i<len; i++)
8447 name[i+1] = c_toupper (name[i+1]);
8449 else if (name[i] == '_')
8453 name[i+1] = c_toupper (name[i+1]);
8456 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
8457 ret = [[NSString stringWithUTF8String: name] UTF8String];
8464 syms_of_nsterm (void)
8466 NSTRACE ("syms_of_nsterm");
8468 ns_antialias_threshold = 10.0;
8470 /* from 23+ we need to tell emacs what modifiers there are.. */
8471 DEFSYM (Qmodifier_value, "modifier-value");
8472 DEFSYM (Qalt, "alt");
8473 DEFSYM (Qhyper, "hyper");
8474 DEFSYM (Qmeta, "meta");
8475 DEFSYM (Qsuper, "super");
8476 DEFSYM (Qcontrol, "control");
8477 DEFSYM (QUTF8_STRING, "UTF8_STRING");
8479 DEFSYM (Qfile, "file");
8480 DEFSYM (Qurl, "url");
8482 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
8483 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
8484 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
8485 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
8486 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
8488 DEFVAR_LISP ("ns-input-file", ns_input_file,
8489 "The file specified in the last NS event.");
8490 ns_input_file =Qnil;
8492 DEFVAR_LISP ("ns-working-text", ns_working_text,
8493 "String for visualizing working composition sequence.");
8494 ns_working_text =Qnil;
8496 DEFVAR_LISP ("ns-input-font", ns_input_font,
8497 "The font specified in the last NS event.");
8498 ns_input_font =Qnil;
8500 DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
8501 "The fontsize specified in the last NS event.");
8502 ns_input_fontsize =Qnil;
8504 DEFVAR_LISP ("ns-input-line", ns_input_line,
8505 "The line specified in the last NS event.");
8506 ns_input_line =Qnil;
8508 DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
8509 "The service name specified in the last NS event.");
8510 ns_input_spi_name =Qnil;
8512 DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
8513 "The service argument specified in the last NS event.");
8514 ns_input_spi_arg =Qnil;
8516 DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
8517 "This variable describes the behavior of the alternate or option key.\n\
8518 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8519 Set to none means that the alternate / option key is not interpreted by Emacs\n\
8520 at all, allowing it to be used at a lower level for accented character entry.");
8521 ns_alternate_modifier = Qmeta;
8523 DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
8524 "This variable describes the behavior of the right alternate or option key.\n\
8525 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8526 Set to left means be the same key as `ns-alternate-modifier'.\n\
8527 Set to none means that the alternate / option key is not interpreted by Emacs\n\
8528 at all, allowing it to be used at a lower level for accented character entry.");
8529 ns_right_alternate_modifier = Qleft;
8531 DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
8532 "This variable describes the behavior of the command key.\n\
8533 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
8534 ns_command_modifier = Qsuper;
8536 DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
8537 "This variable describes the behavior of the right command key.\n\
8538 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8539 Set to left means be the same key as `ns-command-modifier'.\n\
8540 Set to none means that the command / option key is not interpreted by Emacs\n\
8541 at all, allowing it to be used at a lower level for accented character entry.");
8542 ns_right_command_modifier = Qleft;
8544 DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
8545 "This variable describes the behavior of the control key.\n\
8546 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
8547 ns_control_modifier = Qcontrol;
8549 DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
8550 "This variable describes the behavior of the right control key.\n\
8551 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8552 Set to left means be the same key as `ns-control-modifier'.\n\
8553 Set to none means that the control / option key is not interpreted by Emacs\n\
8554 at all, allowing it to be used at a lower level for accented character entry.");
8555 ns_right_control_modifier = Qleft;
8557 DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
8558 "This variable describes the behavior of the function key (on laptops).\n\
8559 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
8560 Set to none means that the function key is not interpreted by Emacs at all,\n\
8561 allowing it to be used at a lower level for accented character entry.");
8562 ns_function_modifier = Qnone;
8564 DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
8565 "Non-nil (the default) means to render text antialiased.");
8566 ns_antialias_text = Qt;
8568 DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
8569 "Whether to confirm application quit using dialog.");
8570 ns_confirm_quit = Qnil;
8572 DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
8573 doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
8574 Only works on OSX 10.6 or later. */);
8575 ns_auto_hide_menu_bar = Qnil;
8577 DEFVAR_BOOL ("ns-use-native-fullscreen", ns_use_native_fullscreen,
8578 doc: /*Non-nil means to use native fullscreen on OSX >= 10.7.
8579 Nil means use fullscreen the old (< 10.7) way. The old way works better with
8580 multiple monitors, but lacks tool bar. This variable is ignored on OSX < 10.7.
8581 Default is t for OSX >= 10.7, nil otherwise. */);
8582 #ifdef HAVE_NATIVE_FS
8583 ns_use_native_fullscreen = YES;
8585 ns_use_native_fullscreen = NO;
8587 ns_last_use_native_fullscreen = ns_use_native_fullscreen;
8589 DEFVAR_BOOL ("ns-use-fullscreen-animation", ns_use_fullscreen_animation,
8590 doc: /*Non-nil means use animation on non-native fullscreen.
8591 For native fullscreen, this does nothing.
8592 Default is nil. */);
8593 ns_use_fullscreen_animation = NO;
8595 DEFVAR_BOOL ("ns-use-srgb-colorspace", ns_use_srgb_colorspace,
8596 doc: /*Non-nil means to use sRGB colorspace on OSX >= 10.7.
8597 Note that this does not apply to images.
8598 This variable is ignored on OSX < 10.7 and GNUstep. */);
8599 ns_use_srgb_colorspace = YES;
8601 /* TODO: move to common code */
8602 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
8603 doc: /* Which toolkit scroll bars Emacs uses, if any.
8604 A value of nil means Emacs doesn't use toolkit scroll bars.
8605 With the X Window system, the value is a symbol describing the
8606 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
8607 With MS Windows or Nextstep, the value is t. */);
8608 Vx_toolkit_scroll_bars = Qt;
8610 DEFVAR_BOOL ("x-use-underline-position-properties",
8611 x_use_underline_position_properties,
8612 doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
8613 A value of nil means ignore them. If you encounter fonts with bogus
8614 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
8615 to 4.1, set this to nil. */);
8616 x_use_underline_position_properties = 0;
8618 DEFVAR_BOOL ("x-underline-at-descent-line",
8619 x_underline_at_descent_line,
8620 doc: /* Non-nil means to draw the underline at the same place as the descent line.
8621 A value of nil means to draw the underline according to the value of the
8622 variable `x-use-underline-position-properties', which is usually at the
8623 baseline level. The default value is nil. */);
8624 x_underline_at_descent_line = 0;
8626 /* Tell Emacs about this window system. */
8627 Fprovide (Qns, Qnil);
8629 DEFSYM (Qcocoa, "cocoa");
8630 DEFSYM (Qgnustep, "gnustep");
8632 #ifdef NS_IMPL_COCOA
8633 Fprovide (Qcocoa, Qnil);
8636 Fprovide (Qgnustep, Qnil);