1 /* NeXT/Open/GNUstep / MacOSX communication module.
3 Copyright (C) 1989, 1993-1994, 2005-2006, 2008-2015 Free Software
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 Originally by Carl Edman
23 Updated by Christian Limpach (chris@nice.ch)
24 OpenStep/Rhapsody port by Scott Bender (sbender@harmony-ds.com)
25 MacOSX/Aqua port by Christophe de Dinechin (descubes@earthlink.net)
26 GNUstep port and post-20 update by Adrian Robert (arobert@cogsci.ucsd.edu)
29 /* This should be the first include, as it may set up #defines affecting
30 interpretation of even the system includes. */
36 #include <sys/types.h>
42 #include <c-strcase.h>
46 #include "blockinput.h"
47 #include "sysselect.h"
50 #include "character.h"
52 #include "composite.h"
55 #include "termhooks.h"
63 #ifdef NS_IMPL_GNUSTEP
73 int term_trace_num = 0;
74 #define NSTRACE(x) fprintf (stderr, "%s:%d: [%d] " #x "\n", \
75 __FILE__, __LINE__, ++term_trace_num)
80 /* Detailed tracing. "S" means "size" and "LL" stands for "lower left". */
82 int term_trace_num = 0;
83 #define NSTRACE_SIZE(str,size) fprintf (stderr, \
85 " (S:%.0f x %.0f)\n", \
86 __FILE__, __LINE__, ++term_trace_num,\
89 #define NSTRACE_RECT(s,r) fprintf (stderr, \
91 " (LL:%.0f x %.0f -> S:%.0f x %.0f)\n", \
92 __FILE__, __LINE__, ++term_trace_num,\
98 #define NSTRACE_SIZE(str,size)
99 #define NSTRACE_RECT(s,r)
102 extern NSString *NSMenuDidBeginTrackingNotification;
104 /* ==========================================================================
106 NSColor, EmacsColor category.
108 ========================================================================== */
109 @implementation NSColor (EmacsColor)
110 + (NSColor *)colorForEmacsRed:(CGFloat)red green:(CGFloat)green
111 blue:(CGFloat)blue alpha:(CGFloat)alpha
114 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
115 if (ns_use_srgb_colorspace)
116 return [NSColor colorWithSRGBRed: red
122 return [NSColor colorWithCalibratedRed: red
128 - (NSColor *)colorUsingDefaultColorSpace
131 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
132 if (ns_use_srgb_colorspace)
133 return [self colorUsingColorSpace: [NSColorSpace sRGBColorSpace]];
136 return [self colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
141 /* ==========================================================================
145 ========================================================================== */
147 /* Convert a symbol indexed with an NSxxx value to a value as defined
148 in keyboard.c (lispy_function_key). I hope this is a correct way
149 of doing things... */
150 static unsigned convert_ns_to_X_keysym[] =
152 NSHomeFunctionKey, 0x50,
153 NSLeftArrowFunctionKey, 0x51,
154 NSUpArrowFunctionKey, 0x52,
155 NSRightArrowFunctionKey, 0x53,
156 NSDownArrowFunctionKey, 0x54,
157 NSPageUpFunctionKey, 0x55,
158 NSPageDownFunctionKey, 0x56,
159 NSEndFunctionKey, 0x57,
160 NSBeginFunctionKey, 0x58,
161 NSSelectFunctionKey, 0x60,
162 NSPrintFunctionKey, 0x61,
163 NSClearLineFunctionKey, 0x0B,
164 NSExecuteFunctionKey, 0x62,
165 NSInsertFunctionKey, 0x63,
166 NSUndoFunctionKey, 0x65,
167 NSRedoFunctionKey, 0x66,
168 NSMenuFunctionKey, 0x67,
169 NSFindFunctionKey, 0x68,
170 NSHelpFunctionKey, 0x6A,
171 NSBreakFunctionKey, 0x6B,
173 NSF1FunctionKey, 0xBE,
174 NSF2FunctionKey, 0xBF,
175 NSF3FunctionKey, 0xC0,
176 NSF4FunctionKey, 0xC1,
177 NSF5FunctionKey, 0xC2,
178 NSF6FunctionKey, 0xC3,
179 NSF7FunctionKey, 0xC4,
180 NSF8FunctionKey, 0xC5,
181 NSF9FunctionKey, 0xC6,
182 NSF10FunctionKey, 0xC7,
183 NSF11FunctionKey, 0xC8,
184 NSF12FunctionKey, 0xC9,
185 NSF13FunctionKey, 0xCA,
186 NSF14FunctionKey, 0xCB,
187 NSF15FunctionKey, 0xCC,
188 NSF16FunctionKey, 0xCD,
189 NSF17FunctionKey, 0xCE,
190 NSF18FunctionKey, 0xCF,
191 NSF19FunctionKey, 0xD0,
192 NSF20FunctionKey, 0xD1,
193 NSF21FunctionKey, 0xD2,
194 NSF22FunctionKey, 0xD3,
195 NSF23FunctionKey, 0xD4,
196 NSF24FunctionKey, 0xD5,
198 NSBackspaceCharacter, 0x08, /* 8: Not on some KBs. */
199 NSDeleteCharacter, 0xFF, /* 127: Big 'delete' key upper right. */
200 NSDeleteFunctionKey, 0x9F, /* 63272: Del forw key off main array. */
202 NSTabCharacter, 0x09,
203 0x19, 0x09, /* left tab->regular since pass shift */
204 NSCarriageReturnCharacter, 0x0D,
205 NSNewlineCharacter, 0x0D,
206 NSEnterCharacter, 0x8D,
208 0x41|NSNumericPadKeyMask, 0xAE, /* KP_Decimal */
209 0x43|NSNumericPadKeyMask, 0xAA, /* KP_Multiply */
210 0x45|NSNumericPadKeyMask, 0xAB, /* KP_Add */
211 0x4B|NSNumericPadKeyMask, 0xAF, /* KP_Divide */
212 0x4E|NSNumericPadKeyMask, 0xAD, /* KP_Subtract */
213 0x51|NSNumericPadKeyMask, 0xBD, /* KP_Equal */
214 0x52|NSNumericPadKeyMask, 0xB0, /* KP_0 */
215 0x53|NSNumericPadKeyMask, 0xB1, /* KP_1 */
216 0x54|NSNumericPadKeyMask, 0xB2, /* KP_2 */
217 0x55|NSNumericPadKeyMask, 0xB3, /* KP_3 */
218 0x56|NSNumericPadKeyMask, 0xB4, /* KP_4 */
219 0x57|NSNumericPadKeyMask, 0xB5, /* KP_5 */
220 0x58|NSNumericPadKeyMask, 0xB6, /* KP_6 */
221 0x59|NSNumericPadKeyMask, 0xB7, /* KP_7 */
222 0x5B|NSNumericPadKeyMask, 0xB8, /* KP_8 */
223 0x5C|NSNumericPadKeyMask, 0xB9, /* KP_9 */
225 0x1B, 0x1B /* escape */
228 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
229 the maximum font size to NOT antialias. On GNUstep there is currently
230 no way to control this behavior. */
231 float ns_antialias_threshold;
233 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
234 NSString *ns_app_name = @"Emacs"; /* default changed later */
236 /* Display variables */
237 struct ns_display_info *x_display_list; /* Chain of existing displays */
238 long context_menu_value = 0;
241 static struct frame *ns_updating_frame;
242 static NSView *focus_view = NULL;
243 static int ns_window_num = 0;
244 #ifdef NS_IMPL_GNUSTEP
247 static BOOL gsaved = NO;
248 static BOOL ns_fake_keydown = NO;
250 static BOOL ns_menu_bar_is_hidden = NO;
252 /*static int debug_lock = 0; */
255 static BOOL send_appdefined = YES;
256 #define NO_APPDEFINED_DATA (-8)
257 static int last_appdefined_event_data = NO_APPDEFINED_DATA;
258 static NSTimer *timed_entry = 0;
259 static NSTimer *scroll_repeat_entry = nil;
260 static fd_set select_readfds, select_writefds;
261 enum { SELECT_HAVE_READ = 1, SELECT_HAVE_WRITE = 2, SELECT_HAVE_TMO = 4 };
262 static int select_nfds = 0, select_valid = 0;
263 static struct timespec select_timeout = { 0, 0 };
264 static int selfds[2] = { -1, -1 };
265 static pthread_mutex_t select_mutex;
266 static int apploopnr = 0;
267 static NSAutoreleasePool *outerpool;
268 static struct input_event *emacs_event = NULL;
269 static struct input_event *q_event_ptr = NULL;
270 static int n_emacs_events_pending = 0;
271 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
272 *ns_pending_service_args;
273 static BOOL ns_do_open_file = NO;
274 static BOOL ns_last_use_native_fullscreen;
276 /* Non-zero means that a HELP_EVENT has been generated since Emacs
279 static BOOL any_help_event_p = NO;
282 struct input_event *q;
288 static NSString *represented_filename = nil;
289 static struct frame *represented_frame = 0;
293 * State for pending menu activation:
294 * MENU_NONE Normal state
295 * MENU_PENDING A menu has been clicked on, but has been canceled so we can
296 * run lisp to update the menu.
297 * MENU_OPENING Menu is up to date, and the click event is redone so the menu
301 #define MENU_PENDING 1
302 #define MENU_OPENING 2
303 static int menu_will_open_state = MENU_NONE;
305 /* Saved position for menu click. */
306 static CGPoint menu_mouse_point;
309 /* Convert modifiers in a NeXTstep event to emacs style modifiers. */
310 #define NS_FUNCTION_KEY_MASK 0x800000
311 #define NSLeftControlKeyMask (0x000001 | NSControlKeyMask)
312 #define NSRightControlKeyMask (0x002000 | NSControlKeyMask)
313 #define NSLeftCommandKeyMask (0x000008 | NSCommandKeyMask)
314 #define NSRightCommandKeyMask (0x000010 | NSCommandKeyMask)
315 #define NSLeftAlternateKeyMask (0x000020 | NSAlternateKeyMask)
316 #define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
317 #define EV_MODIFIERS2(flags) \
318 (((flags & NSHelpKeyMask) ? \
319 hyper_modifier : 0) \
320 | (!EQ (ns_right_alternate_modifier, Qleft) && \
321 ((flags & NSRightAlternateKeyMask) \
322 == NSRightAlternateKeyMask) ? \
323 parse_solitary_modifier (ns_right_alternate_modifier) : 0) \
324 | ((flags & NSAlternateKeyMask) ? \
325 parse_solitary_modifier (ns_alternate_modifier) : 0) \
326 | ((flags & NSShiftKeyMask) ? \
327 shift_modifier : 0) \
328 | (!EQ (ns_right_control_modifier, Qleft) && \
329 ((flags & NSRightControlKeyMask) \
330 == NSRightControlKeyMask) ? \
331 parse_solitary_modifier (ns_right_control_modifier) : 0) \
332 | ((flags & NSControlKeyMask) ? \
333 parse_solitary_modifier (ns_control_modifier) : 0) \
334 | ((flags & NS_FUNCTION_KEY_MASK) ? \
335 parse_solitary_modifier (ns_function_modifier) : 0) \
336 | (!EQ (ns_right_command_modifier, Qleft) && \
337 ((flags & NSRightCommandKeyMask) \
338 == NSRightCommandKeyMask) ? \
339 parse_solitary_modifier (ns_right_command_modifier) : 0) \
340 | ((flags & NSCommandKeyMask) ? \
341 parse_solitary_modifier (ns_command_modifier):0))
342 #define EV_MODIFIERS(e) EV_MODIFIERS2 ([e modifierFlags])
344 #define EV_UDMODIFIERS(e) \
345 ((([e type] == NSLeftMouseDown) ? down_modifier : 0) \
346 | (([e type] == NSRightMouseDown) ? down_modifier : 0) \
347 | (([e type] == NSOtherMouseDown) ? down_modifier : 0) \
348 | (([e type] == NSLeftMouseDragged) ? down_modifier : 0) \
349 | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
350 | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
351 | (([e type] == NSLeftMouseUp) ? up_modifier : 0) \
352 | (([e type] == NSRightMouseUp) ? up_modifier : 0) \
353 | (([e type] == NSOtherMouseUp) ? up_modifier : 0))
355 #define EV_BUTTON(e) \
356 ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 : \
357 (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
358 [e buttonNumber] - 1)
360 /* Convert the time field to a timestamp in milliseconds. */
361 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
363 /* This is a piece of code which is common to all the event handling
364 methods. Maybe it should even be a function. */
365 #define EV_TRAILER(e) \
367 XSETFRAME (emacs_event->frame_or_window, emacsframe); \
371 #define EV_TRAILER2(e) \
373 if (e) emacs_event->timestamp = EV_TIMESTAMP (e); \
376 n_emacs_events_pending++; \
377 kbd_buffer_store_event_hold (emacs_event, q_event_ptr); \
380 hold_event (emacs_event); \
381 EVENT_INIT (*emacs_event); \
382 ns_send_appdefined (-1); \
385 /* TODO: get rid of need for these forward declarations */
386 static void ns_condemn_scroll_bars (struct frame *f);
387 static void ns_judge_scroll_bars (struct frame *f);
388 void x_set_frame_alpha (struct frame *f);
391 /* ==========================================================================
395 ========================================================================== */
398 ns_set_represented_filename (NSString* fstr, struct frame *f)
400 represented_filename = [fstr retain];
401 represented_frame = f;
405 ns_init_events (struct input_event* ev)
418 hold_event (struct input_event *event)
420 if (hold_event_q.nr == hold_event_q.cap)
422 if (hold_event_q.cap == 0) hold_event_q.cap = 10;
423 else hold_event_q.cap *= 2;
425 xrealloc (hold_event_q.q, hold_event_q.cap * sizeof *hold_event_q.q);
428 hold_event_q.q[hold_event_q.nr++] = *event;
429 /* Make sure ns_read_socket is called, i.e. we have input. */
431 send_appdefined = YES;
435 append2 (Lisp_Object list, Lisp_Object item)
436 /* --------------------------------------------------------------------------
437 Utility to append to a list
438 -------------------------------------------------------------------------- */
440 Lisp_Object array[2];
442 array[1] = list1 (item);
443 return Fnconc (2, &array[0]);
448 ns_etc_directory (void)
449 /* If running as a self-contained app bundle, return as a string the
450 filename of the etc directory, if present; else nil. */
452 NSBundle *bundle = [NSBundle mainBundle];
453 NSString *resourceDir = [bundle resourcePath];
454 NSString *resourcePath;
455 NSFileManager *fileManager = [NSFileManager defaultManager];
458 resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
459 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
461 if (isDir) return [resourcePath UTF8String];
469 /* If running as a self-contained app bundle, return as a path string
470 the filenames of the libexec and bin directories, ie libexec:bin.
471 Otherwise, return nil.
472 Normally, Emacs does not add its own bin/ directory to the PATH.
473 However, a self-contained NS build has a different layout, with
474 bin/ and libexec/ subdirectories in the directory that contains
476 We put libexec first, because init_callproc_1 uses the first
477 element to initialize exec-directory. An alternative would be
478 for init_callproc to check for invocation-directory/libexec.
481 NSBundle *bundle = [NSBundle mainBundle];
482 NSString *resourceDir = [bundle resourcePath];
483 NSString *binDir = [bundle bundlePath];
484 NSString *resourcePath, *resourcePaths;
486 NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
487 NSFileManager *fileManager = [NSFileManager defaultManager];
489 NSEnumerator *pathEnum;
492 range = [resourceDir rangeOfString: @"Contents"];
493 if (range.location != NSNotFound)
495 binDir = [binDir stringByAppendingPathComponent: @"Contents"];
497 binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
501 paths = [binDir stringsByAppendingPaths:
502 [NSArray arrayWithObjects: @"libexec", @"bin", nil]];
503 pathEnum = [paths objectEnumerator];
506 while ((resourcePath = [pathEnum nextObject]))
508 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
511 if ([resourcePaths length] > 0)
513 = [resourcePaths stringByAppendingString: pathSeparator];
515 = [resourcePaths stringByAppendingString: resourcePath];
518 if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
526 /* If running as a self-contained app bundle, return as a path string
527 the filenames of the site-lisp and lisp directories.
528 Ie, site-lisp:lisp. Otherwise, return nil. */
530 NSBundle *bundle = [NSBundle mainBundle];
531 NSString *resourceDir = [bundle resourcePath];
532 NSString *resourcePath, *resourcePaths;
533 NSString *pathSeparator = [NSString stringWithFormat: @"%c", SEPCHAR];
534 NSFileManager *fileManager = [NSFileManager defaultManager];
536 NSArray *paths = [resourceDir stringsByAppendingPaths:
537 [NSArray arrayWithObjects:
538 @"site-lisp", @"lisp", nil]];
539 NSEnumerator *pathEnum = [paths objectEnumerator];
542 /* Hack to skip site-lisp. */
543 if (no_site_lisp) resourcePath = [pathEnum nextObject];
545 while ((resourcePath = [pathEnum nextObject]))
547 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
550 if ([resourcePaths length] > 0)
552 = [resourcePaths stringByAppendingString: pathSeparator];
554 = [resourcePaths stringByAppendingString: resourcePath];
557 if ([resourcePaths length] > 0) return [resourcePaths UTF8String];
563 ns_timeout (int usecs)
564 /* --------------------------------------------------------------------------
565 Blocking timer utility used by ns_ring_bell
566 -------------------------------------------------------------------------- */
568 struct timespec wakeup = timespec_add (current_timespec (),
569 make_timespec (0, usecs * 1000));
571 /* Keep waiting until past the time wakeup. */
574 struct timespec timeout, now = current_timespec ();
575 if (timespec_cmp (wakeup, now) <= 0)
577 timeout = timespec_sub (wakeup, now);
579 /* Try to wait that long--but we might wake up sooner. */
580 pselect (0, NULL, NULL, NULL, &timeout, NULL);
586 ns_release_object (void *obj)
587 /* --------------------------------------------------------------------------
588 Release an object (callable from C)
589 -------------------------------------------------------------------------- */
596 ns_retain_object (void *obj)
597 /* --------------------------------------------------------------------------
598 Retain an object (callable from C)
599 -------------------------------------------------------------------------- */
606 ns_alloc_autorelease_pool (void)
607 /* --------------------------------------------------------------------------
608 Allocate a pool for temporary objects (callable from C)
609 -------------------------------------------------------------------------- */
611 return [[NSAutoreleasePool alloc] init];
616 ns_release_autorelease_pool (void *pool)
617 /* --------------------------------------------------------------------------
618 Free a pool and temporary objects it refers to (callable from C)
619 -------------------------------------------------------------------------- */
621 ns_release_object (pool);
626 /* ==========================================================================
628 Focus (clipping) and screen update
630 ========================================================================== */
633 // Window constraining
634 // -------------------
636 // To ensure that the windows are not placed under the menu bar, they
637 // are typically moved by the call-back constrainFrameRect. However,
638 // by overriding it, it's possible to inhibit this, leaving the window
639 // in it's original position.
641 // It's possible to hide the menu bar. However, technically, it's only
642 // possible to hide it when the application is active. To ensure that
643 // this work properly, the menu bar and window constraining are
644 // deferred until the application becomes active.
646 // Even though it's not possible to manually move a window above the
647 // top of the screen, it is allowed if it's done programmatically,
648 // when the menu is hidden. This allows the editable area to cover the
649 // full screen height.
654 // Use the following extra files:
657 // ;; Hide menu and place frame slightly above the top of the screen.
658 // (setq ns-auto-hide-menu-bar t)
659 // (set-frame-position (selected-frame) 0 -20)
663 // emacs -Q -l init.el
665 // Result: No menu bar, and the title bar should be above the screen.
671 // Result: Menu bar visible, frame placed immediately below the menu.
675 ns_constrain_all_frames (void)
677 Lisp_Object tail, frame;
679 FOR_EACH_FRAME (tail, frame)
681 struct frame *f = XFRAME (frame);
684 NSView *view = FRAME_NS_VIEW (f);
685 /* This no-op will trigger the default window placing
686 * constraint system. */
687 [[view window] setFrameOrigin:[[view window] frame].origin];
693 /* True, if the menu bar should be hidden. */
696 ns_menu_bar_should_be_hidden (void)
698 return !NILP (ns_auto_hide_menu_bar)
699 && [NSApp respondsToSelector:@selector(setPresentationOptions:)];
703 /* Show or hide the menu bar, based on user setting. */
706 ns_update_auto_hide_menu_bar (void)
711 NSTRACE (ns_update_auto_hide_menu_bar);
713 if (NSApp != nil && [NSApp isActive])
715 // Note, "setPresentationOptions" triggers an error unless the
716 // application is active.
717 BOOL menu_bar_should_be_hidden = ns_menu_bar_should_be_hidden ();
719 if (menu_bar_should_be_hidden != ns_menu_bar_is_hidden)
721 NSApplicationPresentationOptions options
722 = NSApplicationPresentationDefault;
724 if (menu_bar_should_be_hidden)
725 options |= NSApplicationPresentationAutoHideMenuBar
726 | NSApplicationPresentationAutoHideDock;
728 [NSApp setPresentationOptions: options];
730 ns_menu_bar_is_hidden = menu_bar_should_be_hidden;
732 if (!ns_menu_bar_is_hidden)
734 ns_constrain_all_frames ();
745 ns_update_begin (struct frame *f)
746 /* --------------------------------------------------------------------------
747 Prepare for a grouped sequence of drawing calls
748 external (RIF) call; whole frame, called before update_window_begin
749 -------------------------------------------------------------------------- */
751 EmacsView *view = FRAME_NS_VIEW (f);
752 NSTRACE (ns_update_begin);
754 ns_update_auto_hide_menu_bar ();
757 if ([view isFullscreen] && [view fsIsNative])
759 // Fix reappearing tool bar in fullscreen for OSX 10.7
760 BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (f) ? YES : NO;
761 NSToolbar *toolbar = [FRAME_NS_VIEW (f) toolbar];
762 if (! tbar_visible != ! [toolbar isVisible])
763 [toolbar setVisible: tbar_visible];
767 ns_updating_frame = f;
770 /* drawRect may have been called for say the minibuffer, and then clip path
771 is for the minibuffer. But the display engine may draw more because
772 we have set the frame as garbaged. So reset clip path to the whole
777 NSRect r = [view frame];
778 NSRect cr = [[view window] frame];
779 /* If a large frame size is set, r may be larger than the window frame
780 before constrained. In that case don't change the clip path, as we
781 will clear in to the tool bar and title bar. */
783 + FRAME_NS_TITLEBAR_HEIGHT (f)
784 + FRAME_TOOLBAR_HEIGHT (f) <= cr.size.height)
786 bp = [[NSBezierPath bezierPathWithRect: r] retain];
793 #ifdef NS_IMPL_GNUSTEP
794 uRect = NSMakeRect (0, 0, 0, 0);
800 ns_update_window_begin (struct window *w)
801 /* --------------------------------------------------------------------------
802 Prepare for a grouped sequence of drawing calls
803 external (RIF) call; for one window, called after update_begin
804 -------------------------------------------------------------------------- */
806 struct frame *f = XFRAME (WINDOW_FRAME (w));
807 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
809 NSTRACE (ns_update_window_begin);
810 w->output_cursor = w->cursor;
814 if (f == hlinfo->mouse_face_mouse_frame)
816 /* Don't do highlighting for mouse motion during the update. */
817 hlinfo->mouse_face_defer = 1;
819 /* If the frame needs to be redrawn,
820 simply forget about any prior mouse highlighting. */
821 if (FRAME_GARBAGED_P (f))
822 hlinfo->mouse_face_window = Qnil;
824 /* (further code for mouse faces ifdef'd out in other terms elided) */
832 ns_update_window_end (struct window *w, bool cursor_on_p,
833 bool mouse_face_overwritten_p)
834 /* --------------------------------------------------------------------------
835 Finished a grouped sequence of drawing calls
836 external (RIF) call; for one window called before update_end
837 -------------------------------------------------------------------------- */
839 /* note: this fn is nearly identical in all terms */
840 if (!w->pseudo_window_p)
845 display_and_set_cursor (w, 1,
846 w->output_cursor.hpos, w->output_cursor.vpos,
847 w->output_cursor.x, w->output_cursor.y);
849 if (draw_window_fringes (w, 1))
851 if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
852 x_draw_right_divider (w);
854 x_draw_vertical_border (w);
860 /* If a row with mouse-face was overwritten, arrange for
861 frame_up_to_date to redisplay the mouse highlight. */
862 if (mouse_face_overwritten_p)
863 reset_mouse_highlight (MOUSE_HL_INFO (XFRAME (w->frame)));
865 NSTRACE (update_window_end);
870 ns_update_end (struct frame *f)
871 /* --------------------------------------------------------------------------
872 Finished a grouped sequence of drawing calls
873 external (RIF) call; for whole frame, called after update_window_end
874 -------------------------------------------------------------------------- */
876 EmacsView *view = FRAME_NS_VIEW (f);
878 /* if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
879 MOUSE_HL_INFO (f)->mouse_face_defer = 0;
884 [[view window] flushWindow];
887 ns_updating_frame = NULL;
888 NSTRACE (ns_update_end);
892 ns_focus (struct frame *f, NSRect *r, int n)
893 /* --------------------------------------------------------------------------
894 Internal: Focus on given frame. During small local updates this is used to
895 draw, however during large updates, ns_update_begin and ns_update_end are
896 called to wrap the whole thing, in which case these calls are stubbed out.
897 Except, on GNUstep, we accumulate the rectangle being drawn into, because
898 the back end won't do this automatically, and will just end up flushing
900 -------------------------------------------------------------------------- */
902 // NSTRACE (ns_focus);
904 fprintf (stderr, "focus: %d", c++);
905 if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
906 fprintf (stderr, "\n"); */
908 if (f != ns_updating_frame)
910 NSView *view = FRAME_NS_VIEW (f);
911 if (view != focus_view)
913 if (focus_view != NULL)
915 [focus_view unlockFocus];
916 [[focus_view window] flushWindow];
923 /*if (view) debug_lock++; */
930 [[NSGraphicsContext currentContext] saveGraphicsState];
932 NSRectClipList (r, 2);
941 ns_unfocus (struct frame *f)
942 /* --------------------------------------------------------------------------
943 Internal: Remove focus on given frame
944 -------------------------------------------------------------------------- */
946 // NSTRACE (ns_unfocus);
950 [[NSGraphicsContext currentContext] restoreGraphicsState];
954 if (f != ns_updating_frame)
956 if (focus_view != NULL)
958 [focus_view unlockFocus];
959 [[focus_view window] flushWindow];
968 ns_clip_to_row (struct window *w, struct glyph_row *row,
969 enum glyph_row_area area, BOOL gc)
970 /* --------------------------------------------------------------------------
971 Internal (but parallels other terms): Focus drawing on given row
972 -------------------------------------------------------------------------- */
974 struct frame *f = XFRAME (WINDOW_FRAME (w));
976 int window_x, window_y, window_width;
978 window_box (w, area, &window_x, &window_y, &window_width, 0);
980 clip_rect.origin.x = window_x;
981 clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
982 clip_rect.origin.y = max (clip_rect.origin.y, window_y);
983 clip_rect.size.width = window_width;
984 clip_rect.size.height = row->visible_height;
986 ns_focus (f, &clip_rect, 1);
991 ns_ring_bell (struct frame *f)
992 /* --------------------------------------------------------------------------
994 -------------------------------------------------------------------------- */
996 NSTRACE (ns_ring_bell);
999 NSAutoreleasePool *pool;
1000 struct frame *frame = SELECTED_FRAME ();
1004 pool = [[NSAutoreleasePool alloc] init];
1006 view = FRAME_NS_VIEW (frame);
1010 NSPoint dim = NSMakePoint (128, 128);
1013 r.origin.x += (r.size.width - dim.x) / 2;
1014 r.origin.y += (r.size.height - dim.y) / 2;
1015 r.size.width = dim.x;
1016 r.size.height = dim.y;
1017 surr = NSInsetRect (r, -2, -2);
1018 ns_focus (frame, &surr, 1);
1019 [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
1020 [ns_lookup_indexed_color (NS_FACE_FOREGROUND
1021 (FRAME_DEFAULT_FACE (frame)), frame) set];
1023 [[view window] flushWindow];
1024 ns_timeout (150000);
1025 [[view window] restoreCachedImage];
1026 [[view window] flushWindow];
1038 /* ==========================================================================
1040 Frame / window manager related functions
1042 ========================================================================== */
1046 ns_raise_frame (struct frame *f)
1047 /* --------------------------------------------------------------------------
1048 Bring window to foreground and make it active
1049 -------------------------------------------------------------------------- */
1052 check_window_system (f);
1053 view = FRAME_NS_VIEW (f);
1055 if (FRAME_VISIBLE_P (f))
1056 [[view window] makeKeyAndOrderFront: NSApp];
1062 ns_lower_frame (struct frame *f)
1063 /* --------------------------------------------------------------------------
1065 -------------------------------------------------------------------------- */
1068 check_window_system (f);
1069 view = FRAME_NS_VIEW (f);
1071 [[view window] orderBack: NSApp];
1077 ns_frame_raise_lower (struct frame *f, bool raise)
1078 /* --------------------------------------------------------------------------
1080 -------------------------------------------------------------------------- */
1082 NSTRACE (ns_frame_raise_lower);
1092 ns_frame_rehighlight (struct frame *frame)
1093 /* --------------------------------------------------------------------------
1094 External (hook): called on things like window switching within frame
1095 -------------------------------------------------------------------------- */
1097 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
1098 struct frame *old_highlight = dpyinfo->x_highlight_frame;
1100 NSTRACE (ns_frame_rehighlight);
1101 if (dpyinfo->x_focus_frame)
1103 dpyinfo->x_highlight_frame
1104 = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1105 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1106 : dpyinfo->x_focus_frame);
1107 if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
1109 fset_focus_frame (dpyinfo->x_focus_frame, Qnil);
1110 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
1114 dpyinfo->x_highlight_frame = 0;
1116 if (dpyinfo->x_highlight_frame &&
1117 dpyinfo->x_highlight_frame != old_highlight)
1121 x_update_cursor (old_highlight, 1);
1122 x_set_frame_alpha (old_highlight);
1124 if (dpyinfo->x_highlight_frame)
1126 x_update_cursor (dpyinfo->x_highlight_frame, 1);
1127 x_set_frame_alpha (dpyinfo->x_highlight_frame);
1134 x_make_frame_visible (struct frame *f)
1135 /* --------------------------------------------------------------------------
1136 External: Show the window (X11 semantics)
1137 -------------------------------------------------------------------------- */
1139 NSTRACE (x_make_frame_visible);
1140 /* XXX: at some points in past this was not needed, as the only place that
1141 called this (frame.c:Fraise_frame ()) also called raise_lower;
1142 if this ends up the case again, comment this out again. */
1143 if (!FRAME_VISIBLE_P (f))
1145 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1147 SET_FRAME_VISIBLE (f, 1);
1150 /* Making a new frame from a fullscreen frame will make the new frame
1151 fullscreen also. So skip handleFS as this will print an error. */
1152 if ([view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH
1153 && [view isFullscreen])
1156 if (f->want_fullscreen != FULLSCREEN_NONE)
1167 x_make_frame_invisible (struct frame *f)
1168 /* --------------------------------------------------------------------------
1169 External: Hide the window (X11 semantics)
1170 -------------------------------------------------------------------------- */
1173 NSTRACE (x_make_frame_invisible);
1174 check_window_system (f);
1175 view = FRAME_NS_VIEW (f);
1176 [[view window] orderOut: NSApp];
1177 SET_FRAME_VISIBLE (f, 0);
1178 SET_FRAME_ICONIFIED (f, 0);
1183 x_iconify_frame (struct frame *f)
1184 /* --------------------------------------------------------------------------
1185 External: Iconify window
1186 -------------------------------------------------------------------------- */
1189 struct ns_display_info *dpyinfo;
1191 NSTRACE (x_iconify_frame);
1192 check_window_system (f);
1193 view = FRAME_NS_VIEW (f);
1194 dpyinfo = FRAME_DISPLAY_INFO (f);
1196 if (dpyinfo->x_highlight_frame == f)
1197 dpyinfo->x_highlight_frame = 0;
1199 if ([[view window] windowNumber] <= 0)
1201 /* the window is still deferred. Make it very small, bring it
1202 on screen and order it out. */
1203 NSRect s = { { 100, 100}, {0, 0} };
1205 t = [[view window] frame];
1206 [[view window] setFrame: s display: NO];
1207 [[view window] orderBack: NSApp];
1208 [[view window] orderOut: NSApp];
1209 [[view window] setFrame: t display: NO];
1211 [[view window] miniaturize: NSApp];
1214 /* Free X resources of frame F. */
1217 x_free_frame_resources (struct frame *f)
1220 struct ns_display_info *dpyinfo;
1221 Mouse_HLInfo *hlinfo;
1223 NSTRACE (x_free_frame_resources);
1224 check_window_system (f);
1225 view = FRAME_NS_VIEW (f);
1226 dpyinfo = FRAME_DISPLAY_INFO (f);
1227 hlinfo = MOUSE_HL_INFO (f);
1229 [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1233 free_frame_menubar (f);
1234 free_frame_faces (f);
1236 if (f == dpyinfo->x_focus_frame)
1237 dpyinfo->x_focus_frame = 0;
1238 if (f == dpyinfo->x_highlight_frame)
1239 dpyinfo->x_highlight_frame = 0;
1240 if (f == hlinfo->mouse_face_mouse_frame)
1241 reset_mouse_highlight (hlinfo);
1243 if (f->output_data.ns->miniimage != nil)
1244 [f->output_data.ns->miniimage release];
1246 [[view window] close];
1249 xfree (f->output_data.ns);
1255 x_destroy_window (struct frame *f)
1256 /* --------------------------------------------------------------------------
1257 External: Delete the window
1258 -------------------------------------------------------------------------- */
1260 NSTRACE (x_destroy_window);
1261 check_window_system (f);
1262 x_free_frame_resources (f);
1268 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1269 /* --------------------------------------------------------------------------
1270 External: Position the window
1271 -------------------------------------------------------------------------- */
1273 NSView *view = FRAME_NS_VIEW (f);
1274 NSArray *screens = [NSScreen screens];
1275 NSScreen *fscreen = [screens objectAtIndex: 0];
1276 NSScreen *screen = [[view window] screen];
1278 NSTRACE (x_set_offset);
1285 if (view != nil && screen && fscreen)
1287 f->left_pos = f->size_hint_flags & XNegative
1288 ? [screen visibleFrame].size.width + f->left_pos - FRAME_PIXEL_WIDTH (f)
1290 /* We use visibleFrame here to take menu bar into account.
1291 Ideally we should also adjust left/top with visibleFrame.origin. */
1293 f->top_pos = f->size_hint_flags & YNegative
1294 ? ([screen visibleFrame].size.height + f->top_pos
1295 - FRAME_PIXEL_HEIGHT (f) - FRAME_NS_TITLEBAR_HEIGHT (f)
1296 - FRAME_TOOLBAR_HEIGHT (f))
1298 #ifdef NS_IMPL_GNUSTEP
1299 if (f->left_pos < 100)
1300 f->left_pos = 100; /* don't overlap menu */
1302 /* Constrain the setFrameTopLeftPoint so we don't move behind the
1304 [[view window] setFrameTopLeftPoint:
1305 NSMakePoint (SCREENMAXBOUND (f->left_pos),
1306 SCREENMAXBOUND ([fscreen frame].size.height
1307 - NS_TOP_POS (f)))];
1308 f->size_hint_flags &= ~(XNegative|YNegative);
1316 x_set_window_size (struct frame *f,
1317 bool change_gravity,
1321 /* --------------------------------------------------------------------------
1322 Adjust window pixel size based on given character grid size
1323 Impl is a bit more complex than other terms, need to do some
1325 -------------------------------------------------------------------------- */
1327 EmacsView *view = FRAME_NS_VIEW (f);
1328 NSWindow *window = [view window];
1329 NSRect wr = [window frame];
1330 int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1331 int pixelwidth, pixelheight;
1334 NSTRACE (x_set_window_size);
1339 /*fprintf (stderr, "\tsetWindowSize: %d x %d, pixelwise %d, font size %d x %d\n", width, height, pixelwise, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f));*/
1345 pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
1346 pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
1347 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, pixelwidth);
1348 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, pixelheight);
1352 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, width);
1353 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, height);
1358 /* If we have a toolbar, take its height into account. */
1359 if (tb && ! [view isFullscreen])
1361 /* NOTE: previously this would generate wrong result if toolbar not
1362 yet displayed and fixing toolbar_height=32 helped, but
1363 now (200903) seems no longer needed */
1364 FRAME_TOOLBAR_HEIGHT (f) =
1365 NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1366 - FRAME_NS_TITLEBAR_HEIGHT (f);
1367 #ifdef NS_IMPL_GNUSTEP
1368 FRAME_TOOLBAR_HEIGHT (f) -= 3;
1372 FRAME_TOOLBAR_HEIGHT (f) = 0;
1374 wr.size.width = pixelwidth + f->border_width;
1375 wr.size.height = pixelheight;
1376 if (! [view isFullscreen])
1377 wr.size.height += FRAME_NS_TITLEBAR_HEIGHT (f)
1378 + FRAME_TOOLBAR_HEIGHT (f);
1380 /* Do not try to constrain to this screen. We may have multiple
1381 screens, and want Emacs to span those. Constraining to screen
1382 prevents that, and that is not nice to the user. */
1383 if (f->output_data.ns->zooming)
1384 f->output_data.ns->zooming = 0;
1386 wr.origin.y += FRAME_PIXEL_HEIGHT (f) - pixelheight;
1388 [view setRows: rows andColumns: cols];
1389 [window setFrame: wr display: YES];
1391 /* This is a trick to compensate for Emacs' managing the scrollbar area
1392 as a fixed number of standard character columns. Instead of leaving
1393 blank space for the extra, we chopped it off above. Now for
1394 left-hand scrollbars, we shift all rendering to the left by the
1395 difference between the real width and Emacs' imagined one. For
1396 right-hand bars, don't worry about it since the extra is never used.
1397 (Obviously doesn't work for vertically split windows tho..) */
1399 NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1400 ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1401 - NS_SCROLL_BAR_WIDTH (f), 0)
1402 : NSMakePoint (0, 0);
1403 [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1404 [view setBoundsOrigin: origin];
1407 change_frame_size (f, width, height, 0, 1, 0, pixelwise);
1408 /* SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */
1410 mark_window_cursors_off (XWINDOW (f->root_window));
1411 cancel_mouse_face (f);
1415 do_pending_window_change (0);
1420 ns_fullscreen_hook (struct frame *f)
1422 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1424 if (!FRAME_VISIBLE_P (f))
1427 if (! [view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH)
1429 /* Old style fs don't initiate correctly if created from
1430 init/default-frame alist, so use a timer (not nice...).
1432 [NSTimer scheduledTimerWithTimeInterval: 0.5 target: view
1433 selector: @selector (handleFS)
1434 userInfo: nil repeats: NO];
1443 /* ==========================================================================
1447 ========================================================================== */
1451 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1453 struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1454 if (idx < 1 || idx >= color_table->avail)
1456 return color_table->colors[idx];
1461 ns_index_color (NSColor *color, struct frame *f)
1463 struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1467 if (!color_table->colors)
1469 color_table->size = NS_COLOR_CAPACITY;
1470 color_table->avail = 1; /* skip idx=0 as marker */
1471 color_table->colors = xmalloc (color_table->size * sizeof (NSColor *));
1472 color_table->colors[0] = nil;
1473 color_table->empty_indices = [[NSMutableSet alloc] init];
1476 /* Do we already have this color? */
1477 for (i = 1; i < color_table->avail; i++)
1478 if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1481 if ([color_table->empty_indices count] > 0)
1483 NSNumber *index = [color_table->empty_indices anyObject];
1484 [color_table->empty_indices removeObject: index];
1485 idx = [index unsignedLongValue];
1489 if (color_table->avail == color_table->size)
1490 color_table->colors =
1491 xpalloc (color_table->colors, &color_table->size, 1,
1492 min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1493 idx = color_table->avail++;
1496 color_table->colors[idx] = color;
1498 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1504 ns_free_indexed_color (unsigned long idx, struct frame *f)
1506 struct ns_color_table *color_table;
1513 color_table = FRAME_DISPLAY_INFO (f)->color_table;
1515 if (idx <= 0 || idx >= color_table->size) {
1516 message1 ("ns_free_indexed_color: Color index out of range.\n");
1520 index = [NSNumber numberWithUnsignedInt: idx];
1521 if ([color_table->empty_indices containsObject: index]) {
1522 message1 ("ns_free_indexed_color: attempt to free already freed color.\n");
1526 color = color_table->colors[idx];
1528 color_table->colors[idx] = nil;
1529 [color_table->empty_indices addObject: index];
1530 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1535 ns_get_color (const char *name, NSColor **col)
1536 /* --------------------------------------------------------------------------
1538 -------------------------------------------------------------------------- */
1539 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1540 X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1541 See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1544 static char hex[20];
1546 float r = -1.0, g, b;
1547 NSString *nsname = [NSString stringWithUTF8String: name];
1549 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1552 if ([nsname isEqualToString: @"ns_selection_bg_color"])
1554 #ifdef NS_IMPL_COCOA
1555 NSString *defname = [[NSUserDefaults standardUserDefaults]
1556 stringForKey: @"AppleHighlightColor"];
1561 if ((new = [NSColor selectedTextBackgroundColor]) != nil)
1563 *col = [new colorUsingDefaultColorSpace];
1568 nsname = NS_SELECTION_BG_COLOR_DEFAULT;
1570 name = [nsname UTF8String];
1572 else if ([nsname isEqualToString: @"ns_selection_fg_color"])
1574 /* NOTE: OSX applications normally don't set foreground selection, but
1575 text may be unreadable if we don't.
1577 if ((new = [NSColor selectedTextColor]) != nil)
1579 *col = [new colorUsingDefaultColorSpace];
1584 nsname = NS_SELECTION_FG_COLOR_DEFAULT;
1585 name = [nsname UTF8String];
1588 /* First, check for some sort of numeric specification. */
1591 if (name[0] == '0' || name[0] == '1' || name[0] == '.') /* RGB decimal */
1593 NSScanner *scanner = [NSScanner scannerWithString: nsname];
1594 [scanner scanFloat: &r];
1595 [scanner scanFloat: &g];
1596 [scanner scanFloat: &b];
1598 else if (!strncmp(name, "rgb:", 4)) /* A newer X11 format -- rgb:r/g/b */
1599 scaling = (snprintf (hex, sizeof hex, "%s", name + 4) - 2) / 3;
1600 else if (name[0] == '#') /* An old X11 format; convert to newer */
1602 int len = (strlen(name) - 1);
1603 int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1605 scaling = strlen(name+start) / 3;
1606 for (i = 0; i < 3; i++)
1607 sprintf (hex + i * (scaling + 1), "%.*s/", scaling,
1608 name + start + i * scaling);
1609 hex[3 * (scaling + 1) - 1] = '\0';
1615 float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1616 if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1626 *col = [NSColor colorForEmacsRed: r green: g blue: b alpha: 1.0];
1631 /* Otherwise, color is expected to be from a list */
1633 NSEnumerator *lenum, *cenum;
1637 #ifdef NS_IMPL_GNUSTEP
1638 /* XXX: who is wrong, the requestor or the implementation? */
1639 if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1641 nsname = @"highlightColor";
1644 lenum = [[NSColorList availableColorLists] objectEnumerator];
1645 while ( (clist = [lenum nextObject]) && new == nil)
1647 cenum = [[clist allKeys] objectEnumerator];
1648 while ( (name = [cenum nextObject]) && new == nil )
1650 if ([name compare: nsname
1651 options: NSCaseInsensitiveSearch] == NSOrderedSame )
1652 new = [clist colorWithKey: name];
1658 *col = [new colorUsingDefaultColorSpace];
1665 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1666 /* --------------------------------------------------------------------------
1667 Convert a Lisp string object to a NS color
1668 -------------------------------------------------------------------------- */
1670 NSTRACE (ns_lisp_to_color);
1671 if (STRINGP (color))
1672 return ns_get_color (SSDATA (color), col);
1673 else if (SYMBOLP (color))
1674 return ns_get_color (SSDATA (SYMBOL_NAME (color)), col);
1680 ns_color_to_lisp (NSColor *col)
1681 /* --------------------------------------------------------------------------
1682 Convert a color to a lisp string with the RGB equivalent
1683 -------------------------------------------------------------------------- */
1685 EmacsCGFloat red, green, blue, alpha, gray;
1688 NSTRACE (ns_color_to_lisp);
1691 if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1693 if ((str =[[col colorNameComponent] UTF8String]))
1696 return build_string ((char *)str);
1699 [[col colorUsingDefaultColorSpace]
1700 getRed: &red green: &green blue: &blue alpha: &alpha];
1701 if (red == green && red == blue)
1703 [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1704 getWhite: &gray alpha: &alpha];
1705 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1706 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1708 return build_string (buf);
1711 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1712 lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1715 return build_string (buf);
1720 ns_query_color(void *col, XColor *color_def, int setPixel)
1721 /* --------------------------------------------------------------------------
1722 Get ARGB values out of NSColor col and put them into color_def.
1723 If setPixel, set the pixel to a concatenated version.
1724 and set color_def pixel to the resulting index.
1725 -------------------------------------------------------------------------- */
1727 EmacsCGFloat r, g, b, a;
1729 [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1730 color_def->red = r * 65535;
1731 color_def->green = g * 65535;
1732 color_def->blue = b * 65535;
1734 if (setPixel == YES)
1736 = ARGB_TO_ULONG((int)(a*255),
1737 (int)(r*255), (int)(g*255), (int)(b*255));
1742 ns_defined_color (struct frame *f,
1747 /* --------------------------------------------------------------------------
1748 Return true if named color found, and set color_def rgb accordingly.
1749 If makeIndex and alloc are nonzero put the color in the color_table,
1750 and set color_def pixel to the resulting index.
1751 If makeIndex is zero, set color_def pixel to ARGB.
1752 Return false if not found
1753 -------------------------------------------------------------------------- */
1756 NSTRACE (ns_defined_color);
1759 if (ns_get_color (name, &col) != 0) /* Color not found */
1764 if (makeIndex && alloc)
1765 color_def->pixel = ns_index_color (col, f);
1766 ns_query_color (col, color_def, !makeIndex);
1773 x_set_frame_alpha (struct frame *f)
1774 /* --------------------------------------------------------------------------
1775 change the entire-frame transparency
1776 -------------------------------------------------------------------------- */
1778 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1780 double alpha_min = 1.0;
1782 if (dpyinfo->x_highlight_frame == f)
1783 alpha = f->alpha[0];
1785 alpha = f->alpha[1];
1787 if (FLOATP (Vframe_alpha_lower_limit))
1788 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1789 else if (INTEGERP (Vframe_alpha_lower_limit))
1790 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1794 else if (1.0 < alpha)
1796 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1799 #ifdef NS_IMPL_COCOA
1801 EmacsView *view = FRAME_NS_VIEW (f);
1802 [[view window] setAlphaValue: alpha];
1808 /* ==========================================================================
1812 ========================================================================== */
1816 frame_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1817 /* --------------------------------------------------------------------------
1818 Programmatically reposition mouse pointer in pixel coordinates
1819 -------------------------------------------------------------------------- */
1821 NSTRACE (frame_set_mouse_pixel_position);
1824 /* FIXME: this does not work, and what about GNUstep? */
1825 #ifdef NS_IMPL_COCOA
1826 [FRAME_NS_VIEW (f) lockFocus];
1827 PSsetmouse ((float)pix_x, (float)pix_y);
1828 [FRAME_NS_VIEW (f) unlockFocus];
1834 note_mouse_movement (struct frame *frame, CGFloat x, CGFloat y)
1835 /* ------------------------------------------------------------------------
1836 Called by EmacsView on mouseMovement events. Passes on
1837 to emacs mainstream code if we moved off of a rect of interest
1838 known as last_mouse_glyph.
1839 ------------------------------------------------------------------------ */
1841 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
1844 // NSTRACE (note_mouse_movement);
1846 dpyinfo->last_mouse_motion_frame = frame;
1847 r = &dpyinfo->last_mouse_glyph;
1849 /* Note, this doesn't get called for enter/leave, since we don't have a
1850 position. Those are taken care of in the corresponding NSView methods. */
1852 /* has movement gone beyond last rect we were tracking? */
1853 if (x < r->origin.x || x >= r->origin.x + r->size.width
1854 || y < r->origin.y || y >= r->origin.y + r->size.height)
1856 ns_update_begin (frame);
1857 frame->mouse_moved = 1;
1858 note_mouse_highlight (frame, x, y);
1859 remember_mouse_glyph (frame, x, y, r);
1860 ns_update_end (frame);
1869 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1870 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1872 /* --------------------------------------------------------------------------
1873 External (hook): inform emacs about mouse position and hit parts.
1874 If a scrollbar is being dragged, set bar_window, part, x, y, time.
1875 x & y should be position in the scrollbar (the whole bar, not the handle)
1876 and length of scrollbar respectively
1877 -------------------------------------------------------------------------- */
1881 Lisp_Object frame, tail;
1883 struct ns_display_info *dpyinfo;
1885 NSTRACE (ns_mouse_position);
1889 fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1893 dpyinfo = FRAME_DISPLAY_INFO (*fp);
1897 /* Clear the mouse-moved flag for every frame on this display. */
1898 FOR_EACH_FRAME (tail, frame)
1899 if (FRAME_NS_P (XFRAME (frame))
1900 && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1901 XFRAME (frame)->mouse_moved = 0;
1903 dpyinfo->last_mouse_scroll_bar = nil;
1904 if (dpyinfo->last_mouse_frame
1905 && FRAME_LIVE_P (dpyinfo->last_mouse_frame))
1906 f = dpyinfo->last_mouse_frame;
1908 f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame : SELECTED_FRAME ();
1910 if (f && FRAME_NS_P (f))
1912 view = FRAME_NS_VIEW (*fp);
1914 position = [[view window] mouseLocationOutsideOfEventStream];
1915 position = [view convertPoint: position fromView: nil];
1916 remember_mouse_glyph (f, position.x, position.y,
1917 &dpyinfo->last_mouse_glyph);
1918 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1920 if (bar_window) *bar_window = Qnil;
1921 if (part) *part = scroll_bar_above_handle;
1923 if (x) XSETINT (*x, lrint (position.x));
1924 if (y) XSETINT (*y, lrint (position.y));
1926 *time = dpyinfo->last_mouse_movement_time;
1935 ns_frame_up_to_date (struct frame *f)
1936 /* --------------------------------------------------------------------------
1937 External (hook): Fix up mouse highlighting right after a full update.
1938 Can't use FRAME_MOUSE_UPDATE due to ns_frame_begin and ns_frame_end calls.
1939 -------------------------------------------------------------------------- */
1941 NSTRACE (ns_frame_up_to_date);
1945 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1946 if (f == hlinfo->mouse_face_mouse_frame)
1950 note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
1951 hlinfo->mouse_face_mouse_x,
1952 hlinfo->mouse_face_mouse_y);
1961 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1962 /* --------------------------------------------------------------------------
1963 External (RIF): set frame mouse pointer type.
1964 -------------------------------------------------------------------------- */
1966 NSTRACE (ns_define_frame_cursor);
1967 if (FRAME_POINTER_TYPE (f) != cursor)
1969 EmacsView *view = FRAME_NS_VIEW (f);
1970 FRAME_POINTER_TYPE (f) = cursor;
1971 [[view window] invalidateCursorRectsForView: view];
1972 /* Redisplay assumes this function also draws the changed frame
1973 cursor, but this function doesn't, so do it explicitly. */
1974 x_update_cursor (f, 1);
1980 /* ==========================================================================
1984 ========================================================================== */
1988 ns_convert_key (unsigned code)
1989 /* --------------------------------------------------------------------------
1990 Internal call used by NSView-keyDown.
1991 -------------------------------------------------------------------------- */
1993 const unsigned last_keysym = ARRAYELTS (convert_ns_to_X_keysym);
1995 /* An array would be faster, but less easy to read. */
1996 for (keysym = 0; keysym < last_keysym; keysym += 2)
1997 if (code == convert_ns_to_X_keysym[keysym])
1998 return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
2000 /* if decide to use keyCode and Carbon table, use this line:
2001 return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
2006 x_get_keysym_name (int keysym)
2007 /* --------------------------------------------------------------------------
2008 Called by keyboard.c. Not sure if the return val is important, except
2010 -------------------------------------------------------------------------- */
2012 static char value[16];
2013 NSTRACE (x_get_keysym_name);
2014 sprintf (value, "%d", keysym);
2020 /* ==========================================================================
2022 Block drawing operations
2024 ========================================================================== */
2028 ns_redraw_scroll_bars (struct frame *f)
2032 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
2033 NSTRACE (ns_redraw_scroll_bars);
2034 for (i =[subviews count]-1; i >= 0; i--)
2036 view = [subviews objectAtIndex: i];
2037 if (![view isKindOfClass: [EmacsScroller class]]) continue;
2044 ns_clear_frame (struct frame *f)
2045 /* --------------------------------------------------------------------------
2046 External (hook): Erase the entire frame
2047 -------------------------------------------------------------------------- */
2049 NSView *view = FRAME_NS_VIEW (f);
2052 NSTRACE (ns_clear_frame);
2054 /* comes on initial frame because we have
2055 after-make-frame-functions = select-frame */
2056 if (!FRAME_DEFAULT_FACE (f))
2059 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2064 ns_focus (f, &r, 1);
2065 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
2069 /* as of 2006/11 or so this is now needed */
2070 ns_redraw_scroll_bars (f);
2076 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2077 /* --------------------------------------------------------------------------
2078 External (RIF): Clear section of frame
2079 -------------------------------------------------------------------------- */
2081 NSRect r = NSMakeRect (x, y, width, height);
2082 NSView *view = FRAME_NS_VIEW (f);
2083 struct face *face = FRAME_DEFAULT_FACE (f);
2088 NSTRACE (ns_clear_frame_area);
2090 r = NSIntersectionRect (r, [view frame]);
2091 ns_focus (f, &r, 1);
2092 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2102 ns_scroll_run (struct window *w, struct run *run)
2103 /* --------------------------------------------------------------------------
2104 External (RIF): Insert or delete n lines at line vpos
2105 -------------------------------------------------------------------------- */
2107 struct frame *f = XFRAME (w->frame);
2108 int x, y, width, height, from_y, to_y, bottom_y;
2110 NSTRACE (ns_scroll_run);
2112 /* begin copy from other terms */
2113 /* Get frame-relative bounding box of the text display area of W,
2114 without mode lines. Include in this box the left and right
2116 window_box (w, ANY_AREA, &x, &y, &width, &height);
2118 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2119 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2120 bottom_y = y + height;
2124 /* Scrolling up. Make sure we don't copy part of the mode
2125 line at the bottom. */
2126 if (from_y + run->height > bottom_y)
2127 height = bottom_y - from_y;
2129 height = run->height;
2133 /* Scrolling down. Make sure we don't copy over the mode line.
2135 if (to_y + run->height > bottom_y)
2136 height = bottom_y - to_y;
2138 height = run->height;
2140 /* end copy from other terms */
2150 NSRect srcRect = NSMakeRect (x, from_y, width, height);
2151 NSRect dstRect = NSMakeRect (x, to_y, width, height);
2152 NSPoint dstOrigin = NSMakePoint (x, to_y);
2154 ns_focus (f, &dstRect, 1);
2155 NSCopyBits (0, srcRect , dstOrigin);
2164 ns_after_update_window_line (struct window *w, struct glyph_row *desired_row)
2165 /* --------------------------------------------------------------------------
2166 External (RIF): preparatory to fringe update after text was updated
2167 -------------------------------------------------------------------------- */
2172 NSTRACE (ns_after_update_window_line);
2174 /* begin copy from other terms */
2177 if (!desired_row->mode_line_p && !w->pseudo_window_p)
2178 desired_row->redraw_fringe_bitmaps_p = 1;
2180 /* When a window has disappeared, make sure that no rest of
2181 full-width rows stays visible in the internal border. */
2182 if (windows_or_buffers_changed
2183 && desired_row->full_width_p
2184 && (f = XFRAME (w->frame),
2185 width = FRAME_INTERNAL_BORDER_WIDTH (f),
2187 && (height = desired_row->visible_height,
2190 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2193 ns_clear_frame_area (f, 0, y, width, height);
2194 ns_clear_frame_area (f,
2195 FRAME_PIXEL_WIDTH (f) - width,
2203 ns_shift_glyphs_for_insert (struct frame *f,
2204 int x, int y, int width, int height,
2206 /* --------------------------------------------------------------------------
2207 External (RIF): copy an area horizontally, don't worry about clearing src
2208 -------------------------------------------------------------------------- */
2210 NSRect srcRect = NSMakeRect (x, y, width, height);
2211 NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2212 NSPoint dstOrigin = dstRect.origin;
2214 NSTRACE (ns_shift_glyphs_for_insert);
2216 ns_focus (f, &dstRect, 1);
2217 NSCopyBits (0, srcRect, dstOrigin);
2223 /* ==========================================================================
2225 Character encoding and metrics
2227 ========================================================================== */
2231 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2232 /* --------------------------------------------------------------------------
2233 External (RIF); compute left/right overhang of whole string and set in s
2234 -------------------------------------------------------------------------- */
2236 struct font *font = s->font;
2240 struct font_metrics metrics;
2241 unsigned int codes[2];
2242 codes[0] = *(s->char2b);
2243 codes[1] = *(s->char2b + s->nchars - 1);
2245 font->driver->text_extents (font, codes, 2, &metrics);
2246 s->left_overhang = -metrics.lbearing;
2248 = metrics.rbearing > metrics.width
2249 ? metrics.rbearing - metrics.width : 0;
2253 s->left_overhang = 0;
2254 if (EQ (font->driver->type, Qns))
2255 s->right_overhang = ((struct nsfont_info *)font)->ital ?
2256 FONT_HEIGHT (font) * 0.2 : 0;
2258 s->right_overhang = 0;
2264 /* ==========================================================================
2266 Fringe and cursor drawing
2268 ========================================================================== */
2271 extern int max_used_fringe_bitmap;
2273 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2274 struct draw_fringe_bitmap_params *p)
2275 /* --------------------------------------------------------------------------
2276 External (RIF); fringe-related
2277 -------------------------------------------------------------------------- */
2279 struct frame *f = XFRAME (WINDOW_FRAME (w));
2280 struct face *face = p->face;
2281 static EmacsImage **bimgs = NULL;
2282 static int nBimgs = 0;
2284 /* grow bimgs if needed */
2285 if (nBimgs < max_used_fringe_bitmap)
2287 bimgs = xrealloc (bimgs, max_used_fringe_bitmap * sizeof *bimgs);
2288 memset (bimgs + nBimgs, 0,
2289 (max_used_fringe_bitmap - nBimgs) * sizeof *bimgs);
2290 nBimgs = max_used_fringe_bitmap;
2293 /* Must clip because of partially visible lines. */
2294 ns_clip_to_row (w, row, ANY_AREA, YES);
2298 int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
2300 if (bx >= 0 && nx > 0)
2302 NSRect r = NSMakeRect (bx, by, nx, ny);
2304 [ns_lookup_indexed_color (face->background, f) set];
2311 NSRect r = NSMakeRect (p->x, p->y, p->wd, p->h);
2312 EmacsImage *img = bimgs[p->which - 1];
2316 unsigned short *bits = p->bits + p->dh;
2319 unsigned char *cbits = xmalloc (len);
2321 for (i = 0; i < len; i++)
2322 cbits[i] = ~(bits[i] & 0xff);
2323 img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2325 bimgs[p->which - 1] = img;
2330 /* Since we composite the bitmap instead of just blitting it, we need
2331 to erase the whole background. */
2332 [ns_lookup_indexed_color(face->background, f) set];
2338 bm_color = ns_lookup_indexed_color(face->foreground, f);
2339 else if (p->overlay_p)
2340 bm_color = ns_lookup_indexed_color(face->background, f);
2342 bm_color = f->output_data.ns->cursor_color;
2343 [img setXBMColor: bm_color];
2346 #ifdef NS_IMPL_COCOA
2348 fromRect: NSZeroRect
2349 operation: NSCompositeSourceOver
2355 NSPoint pt = r.origin;
2357 [img compositeToPoint: pt operation: NSCompositeSourceOver];
2366 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2367 int x, int y, enum text_cursor_kinds cursor_type,
2368 int cursor_width, bool on_p, bool active_p)
2369 /* --------------------------------------------------------------------------
2370 External call (RIF): draw cursor.
2371 Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2372 -------------------------------------------------------------------------- */
2375 int fx, fy, h, cursor_height;
2376 struct frame *f = WINDOW_XFRAME (w);
2377 struct glyph *phys_cursor_glyph;
2378 struct glyph *cursor_glyph;
2380 NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2382 /* If cursor is out of bounds, don't draw garbage. This can happen
2383 in mini-buffer windows when switching between echo area glyphs
2386 NSTRACE (dumpcursor);
2391 w->phys_cursor_type = cursor_type;
2392 w->phys_cursor_on_p = on_p;
2394 if (cursor_type == NO_CURSOR)
2396 w->phys_cursor_width = 0;
2400 if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2402 if (glyph_row->exact_window_width_line_p
2403 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2405 glyph_row->cursor_in_fringe_p = 1;
2406 draw_fringe_bitmap (w, glyph_row, 0);
2411 /* We draw the cursor (with NSRectFill), then draw the glyph on top
2412 (other terminals do it the other way round). We must set
2413 w->phys_cursor_width to the cursor width. For bar cursors, that
2414 is CURSOR_WIDTH; for box cursors, it is the glyph width. */
2415 get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2417 /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2418 to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2419 if (cursor_type == BAR_CURSOR)
2421 if (cursor_width < 1)
2422 cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2423 w->phys_cursor_width = cursor_width;
2425 /* If we have an HBAR, "cursor_width" MAY specify height. */
2426 else if (cursor_type == HBAR_CURSOR)
2428 cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2429 if (cursor_height > glyph_row->height)
2430 cursor_height = glyph_row->height;
2431 if (h > cursor_height) // Cursor smaller than line height, move down
2432 fy += h - cursor_height;
2436 r.origin.x = fx, r.origin.y = fy;
2438 r.size.width = w->phys_cursor_width;
2440 /* TODO: only needed in rare cases with last-resort font in HELLO..
2441 should we do this more efficiently? */
2442 ns_clip_to_row (w, glyph_row, ANY_AREA, NO); /* do ns_focus(f, &r, 1); if remove */
2445 face = FACE_FROM_ID (f, phys_cursor_glyph->face_id);
2446 if (face && NS_FACE_BACKGROUND (face)
2447 == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2449 [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2450 hollow_color = FRAME_CURSOR_COLOR (f);
2453 [FRAME_CURSOR_COLOR (f) set];
2455 #ifdef NS_IMPL_COCOA
2456 /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2457 atomic. Cleaner ways of doing this should be investigated.
2458 One way would be to set a global variable DRAWING_CURSOR
2459 when making the call to draw_phys..(), don't focus in that
2460 case, then move the ns_unfocus() here after that call. */
2461 NSDisableScreenUpdates ();
2464 switch (cursor_type)
2468 case FILLED_BOX_CURSOR:
2471 case HOLLOW_BOX_CURSOR:
2474 NSRectFill (NSInsetRect (r, 1, 1));
2475 [FRAME_CURSOR_COLOR (f) set];
2482 /* If the character under cursor is R2L, draw the bar cursor
2483 on the right of its glyph, rather than on the left. */
2484 cursor_glyph = get_phys_cursor_glyph (w);
2485 if ((cursor_glyph->resolved_level & 1) != 0)
2486 s.origin.x += cursor_glyph->pixel_width - s.size.width;
2493 /* draw the character under the cursor */
2494 if (cursor_type != NO_CURSOR)
2495 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2497 #ifdef NS_IMPL_COCOA
2498 NSEnableScreenUpdates ();
2505 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2506 /* --------------------------------------------------------------------------
2507 External (RIF): Draw a vertical line.
2508 -------------------------------------------------------------------------- */
2510 struct frame *f = XFRAME (WINDOW_FRAME (w));
2512 NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2514 NSTRACE (ns_draw_vertical_window_border);
2516 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2518 [ns_lookup_indexed_color(face->foreground, f) set];
2520 ns_focus (f, &r, 1);
2527 ns_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
2528 /* --------------------------------------------------------------------------
2529 External (RIF): Draw a window divider.
2530 -------------------------------------------------------------------------- */
2532 struct frame *f = XFRAME (WINDOW_FRAME (w));
2534 NSRect r = NSMakeRect (x0, y0, x1-x0, y1-y0);
2536 NSTRACE (ns_draw_window_divider);
2538 face = FACE_FROM_ID (f, WINDOW_DIVIDER_FACE_ID);
2540 [ns_lookup_indexed_color(face->foreground, f) set];
2542 ns_focus (f, &r, 1);
2548 ns_show_hourglass (struct frame *f)
2550 /* TODO: add NSProgressIndicator to all frames. */
2554 ns_hide_hourglass (struct frame *f)
2556 /* TODO: remove NSProgressIndicator from all frames. */
2559 /* ==========================================================================
2561 Glyph drawing operations
2563 ========================================================================== */
2566 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2567 /* --------------------------------------------------------------------------
2568 Wrapper utility to account for internal border width on full-width lines,
2569 and allow top full-width rows to hit the frame top. nr should be pointer
2570 to two successive NSRects. Number of rects actually used is returned.
2571 -------------------------------------------------------------------------- */
2573 int n = get_glyph_string_clip_rects (s, nr, 2);
2577 /* --------------------------------------------------------------------
2578 Draw a wavy line under glyph string s. The wave fills wave_height
2585 wave_height = 3 | * * * *
2586 --------------------------------------------------------------------- */
2589 ns_draw_underwave (struct glyph_string *s, EmacsCGFloat width, EmacsCGFloat x)
2591 int wave_height = 3, wave_length = 2;
2592 int y, dx, dy, odd, xmax;
2597 dy = wave_height - 1;
2598 y = s->ybase - wave_height + 3;
2601 /* Find and set clipping rectangle */
2602 waveClip = NSMakeRect (x, y, width, wave_height);
2603 [[NSGraphicsContext currentContext] saveGraphicsState];
2604 NSRectClip (waveClip);
2606 /* Draw the waves */
2607 a.x = x - ((int)(x) % dx) + (EmacsCGFloat) 0.5;
2609 odd = (int)(a.x/dx) % 2;
2610 a.y = b.y = y + 0.5;
2619 [NSBezierPath strokeLineFromPoint:a toPoint:b];
2620 a.x = b.x, a.y = b.y;
2621 b.x += dx, b.y = y + 0.5 + odd*dy;
2625 /* Restore previous clipping rectangle(s) */
2626 [[NSGraphicsContext currentContext] restoreGraphicsState];
2632 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
2633 NSColor *defaultCol, CGFloat width, CGFloat x)
2634 /* --------------------------------------------------------------------------
2635 Draw underline, overline, and strike-through on glyph string s.
2636 -------------------------------------------------------------------------- */
2638 if (s->for_overlaps)
2642 if (face->underline_p)
2644 if (s->face->underline_type == FACE_UNDER_WAVE)
2646 if (face->underline_defaulted_p)
2649 [ns_lookup_indexed_color (face->underline_color, s->f) set];
2651 ns_draw_underwave (s, width, x);
2653 else if (s->face->underline_type == FACE_UNDER_LINE)
2657 unsigned long thickness, position;
2659 /* If the prev was underlined, match its appearance. */
2660 if (s->prev && s->prev->face->underline_p
2661 && s->prev->face->underline_type == FACE_UNDER_LINE
2662 && s->prev->underline_thickness > 0)
2664 thickness = s->prev->underline_thickness;
2665 position = s->prev->underline_position;
2670 unsigned long descent;
2673 descent = s->y + s->height - s->ybase;
2675 /* Use underline thickness of font, defaulting to 1. */
2676 thickness = (font && font->underline_thickness > 0)
2677 ? font->underline_thickness : 1;
2679 /* Determine the offset of underlining from the baseline. */
2680 if (x_underline_at_descent_line)
2681 position = descent - thickness;
2682 else if (x_use_underline_position_properties
2683 && font && font->underline_position >= 0)
2684 position = font->underline_position;
2686 position = lround (font->descent / 2);
2688 position = underline_minimum_offset;
2690 position = max (position, underline_minimum_offset);
2692 /* Ensure underlining is not cropped. */
2693 if (descent <= position)
2695 position = descent - 1;
2698 else if (descent < position + thickness)
2702 s->underline_thickness = thickness;
2703 s->underline_position = position;
2705 r = NSMakeRect (x, s->ybase + position, width, thickness);
2707 if (face->underline_defaulted_p)
2710 [ns_lookup_indexed_color (face->underline_color, s->f) set];
2714 /* Do overline. We follow other terms in using a thickness of 1
2715 and ignoring overline_margin. */
2716 if (face->overline_p)
2719 r = NSMakeRect (x, s->y, width, 1);
2721 if (face->overline_color_defaulted_p)
2724 [ns_lookup_indexed_color (face->overline_color, s->f) set];
2728 /* Do strike-through. We follow other terms for thickness and
2729 vertical position.*/
2730 if (face->strike_through_p)
2735 dy = lrint ((s->height - 1) / 2);
2736 r = NSMakeRect (x, s->y + dy, width, 1);
2738 if (face->strike_through_color_defaulted_p)
2741 [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
2747 ns_draw_box (NSRect r, CGFloat thickness, NSColor *col,
2748 char left_p, char right_p)
2749 /* --------------------------------------------------------------------------
2750 Draw an unfilled rect inside r, optionally leaving left and/or right open.
2751 Note we can't just use an NSDrawRect command, because of the possibility
2752 of some sides not being drawn, and because the rect will be filled.
2753 -------------------------------------------------------------------------- */
2759 s.size.height = thickness;
2761 s.origin.y += r.size.height - thickness;
2764 s.size.height = r.size.height;
2765 s.origin.y = r.origin.y;
2767 /* left, right (optional) */
2768 s.size.width = thickness;
2773 s.origin.x += r.size.width - thickness;
2780 ns_draw_relief (NSRect r, int thickness, char raised_p,
2781 char top_p, char bottom_p, char left_p, char right_p,
2782 struct glyph_string *s)
2783 /* --------------------------------------------------------------------------
2784 Draw a relief rect inside r, optionally leaving some sides open.
2785 Note we can't just use an NSDrawBezel command, because of the possibility
2786 of some sides not being drawn, and because the rect will be filled.
2787 -------------------------------------------------------------------------- */
2789 static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2790 NSColor *newBaseCol = nil;
2793 NSTRACE (ns_draw_relief);
2797 if (s->face->use_box_color_for_shadows_p)
2799 newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2801 /* else if (s->first_glyph->type == IMAGE_GLYPH
2803 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2805 newBaseCol = IMAGE_BACKGROUND (s->img, s->f, 0);
2809 newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2812 if (newBaseCol == nil)
2813 newBaseCol = [NSColor grayColor];
2815 if (newBaseCol != baseCol) /* TODO: better check */
2818 baseCol = [newBaseCol retain];
2820 lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2822 darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2825 [(raised_p ? lightCol : darkCol) set];
2827 /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2830 sr.size.height = thickness;
2831 if (top_p) NSRectFill (sr);
2834 sr.size.height = r.size.height;
2835 sr.size.width = thickness;
2836 if (left_p) NSRectFill (sr);
2838 [(raised_p ? darkCol : lightCol) set];
2841 sr.size.width = r.size.width;
2842 sr.size.height = thickness;
2843 sr.origin.y += r.size.height - thickness;
2844 if (bottom_p) NSRectFill (sr);
2847 sr.size.height = r.size.height;
2848 sr.origin.y = r.origin.y;
2849 sr.size.width = thickness;
2850 sr.origin.x += r.size.width - thickness;
2851 if (right_p) NSRectFill (sr);
2856 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2857 /* --------------------------------------------------------------------------
2858 Function modeled after x_draw_glyph_string_box ().
2859 Sets up parameters for drawing.
2860 -------------------------------------------------------------------------- */
2862 int right_x, last_x;
2863 char left_p, right_p;
2864 struct glyph *last_glyph;
2869 if (s->hl == DRAW_MOUSE_FACE)
2871 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2873 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2878 thickness = face->box_line_width;
2880 NSTRACE (ns_dumpglyphs_box_or_relief);
2882 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2883 ? WINDOW_RIGHT_EDGE_X (s->w)
2884 : window_box_right (s->w, s->area));
2885 last_glyph = (s->cmp || s->img
2886 ? s->first_glyph : s->first_glyph + s->nchars-1);
2888 right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2889 ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2891 left_p = (s->first_glyph->left_box_line_p
2892 || (s->hl == DRAW_MOUSE_FACE
2893 && (s->prev == NULL || s->prev->hl != s->hl)));
2894 right_p = (last_glyph->right_box_line_p
2895 || (s->hl == DRAW_MOUSE_FACE
2896 && (s->next == NULL || s->next->hl != s->hl)));
2898 r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2900 /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
2901 if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
2903 ns_draw_box (r, abs (thickness),
2904 ns_lookup_indexed_color (face->box_color, s->f),
2909 ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2910 1, 1, left_p, right_p, s);
2916 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2917 /* --------------------------------------------------------------------------
2918 Modeled after x_draw_glyph_string_background, which draws BG in
2919 certain cases. Others are left to the text rendering routine.
2920 -------------------------------------------------------------------------- */
2922 NSTRACE (ns_maybe_dumpglyphs_background);
2924 if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2926 int box_line_width = max (s->face->box_line_width, 0);
2927 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2928 || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2931 if (s->hl == DRAW_MOUSE_FACE)
2933 face = FACE_FROM_ID (s->f,
2934 MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2936 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2939 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2941 [(NS_FACE_BACKGROUND (face) != 0
2942 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2943 : FRAME_BACKGROUND_COLOR (s->f)) set];
2946 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (s->f);
2947 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2950 if (s->hl != DRAW_CURSOR)
2952 NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2953 s->background_width,
2954 s->height-2*box_line_width);
2958 s->background_filled_p = 1;
2965 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2966 /* --------------------------------------------------------------------------
2967 Renders an image and associated borders.
2968 -------------------------------------------------------------------------- */
2970 EmacsImage *img = s->img->pixmap;
2971 int box_line_vwidth = max (s->face->box_line_width, 0);
2972 int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2973 int bg_x, bg_y, bg_height;
2980 NSTRACE (ns_dumpglyphs_image);
2982 if (s->face->box != FACE_NO_BOX
2983 && s->first_glyph->left_box_line_p && s->slice.x == 0)
2984 x += abs (s->face->box_line_width);
2987 bg_y = s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2988 bg_height = s->height;
2989 /* other terms have this, but was causing problems w/tabbar mode */
2990 /* - 2 * box_line_vwidth; */
2992 if (s->slice.x == 0) x += s->img->hmargin;
2993 if (s->slice.y == 0) y += s->img->vmargin;
2995 /* Draw BG: if we need larger area than image itself cleared, do that,
2996 otherwise, since we composite the image under NS (instead of mucking
2997 with its background color), we must clear just the image area. */
2998 if (s->hl == DRAW_MOUSE_FACE)
3000 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3002 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3005 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3007 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
3009 if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
3010 || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
3012 br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
3013 s->background_filled_p = 1;
3017 br = NSMakeRect (x, y, s->slice.width, s->slice.height);
3022 /* Draw the image.. do we need to draw placeholder if img ==nil? */
3025 #ifdef NS_IMPL_COCOA
3026 NSRect dr = NSMakeRect (x, y, s->slice.width, s->slice.height);
3027 NSRect ir = NSMakeRect (s->slice.x, s->slice.y,
3028 s->slice.width, s->slice.height);
3031 operation: NSCompositeSourceOver
3036 [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3037 operation: NSCompositeSourceOver];
3041 if (s->hl == DRAW_CURSOR)
3043 [FRAME_CURSOR_COLOR (s->f) set];
3044 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3045 tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3047 /* Currently on NS img->mask is always 0. Since
3048 get_window_cursor_type specifies a hollow box cursor when on
3049 a non-masked image we never reach this clause. But we put it
3050 in in anticipation of better support for image masks on
3052 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3056 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3059 /* Draw underline, overline, strike-through. */
3060 ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3062 /* Draw relief, if requested */
3063 if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3065 if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3067 th = tool_bar_button_relief >= 0 ?
3068 tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3069 raised_p = (s->hl == DRAW_IMAGE_RAISED);
3073 th = abs (s->img->relief);
3074 raised_p = (s->img->relief > 0);
3077 r.origin.x = x - th;
3078 r.origin.y = y - th;
3079 r.size.width = s->slice.width + 2*th-1;
3080 r.size.height = s->slice.height + 2*th-1;
3081 ns_draw_relief (r, th, raised_p,
3083 s->slice.y + s->slice.height == s->img->height,
3085 s->slice.x + s->slice.width == s->img->width, s);
3088 /* If there is no mask, the background won't be seen,
3089 so draw a rectangle on the image for the cursor.
3090 Do this for all images, getting transparency right is not reliable. */
3091 if (s->hl == DRAW_CURSOR)
3093 int thickness = abs (s->img->relief);
3094 if (thickness == 0) thickness = 1;
3095 ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3101 ns_dumpglyphs_stretch (struct glyph_string *s)
3106 NSColor *fgCol, *bgCol;
3108 if (!s->background_filled_p)
3110 n = ns_get_glyph_string_clip_rect (s, r);
3111 *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3113 ns_focus (s->f, r, n);
3115 if (s->hl == DRAW_MOUSE_FACE)
3117 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3119 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3122 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3124 bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3125 fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3127 for (i = 0; i < n; ++i)
3129 if (!s->row->full_width_p)
3131 int overrun, leftoverrun;
3133 /* truncate to avoid overwriting fringe and/or scrollbar */
3134 overrun = max (0, (s->x + s->background_width)
3135 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3136 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3137 r[i].size.width -= overrun;
3139 /* truncate to avoid overwriting to left of the window box */
3140 leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3141 + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3143 if (leftoverrun > 0)
3145 r[i].origin.x += leftoverrun;
3146 r[i].size.width -= leftoverrun;
3149 /* XXX: Try to work between problem where a stretch glyph on
3150 a partially-visible bottom row will clear part of the
3151 modeline, and another where list-buffers headers and similar
3152 rows erroneously have visible_height set to 0. Not sure
3153 where this is coming from as other terms seem not to show. */
3154 r[i].size.height = min (s->height, s->row->visible_height);
3159 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3160 overwriting cursor (usually when cursor on a tab) */
3161 if (s->hl == DRAW_CURSOR)
3166 width = s->w->phys_cursor_width;
3167 r[i].size.width -= width;
3168 r[i].origin.x += width;
3172 /* Draw overlining, etc. on the cursor. */
3173 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3174 ns_draw_text_decoration (s, face, bgCol, width, x);
3176 ns_draw_text_decoration (s, face, fgCol, width, x);
3183 /* Draw overlining, etc. on the stretch glyph (or the part
3184 of the stretch glyph after the cursor). */
3185 ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3189 s->background_filled_p = 1;
3195 ns_draw_glyph_string (struct glyph_string *s)
3196 /* --------------------------------------------------------------------------
3197 External (RIF): Main draw-text call.
3198 -------------------------------------------------------------------------- */
3200 /* TODO (optimize): focus for box and contents draw */
3203 char box_drawn_p = 0;
3204 struct font *font = s->face->font;
3205 if (! font) font = FRAME_FONT (s->f);
3207 NSTRACE (ns_draw_glyph_string);
3209 if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3212 struct glyph_string *next;
3214 for (width = 0, next = s->next;
3215 next && width < s->right_overhang;
3216 width += next->width, next = next->next)
3217 if (next->first_glyph->type != IMAGE_GLYPH)
3219 if (next->first_glyph->type != STRETCH_GLYPH)
3221 n = ns_get_glyph_string_clip_rect (s->next, r);
3222 ns_focus (s->f, r, n);
3223 ns_maybe_dumpglyphs_background (s->next, 1);
3228 ns_dumpglyphs_stretch (s->next);
3230 next->num_clips = 0;
3234 if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3235 && (s->first_glyph->type == CHAR_GLYPH
3236 || s->first_glyph->type == COMPOSITE_GLYPH))
3238 n = ns_get_glyph_string_clip_rect (s, r);
3239 ns_focus (s->f, r, n);
3240 ns_maybe_dumpglyphs_background (s, 1);
3241 ns_dumpglyphs_box_or_relief (s);
3246 switch (s->first_glyph->type)
3250 n = ns_get_glyph_string_clip_rect (s, r);
3251 ns_focus (s->f, r, n);
3252 ns_dumpglyphs_image (s, r[0]);
3257 ns_dumpglyphs_stretch (s);
3261 case COMPOSITE_GLYPH:
3262 n = ns_get_glyph_string_clip_rect (s, r);
3263 ns_focus (s->f, r, n);
3265 if (s->for_overlaps || (s->cmp_from > 0
3266 && ! s->first_glyph->u.cmp.automatic))
3267 s->background_filled_p = 1;
3269 ns_maybe_dumpglyphs_background
3270 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3272 flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3273 (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3274 (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3275 NS_DUMPGLYPH_NORMAL));
3277 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3279 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3280 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3281 NS_FACE_FOREGROUND (s->face) = tmp;
3285 BOOL isComposite = s->first_glyph->type == COMPOSITE_GLYPH;
3286 int end = isComposite ? s->cmp_to : s->nchars;
3289 (s, s->cmp_from, end, s->x, s->ybase,
3290 (flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3291 || flags == NS_DUMPGLYPH_MOUSEFACE);
3296 NSColor *col = (NS_FACE_FOREGROUND (s->face) != 0
3297 ? ns_lookup_indexed_color (NS_FACE_FOREGROUND (s->face),
3299 : FRAME_FOREGROUND_COLOR (s->f));
3302 /* Draw underline, overline, strike-through. */
3303 ns_draw_text_decoration (s, s->face, col, s->width, s->x);
3306 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3308 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3309 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3310 NS_FACE_FOREGROUND (s->face) = tmp;
3316 case GLYPHLESS_GLYPH:
3317 n = ns_get_glyph_string_clip_rect (s, r);
3318 ns_focus (s->f, r, n);
3320 if (s->for_overlaps || (s->cmp_from > 0
3321 && ! s->first_glyph->u.cmp.automatic))
3322 s->background_filled_p = 1;
3324 ns_maybe_dumpglyphs_background
3325 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3327 /* Not yet implemented. */
3336 /* Draw box if not done already. */
3337 if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3339 n = ns_get_glyph_string_clip_rect (s, r);
3340 ns_focus (s->f, r, n);
3341 ns_dumpglyphs_box_or_relief (s);
3350 /* ==========================================================================
3354 ========================================================================== */
3358 ns_send_appdefined (int value)
3359 /* --------------------------------------------------------------------------
3360 Internal: post an appdefined event which EmacsApp-sendEvent will
3361 recognize and take as a command to halt the event loop.
3362 -------------------------------------------------------------------------- */
3364 /*NSTRACE (ns_send_appdefined); */
3366 #ifdef NS_IMPL_GNUSTEP
3367 // GNUstep needs postEvent to happen on the main thread.
3368 if (! [[NSThread currentThread] isMainThread])
3370 EmacsApp *app = (EmacsApp *)NSApp;
3371 app->nextappdefined = value;
3372 [app performSelectorOnMainThread:@selector (sendFromMainThread:)
3379 /* Only post this event if we haven't already posted one. This will end
3380 the [NXApp run] main loop after having processed all events queued at
3383 #ifdef NS_IMPL_COCOA
3384 if (! send_appdefined)
3386 /* OSX 10.10.1 swallows the AppDefined event we are sending ourselves
3387 in certain situations (rapid incoming events).
3388 So check if we have one, if not add one. */
3389 NSEvent *appev = [NSApp nextEventMatchingMask:NSApplicationDefinedMask
3390 untilDate:[NSDate distantPast]
3391 inMode:NSDefaultRunLoopMode
3393 if (! appev) send_appdefined = YES;
3397 if (send_appdefined)
3401 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
3402 send_appdefined = NO;
3404 /* Don't need wakeup timer any more */
3407 [timed_entry invalidate];
3408 [timed_entry release];
3412 nxev = [NSEvent otherEventWithType: NSApplicationDefined
3413 location: NSMakePoint (0, 0)
3416 windowNumber: [[NSApp mainWindow] windowNumber]
3417 context: [NSApp context]
3422 /* Post an application defined event on the event queue. When this is
3423 received the [NXApp run] will return, thus having processed all
3424 events which are currently queued. */
3425 [NSApp postEvent: nxev atStart: NO];
3429 #ifdef HAVE_NATIVE_FS
3433 Lisp_Object frame, tail;
3435 if (ns_last_use_native_fullscreen == ns_use_native_fullscreen)
3438 ns_last_use_native_fullscreen = ns_use_native_fullscreen;
3440 FOR_EACH_FRAME (tail, frame)
3442 struct frame *f = XFRAME (frame);
3445 EmacsView *view = FRAME_NS_VIEW (f);
3446 [view updateCollectionBehavior];
3452 /* GNUstep does not have cancelTracking. */
3453 #ifdef NS_IMPL_COCOA
3454 /* Check if menu open should be canceled or continued as normal. */
3456 ns_check_menu_open (NSMenu *menu)
3458 /* Click in menu bar? */
3459 NSArray *a = [[NSApp mainMenu] itemArray];
3463 if (menu == nil) // Menu tracking ended.
3465 if (menu_will_open_state == MENU_OPENING)
3466 menu_will_open_state = MENU_NONE;
3470 for (i = 0; ! found && i < [a count]; i++)
3471 found = menu == [[a objectAtIndex:i] submenu];
3474 if (menu_will_open_state == MENU_NONE && emacs_event)
3476 NSEvent *theEvent = [NSApp currentEvent];
3477 struct frame *emacsframe = SELECTED_FRAME ();
3479 [menu cancelTracking];
3480 menu_will_open_state = MENU_PENDING;
3481 emacs_event->kind = MENU_BAR_ACTIVATE_EVENT;
3482 EV_TRAILER (theEvent);
3484 CGEventRef ourEvent = CGEventCreate (NULL);
3485 menu_mouse_point = CGEventGetLocation (ourEvent);
3486 CFRelease (ourEvent);
3488 else if (menu_will_open_state == MENU_OPENING)
3490 menu_will_open_state = MENU_NONE;
3495 /* Redo saved menu click if state is MENU_PENDING. */
3497 ns_check_pending_open_menu ()
3499 if (menu_will_open_state == MENU_PENDING)
3501 CGEventSourceRef source
3502 = CGEventSourceCreate (kCGEventSourceStateHIDSystemState);
3504 CGEventRef event = CGEventCreateMouseEvent (source,
3505 kCGEventLeftMouseDown,
3507 kCGMouseButtonLeft);
3508 CGEventSetType (event, kCGEventLeftMouseDown);
3509 CGEventPost (kCGHIDEventTap, event);
3513 menu_will_open_state = MENU_OPENING;
3516 #endif /* NS_IMPL_COCOA */
3519 unwind_apploopnr (Lisp_Object not_used)
3522 n_emacs_events_pending = 0;
3523 ns_finish_events ();
3528 ns_read_socket (struct terminal *terminal, struct input_event *hold_quit)
3529 /* --------------------------------------------------------------------------
3530 External (hook): Post an event to ourself and keep reading events until
3531 we read it back again. In effect process all events which were waiting.
3532 From 21+ we have to manage the event buffer ourselves.
3533 -------------------------------------------------------------------------- */
3535 struct input_event ev;
3538 /* NSTRACE (ns_read_socket); */
3540 #ifdef HAVE_NATIVE_FS
3544 if ([NSApp modalWindow] != nil)
3547 if (hold_event_q.nr > 0)
3550 for (i = 0; i < hold_event_q.nr; ++i)
3551 kbd_buffer_store_event_hold (&hold_event_q.q[i], hold_quit);
3552 hold_event_q.nr = 0;
3557 n_emacs_events_pending = 0;
3558 ns_init_events (&ev);
3559 q_event_ptr = hold_quit;
3561 /* we manage autorelease pools by allocate/reallocate each time around
3562 the loop; strict nesting is occasionally violated but seems not to
3563 matter.. earlier methods using full nesting caused major memory leaks */
3564 [outerpool release];
3565 outerpool = [[NSAutoreleasePool alloc] init];
3567 /* If have pending open-file requests, attend to the next one of those. */
3568 if (ns_pending_files && [ns_pending_files count] != 0
3569 && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3571 [ns_pending_files removeObjectAtIndex: 0];
3573 /* Deal with pending service requests. */
3574 else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3576 NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3577 withArg: [ns_pending_service_args objectAtIndex: 0]])
3579 [ns_pending_service_names removeObjectAtIndex: 0];
3580 [ns_pending_service_args removeObjectAtIndex: 0];
3584 ptrdiff_t specpdl_count = SPECPDL_INDEX ();
3585 /* Run and wait for events. We must always send one NX_APPDEFINED event
3586 to ourself, otherwise [NXApp run] will never exit. */
3587 send_appdefined = YES;
3588 ns_send_appdefined (-1);
3590 if (++apploopnr != 1)
3594 record_unwind_protect (unwind_apploopnr, Qt);
3596 unbind_to (specpdl_count, Qnil); /* calls unwind_apploopnr */
3599 nevents = n_emacs_events_pending;
3600 n_emacs_events_pending = 0;
3601 ns_finish_events ();
3610 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3611 fd_set *exceptfds, struct timespec const *timeout,
3612 sigset_t const *sigmask)
3613 /* --------------------------------------------------------------------------
3614 Replacement for select, checking for events
3615 -------------------------------------------------------------------------- */
3619 struct input_event event;
3622 /* NSTRACE (ns_select); */
3624 #ifdef HAVE_NATIVE_FS
3628 if (hold_event_q.nr > 0)
3630 /* We already have events pending. */
3636 for (k = 0; k < nfds+1; k++)
3638 if (readfds && FD_ISSET(k, readfds)) ++nr;
3639 if (writefds && FD_ISSET(k, writefds)) ++nr;
3643 || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0))
3644 return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
3646 [outerpool release];
3647 outerpool = [[NSAutoreleasePool alloc] init];
3650 send_appdefined = YES;
3653 pthread_mutex_lock (&select_mutex);
3658 select_readfds = *readfds;
3659 select_valid += SELECT_HAVE_READ;
3663 select_writefds = *writefds;
3664 select_valid += SELECT_HAVE_WRITE;
3669 select_timeout = *timeout;
3670 select_valid += SELECT_HAVE_TMO;
3673 pthread_mutex_unlock (&select_mutex);
3675 /* Inform fd_handler that select should be called */
3677 emacs_write_sig (selfds[1], &c, 1);
3679 else if (nr == 0 && timeout)
3681 /* No file descriptor, just a timeout, no need to wake fd_handler */
3682 double time = timespectod (*timeout);
3683 timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3686 @selector (timeout_handler:)
3691 else /* No timeout and no file descriptors, can this happen? */
3693 /* Send appdefined so we exit from the loop */
3694 ns_send_appdefined (-1);
3698 ns_init_events (&event);
3699 if (++apploopnr != 1)
3705 ptrdiff_t specpdl_count = SPECPDL_INDEX ();
3706 record_unwind_protect (unwind_apploopnr, Qt);
3708 unbind_to (specpdl_count, Qnil); /* calls unwind_apploopnr */
3711 ns_finish_events ();
3712 if (nr > 0 && readfds)
3715 emacs_write_sig (selfds[1], &c, 1);
3719 t = last_appdefined_event_data;
3721 if (t != NO_APPDEFINED_DATA)
3723 last_appdefined_event_data = NO_APPDEFINED_DATA;
3727 /* The NX_APPDEFINED event we received was a timeout. */
3732 /* The NX_APPDEFINED event we received was the result of
3733 at least one real input event arriving. */
3739 /* Received back from select () in fd_handler; copy the results */
3740 pthread_mutex_lock (&select_mutex);
3741 if (readfds) *readfds = select_readfds;
3742 if (writefds) *writefds = select_writefds;
3743 pthread_mutex_unlock (&select_mutex);
3758 /* ==========================================================================
3762 ========================================================================== */
3766 ns_set_vertical_scroll_bar (struct window *window,
3767 int portion, int whole, int position)
3768 /* --------------------------------------------------------------------------
3769 External (hook): Update or add scrollbar
3770 -------------------------------------------------------------------------- */
3774 struct frame *f = XFRAME (WINDOW_FRAME (window));
3775 EmacsView *view = FRAME_NS_VIEW (f);
3777 int window_y, window_height;
3778 int top, left, height, width;
3779 BOOL update_p = YES;
3781 /* optimization; display engine sends WAY too many of these.. */
3782 if (!NILP (window->vertical_scroll_bar))
3784 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3785 if ([bar checkSamePosition: position portion: portion whole: whole])
3787 if (view->scrollbarsNeedingUpdate == 0)
3789 if (!windows_or_buffers_changed)
3793 view->scrollbarsNeedingUpdate--;
3798 NSTRACE (ns_set_vertical_scroll_bar);
3800 /* Get dimensions. */
3801 window_box (window, ANY_AREA, 0, &window_y, 0, &window_height);
3803 height = window_height;
3804 width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3805 left = WINDOW_SCROLL_BAR_AREA_X (window);
3807 r = NSMakeRect (left, top, width, height);
3808 /* the parent view is flipped, so we need to flip y value */
3810 r.origin.y = (v.size.height - r.size.height - r.origin.y);
3812 XSETWINDOW (win, window);
3815 /* we want at least 5 lines to display a scrollbar */
3816 if (WINDOW_TOTAL_LINES (window) < 5)
3818 if (!NILP (window->vertical_scroll_bar))
3820 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3821 [bar removeFromSuperview];
3822 wset_vertical_scroll_bar (window, Qnil);
3825 ns_clear_frame_area (f, left, top, width, height);
3830 if (NILP (window->vertical_scroll_bar))
3832 if (width > 0 && height > 0)
3833 ns_clear_frame_area (f, left, top, width, height);
3835 bar = [[EmacsScroller alloc] initFrame: r window: win];
3836 wset_vertical_scroll_bar (window, make_save_ptr (bar));
3842 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3843 oldRect = [bar frame];
3844 r.size.width = oldRect.size.width;
3845 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3847 if (oldRect.origin.x != r.origin.x)
3848 ns_clear_frame_area (f, left, top, width, height);
3854 [bar setPosition: position portion: portion whole: whole];
3860 ns_set_horizontal_scroll_bar (struct window *window,
3861 int portion, int whole, int position)
3862 /* --------------------------------------------------------------------------
3863 External (hook): Update or add scrollbar
3864 -------------------------------------------------------------------------- */
3868 struct frame *f = XFRAME (WINDOW_FRAME (window));
3869 EmacsView *view = FRAME_NS_VIEW (f);
3871 int top, height, left, width;
3872 int window_x, window_width;
3873 int pixel_width = WINDOW_PIXEL_WIDTH (window);
3874 BOOL update_p = YES;
3876 /* optimization; display engine sends WAY too many of these.. */
3877 if (!NILP (window->horizontal_scroll_bar))
3879 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
3880 if ([bar checkSamePosition: position portion: portion whole: whole])
3882 if (view->scrollbarsNeedingUpdate == 0)
3884 if (!windows_or_buffers_changed)
3888 view->scrollbarsNeedingUpdate--;
3893 NSTRACE (ns_set_horizontal_scroll_bar);
3895 /* Get dimensions. */
3896 window_box (window, ANY_AREA, 0, &window_x, &window_width, 0);
3898 width = window_width;
3899 height = WINDOW_CONFIG_SCROLL_BAR_LINES (window) * FRAME_LINE_HEIGHT (f);
3900 top = WINDOW_SCROLL_BAR_AREA_Y (window);
3902 r = NSMakeRect (left, top, width, height);
3903 /* the parent view is flipped, so we need to flip y value */
3905 /* ??????? PXW/scrollbars !!!!!!!!!!!!!!!!!!!! */
3906 r.origin.y = (v.size.height - r.size.height - r.origin.y);
3908 XSETWINDOW (win, window);
3911 if (WINDOW_TOTAL_COLS (window) < 5)
3913 if (!NILP (window->horizontal_scroll_bar))
3915 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
3916 [bar removeFromSuperview];
3917 wset_horizontal_scroll_bar (window, Qnil);
3919 ns_clear_frame_area (f, left, top, width, height);
3924 if (NILP (window->horizontal_scroll_bar))
3926 if (width > 0 && height > 0)
3927 ns_clear_frame_area (f, left, top, width, height);
3929 bar = [[EmacsScroller alloc] initFrame: r window: win];
3930 wset_horizontal_scroll_bar (window, make_save_ptr (bar));
3936 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
3937 oldRect = [bar frame];
3938 r.size.width = oldRect.size.width;
3939 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3941 if (oldRect.origin.x != r.origin.x)
3942 ns_clear_frame_area (f, left, top, width, height);
3949 [bar setPosition: position portion: portion whole: whole];
3955 ns_condemn_scroll_bars (struct frame *f)
3956 /* --------------------------------------------------------------------------
3957 External (hook): arrange for all frame's scrollbars to be removed
3958 at next call to judge_scroll_bars, except for those redeemed.
3959 -------------------------------------------------------------------------- */
3963 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3965 NSTRACE (ns_condemn_scroll_bars);
3967 for (i =[subviews count]-1; i >= 0; i--)
3969 view = [subviews objectAtIndex: i];
3970 if ([view isKindOfClass: [EmacsScroller class]])
3977 ns_redeem_scroll_bar (struct window *window)
3978 /* --------------------------------------------------------------------------
3979 External (hook): arrange to spare this window's scrollbar
3980 at next call to judge_scroll_bars.
3981 -------------------------------------------------------------------------- */
3984 NSTRACE (ns_redeem_scroll_bar);
3985 if (!NILP (window->vertical_scroll_bar))
3987 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3991 if (!NILP (window->horizontal_scroll_bar))
3993 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4000 ns_judge_scroll_bars (struct frame *f)
4001 /* --------------------------------------------------------------------------
4002 External (hook): destroy all scrollbars on frame that weren't
4003 redeemed after call to condemn_scroll_bars.
4004 -------------------------------------------------------------------------- */
4008 EmacsView *eview = FRAME_NS_VIEW (f);
4009 NSArray *subviews = [[eview superview] subviews];
4012 NSTRACE (ns_judge_scroll_bars);
4013 for (i = [subviews count]-1; i >= 0; --i)
4015 view = [subviews objectAtIndex: i];
4016 if (![view isKindOfClass: [EmacsScroller class]]) continue;
4022 [eview updateFrameSize: NO];
4025 /* ==========================================================================
4029 ========================================================================== */
4032 x_display_pixel_height (struct ns_display_info *dpyinfo)
4034 NSArray *screens = [NSScreen screens];
4035 NSEnumerator *enumerator = [screens objectEnumerator];
4040 while ((screen = [enumerator nextObject]) != nil)
4041 frame = NSUnionRect (frame, [screen frame]);
4043 return NSHeight (frame);
4047 x_display_pixel_width (struct ns_display_info *dpyinfo)
4049 NSArray *screens = [NSScreen screens];
4050 NSEnumerator *enumerator = [screens objectEnumerator];
4055 while ((screen = [enumerator nextObject]) != nil)
4056 frame = NSUnionRect (frame, [screen frame]);
4058 return NSWidth (frame);
4062 static Lisp_Object ns_string_to_lispmod (const char *s)
4063 /* --------------------------------------------------------------------------
4064 Convert modifier name to lisp symbol
4065 -------------------------------------------------------------------------- */
4067 if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
4069 else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
4071 else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
4073 else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
4075 else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
4077 else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
4085 ns_default (const char *parameter, Lisp_Object *result,
4086 Lisp_Object yesval, Lisp_Object noval,
4087 BOOL is_float, BOOL is_modstring)
4088 /* --------------------------------------------------------------------------
4089 Check a parameter value in user's preferences
4090 -------------------------------------------------------------------------- */
4092 const char *value = ns_get_defaults_value (parameter);
4098 if (c_strcasecmp (value, "YES") == 0)
4100 else if (c_strcasecmp (value, "NO") == 0)
4102 else if (is_float && (f = strtod (value, &pos), pos != value))
4103 *result = make_float (f);
4104 else if (is_modstring && value)
4105 *result = ns_string_to_lispmod (value);
4106 else fprintf (stderr,
4107 "Bad value for default \"%s\": \"%s\"\n", parameter, value);
4113 ns_initialize_display_info (struct ns_display_info *dpyinfo)
4114 /* --------------------------------------------------------------------------
4115 Initialize global info and storage for display.
4116 -------------------------------------------------------------------------- */
4118 NSScreen *screen = [NSScreen mainScreen];
4119 NSWindowDepth depth = [screen depth];
4121 dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
4122 dpyinfo->resy = 72.27;
4123 dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
4124 NSColorSpaceFromDepth (depth)]
4125 && ![NSCalibratedWhiteColorSpace isEqualToString:
4126 NSColorSpaceFromDepth (depth)];
4127 dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
4128 dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
4129 dpyinfo->color_table->colors = NULL;
4130 dpyinfo->root_window = 42; /* a placeholder.. */
4131 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
4132 dpyinfo->n_fonts = 0;
4133 dpyinfo->smallest_font_height = 1;
4134 dpyinfo->smallest_char_width = 1;
4136 reset_mouse_highlight (&dpyinfo->mouse_highlight);
4140 /* This and next define (many of the) public functions in this file. */
4141 /* x_... are generic versions in xdisp.c that we, and other terms, get away
4142 with using despite presence in the "system dependent" redisplay
4143 interface. In addition, many of the ns_ methods have code that is
4144 shared with all terms, indicating need for further refactoring. */
4145 extern frame_parm_handler ns_frame_parm_handlers[];
4146 static struct redisplay_interface ns_redisplay_interface =
4148 ns_frame_parm_handlers,
4152 x_clear_end_of_line,
4154 ns_after_update_window_line,
4155 ns_update_window_begin,
4156 ns_update_window_end,
4157 0, /* flush_display */
4158 x_clear_window_mouse_face,
4159 x_get_glyph_overhangs,
4160 x_fix_overlapping_area,
4161 ns_draw_fringe_bitmap,
4162 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
4163 0, /* destroy_fringe_bitmap */
4164 ns_compute_glyph_string_overhangs,
4165 ns_draw_glyph_string,
4166 ns_define_frame_cursor,
4167 ns_clear_frame_area,
4168 ns_draw_window_cursor,
4169 ns_draw_vertical_window_border,
4170 ns_draw_window_divider,
4171 ns_shift_glyphs_for_insert,
4178 ns_delete_display (struct ns_display_info *dpyinfo)
4184 /* This function is called when the last frame on a display is deleted. */
4186 ns_delete_terminal (struct terminal *terminal)
4188 struct ns_display_info *dpyinfo = terminal->display_info.ns;
4190 /* Protect against recursive calls. delete_frame in
4191 delete_terminal calls us back when it deletes our last frame. */
4192 if (!terminal->name)
4197 x_destroy_all_bitmaps (dpyinfo);
4198 ns_delete_display (dpyinfo);
4203 static struct terminal *
4204 ns_create_terminal (struct ns_display_info *dpyinfo)
4205 /* --------------------------------------------------------------------------
4206 Set up use of NS before we make the first connection.
4207 -------------------------------------------------------------------------- */
4209 struct terminal *terminal;
4211 NSTRACE (ns_create_terminal);
4213 terminal = create_terminal (output_ns, &ns_redisplay_interface);
4215 terminal->display_info.ns = dpyinfo;
4216 dpyinfo->terminal = terminal;
4218 terminal->clear_frame_hook = ns_clear_frame;
4219 terminal->ring_bell_hook = ns_ring_bell;
4220 terminal->update_begin_hook = ns_update_begin;
4221 terminal->update_end_hook = ns_update_end;
4222 terminal->read_socket_hook = ns_read_socket;
4223 terminal->frame_up_to_date_hook = ns_frame_up_to_date;
4224 terminal->mouse_position_hook = ns_mouse_position;
4225 terminal->frame_rehighlight_hook = ns_frame_rehighlight;
4226 terminal->frame_raise_lower_hook = ns_frame_raise_lower;
4227 terminal->fullscreen_hook = ns_fullscreen_hook;
4228 terminal->menu_show_hook = ns_menu_show;
4229 terminal->popup_dialog_hook = ns_popup_dialog;
4230 terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
4231 terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
4232 terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
4233 terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
4234 terminal->delete_frame_hook = x_destroy_window;
4235 terminal->delete_terminal_hook = ns_delete_terminal;
4236 /* Other hooks are NULL by default. */
4242 struct ns_display_info *
4243 ns_term_init (Lisp_Object display_name)
4244 /* --------------------------------------------------------------------------
4245 Start the Application and get things rolling.
4246 -------------------------------------------------------------------------- */
4248 struct terminal *terminal;
4249 struct ns_display_info *dpyinfo;
4250 static int ns_initialized = 0;
4253 if (ns_initialized) return x_display_list;
4256 NSTRACE (ns_term_init);
4258 [outerpool release];
4259 outerpool = [[NSAutoreleasePool alloc] init];
4261 /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4262 /*GSDebugAllocationActive (YES); */
4266 Fset_input_interrupt_mode (Qnil);
4268 if (selfds[0] == -1)
4270 if (emacs_pipe (selfds) != 0)
4272 fprintf (stderr, "Failed to create pipe: %s\n",
4273 emacs_strerror (errno));
4277 fcntl (selfds[0], F_SETFL, O_NONBLOCK|fcntl (selfds[0], F_GETFL));
4278 FD_ZERO (&select_readfds);
4279 FD_ZERO (&select_writefds);
4280 pthread_mutex_init (&select_mutex, NULL);
4283 ns_pending_files = [[NSMutableArray alloc] init];
4284 ns_pending_service_names = [[NSMutableArray alloc] init];
4285 ns_pending_service_args = [[NSMutableArray alloc] init];
4287 /* Start app and create the main menu, window, view.
4288 Needs to be here because ns_initialize_display_info () uses AppKit classes.
4289 The view will then ask the NSApp to stop and return to Emacs. */
4290 [EmacsApp sharedApplication];
4293 [NSApp setDelegate: NSApp];
4295 /* Start the select thread. */
4296 [NSThread detachNewThreadSelector:@selector (fd_handler:)
4300 /* debugging: log all notifications */
4301 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
4302 selector: @selector (logNotification:)
4303 name: nil object: nil]; */
4305 dpyinfo = xzalloc (sizeof *dpyinfo);
4307 ns_initialize_display_info (dpyinfo);
4308 terminal = ns_create_terminal (dpyinfo);
4310 terminal->kboard = allocate_kboard (Qns);
4311 /* Don't let the initial kboard remain current longer than necessary.
4312 That would cause problems if a file loaded on startup tries to
4313 prompt in the mini-buffer. */
4314 if (current_kboard == initial_kboard)
4315 current_kboard = terminal->kboard;
4316 terminal->kboard->reference_count++;
4318 dpyinfo->next = x_display_list;
4319 x_display_list = dpyinfo;
4321 dpyinfo->name_list_element = Fcons (display_name, Qnil);
4323 terminal->name = xstrdup (SSDATA (display_name));
4327 if (!inhibit_x_resources)
4329 ns_default ("GSFontAntiAlias", &ns_antialias_text,
4332 /* this is a standard variable */
4333 ns_default ("AppleAntiAliasingThreshold", &tmp,
4334 make_float (10.0), make_float (6.0), YES, NO);
4335 ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4339 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4343 Lisp_Object color_file, color_map, color;
4347 color_file = Fexpand_file_name (build_string ("rgb.txt"),
4348 Fsymbol_value (intern ("data-directory")));
4350 color_map = Fx_load_color_file (color_file);
4351 if (NILP (color_map))
4352 fatal ("Could not read %s.\n", SDATA (color_file));
4354 cl = [[NSColorList alloc] initWithName: @"Emacs"];
4355 for ( ; CONSP (color_map); color_map = XCDR (color_map))
4357 color = XCAR (color_map);
4358 name = SSDATA (XCAR (color));
4359 c = XINT (XCDR (color));
4361 [NSColor colorForEmacsRed: RED_FROM_ULONG (c) / 255.0
4362 green: GREEN_FROM_ULONG (c) / 255.0
4363 blue: BLUE_FROM_ULONG (c) / 255.0
4365 forKey: [NSString stringWithUTF8String: name]];
4367 [cl writeToFile: nil];
4372 #ifdef NS_IMPL_GNUSTEP
4373 Vwindow_system_version = build_string (gnustep_base_version);
4375 /*PSnextrelease (128, c); */
4376 char c[DBL_BUFSIZE_BOUND];
4377 int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4378 Vwindow_system_version = make_unibyte_string (c, len);
4382 delete_keyboard_wait_descriptor (0);
4384 ns_app_name = [[NSProcessInfo processInfo] processName];
4386 /* Set up OS X app menu */
4387 #ifdef NS_IMPL_COCOA
4391 /* set up the application menu */
4392 svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4393 [svcsMenu setAutoenablesItems: NO];
4394 appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4395 [appMenu setAutoenablesItems: NO];
4396 mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4397 dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4399 [appMenu insertItemWithTitle: @"About Emacs"
4400 action: @selector (orderFrontStandardAboutPanel:)
4403 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4404 [appMenu insertItemWithTitle: @"Preferences..."
4405 action: @selector (showPreferencesWindow:)
4408 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4409 item = [appMenu insertItemWithTitle: @"Services"
4410 action: @selector (menuDown:)
4413 [appMenu setSubmenu: svcsMenu forItem: item];
4414 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4415 [appMenu insertItemWithTitle: @"Hide Emacs"
4416 action: @selector (hide:)
4419 item = [appMenu insertItemWithTitle: @"Hide Others"
4420 action: @selector (hideOtherApplications:)
4423 [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4424 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4425 [appMenu insertItemWithTitle: @"Quit Emacs"
4426 action: @selector (terminate:)
4430 item = [mainMenu insertItemWithTitle: ns_app_name
4431 action: @selector (menuDown:)
4434 [mainMenu setSubmenu: appMenu forItem: item];
4435 [dockMenu insertItemWithTitle: @"New Frame"
4436 action: @selector (newFrame:)
4440 [NSApp setMainMenu: mainMenu];
4441 [NSApp setAppleMenu: appMenu];
4442 [NSApp setServicesMenu: svcsMenu];
4443 /* Needed at least on Cocoa, to get dock menu to show windows */
4444 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4446 [[NSNotificationCenter defaultCenter]
4447 addObserver: mainMenu
4448 selector: @selector (trackingNotification:)
4449 name: NSMenuDidBeginTrackingNotification object: mainMenu];
4450 [[NSNotificationCenter defaultCenter]
4451 addObserver: mainMenu
4452 selector: @selector (trackingNotification:)
4453 name: NSMenuDidEndTrackingNotification object: mainMenu];
4455 #endif /* MAC OS X menu setup */
4457 /* Register our external input/output types, used for determining
4458 applicable services and also drag/drop eligibility. */
4459 ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
4460 ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
4462 ns_drag_types = [[NSArray arrayWithObjects:
4464 NSTabularTextPboardType,
4465 NSFilenamesPboardType,
4466 NSURLPboardType, nil] retain];
4468 /* If fullscreen is in init/default-frame-alist, focus isn't set
4469 right for fullscreen windows, so set this. */
4470 [NSApp activateIgnoringOtherApps:YES];
4473 ns_do_open_file = YES;
4475 #ifdef NS_IMPL_GNUSTEP
4476 /* GNUstep steals SIGCHLD for use in NSTask, but we don't use NSTask.
4477 We must re-catch it so subprocess works. */
4478 catch_child_signal ();
4485 ns_term_shutdown (int sig)
4487 [[NSUserDefaults standardUserDefaults] synchronize];
4489 /* code not reached in emacs.c after this is called by shut_down_emacs: */
4490 if (STRINGP (Vauto_save_list_file_name))
4491 unlink (SSDATA (Vauto_save_list_file_name));
4493 if (sig == 0 || sig == SIGTERM)
4495 [NSApp terminate: NSApp];
4497 else // force a stack trace to happen
4504 /* ==========================================================================
4506 EmacsApp implementation
4508 ========================================================================== */
4511 @implementation EmacsApp
4515 if (self = [super init])
4517 #ifdef NS_IMPL_COCOA
4518 self->isFirst = YES;
4520 #ifdef NS_IMPL_GNUSTEP
4521 self->applicationDidFinishLaunchingCalled = NO;
4528 #ifdef NS_IMPL_COCOA
4531 #ifndef NSAppKitVersionNumber10_9
4532 #define NSAppKitVersionNumber10_9 1265
4535 if ((int)NSAppKitVersionNumber != NSAppKitVersionNumber10_9)
4541 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
4543 if (isFirst) [self finishLaunching];
4546 shouldKeepRunning = YES;
4550 pool = [[NSAutoreleasePool alloc] init];
4553 [self nextEventMatchingMask:NSAnyEventMask
4554 untilDate:[NSDate distantFuture]
4555 inMode:NSDefaultRunLoopMode
4558 [self sendEvent:event];
4559 [self updateWindows];
4560 } while (shouldKeepRunning);
4565 - (void)stop: (id)sender
4567 shouldKeepRunning = NO;
4568 // Stop possible dialog also. Noop if no dialog present.
4569 // The file dialog still leaks 7k - 10k on 10.9 though.
4570 [super stop:sender];
4572 #endif /* NS_IMPL_COCOA */
4574 - (void)logNotification: (NSNotification *)notification
4576 const char *name = [[notification name] UTF8String];
4577 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4578 && !strstr (name, "WindowNumber"))
4579 NSLog (@"notification: '%@'", [notification name]);
4583 - (void)sendEvent: (NSEvent *)theEvent
4584 /* --------------------------------------------------------------------------
4585 Called when NSApp is running for each event received. Used to stop
4586 the loop when we choose, since there's no way to just run one iteration.
4587 -------------------------------------------------------------------------- */
4589 int type = [theEvent type];
4590 NSWindow *window = [theEvent window];
4592 /* NSTRACE (sendEvent); */
4593 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4595 #ifdef NS_IMPL_GNUSTEP
4596 // Keyboard events aren't propagated to file dialogs for some reason.
4597 if ([NSApp modalWindow] != nil &&
4598 (type == NSKeyDown || type == NSKeyUp || type == NSFlagsChanged))
4600 [[NSApp modalWindow] sendEvent: theEvent];
4605 if (represented_filename != nil && represented_frame)
4607 NSString *fstr = represented_filename;
4608 NSView *view = FRAME_NS_VIEW (represented_frame);
4609 #ifdef NS_IMPL_COCOA
4610 /* work around a bug observed on 10.3 and later where
4611 setTitleWithRepresentedFilename does not clear out previous state
4612 if given filename does not exist */
4613 if (! [[NSFileManager defaultManager] fileExistsAtPath: fstr])
4614 [[view window] setRepresentedFilename: @""];
4616 [[view window] setRepresentedFilename: fstr];
4617 [represented_filename release];
4618 represented_filename = nil;
4619 represented_frame = NULL;
4622 if (type == NSApplicationDefined)
4624 switch ([theEvent data2])
4626 #ifdef NS_IMPL_COCOA
4627 case NSAPP_DATA2_RUNASSCRIPT:
4632 case NSAPP_DATA2_RUNFILEDIALOG:
4633 ns_run_file_dialog ();
4639 if (type == NSCursorUpdate && window == nil)
4641 fprintf (stderr, "Dropping external cursor update event.\n");
4645 if (type == NSApplicationDefined)
4647 /* Events posted by ns_send_appdefined interrupt the run loop here.
4648 But, if a modal window is up, an appdefined can still come through,
4649 (e.g., from a makeKeyWindow event) but stopping self also stops the
4650 modal loop. Just defer it until later. */
4651 if ([NSApp modalWindow] == nil)
4653 last_appdefined_event_data = [theEvent data1];
4658 send_appdefined = YES;
4663 #ifdef NS_IMPL_COCOA
4664 /* If no dialog and none of our frames have focus and it is a move, skip it.
4665 It is a mouse move in an auxiliary menu, i.e. on the top right on OSX,
4666 such as Wifi, sound, date or similar.
4667 This prevents "spooky" highlighting in the frame under the menu. */
4668 if (type == NSMouseMoved && [NSApp modalWindow] == nil)
4670 struct ns_display_info *di;
4671 BOOL has_focus = NO;
4672 for (di = x_display_list; ! has_focus && di; di = di->next)
4673 has_focus = di->x_focus_frame != 0;
4679 [super sendEvent: theEvent];
4683 - (void)showPreferencesWindow: (id)sender
4685 struct frame *emacsframe = SELECTED_FRAME ();
4686 NSEvent *theEvent = [NSApp currentEvent];
4690 emacs_event->kind = NS_NONKEY_EVENT;
4691 emacs_event->code = KEY_NS_SHOW_PREFS;
4692 emacs_event->modifiers = 0;
4693 EV_TRAILER (theEvent);
4697 - (void)newFrame: (id)sender
4699 struct frame *emacsframe = SELECTED_FRAME ();
4700 NSEvent *theEvent = [NSApp currentEvent];
4704 emacs_event->kind = NS_NONKEY_EVENT;
4705 emacs_event->code = KEY_NS_NEW_FRAME;
4706 emacs_event->modifiers = 0;
4707 EV_TRAILER (theEvent);
4711 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4712 - (BOOL) openFile: (NSString *)fileName
4714 struct frame *emacsframe = SELECTED_FRAME ();
4715 NSEvent *theEvent = [NSApp currentEvent];
4720 emacs_event->kind = NS_NONKEY_EVENT;
4721 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4722 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4723 ns_input_line = Qnil; /* can be start or cons start,end */
4724 emacs_event->modifiers =0;
4725 EV_TRAILER (theEvent);
4731 /* **************************************************************************
4733 EmacsApp delegate implementation
4735 ************************************************************************** */
4737 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4738 /* --------------------------------------------------------------------------
4739 When application is loaded, terminate event loop in ns_term_init
4740 -------------------------------------------------------------------------- */
4742 NSTRACE (applicationDidFinishLaunching);
4743 #ifdef NS_IMPL_GNUSTEP
4744 ((EmacsApp *)self)->applicationDidFinishLaunchingCalled = YES;
4746 [NSApp setServicesProvider: NSApp];
4748 [self antialiasThresholdDidChange:nil];
4749 #ifdef NS_IMPL_COCOA
4750 [[NSNotificationCenter defaultCenter]
4752 selector:@selector(antialiasThresholdDidChange:)
4753 name:NSAntialiasThresholdChangedNotification
4757 ns_send_appdefined (-2);
4760 - (void)antialiasThresholdDidChange:(NSNotification *)notification
4762 #ifdef NS_IMPL_COCOA
4763 macfont_update_antialias_threshold ();
4768 /* Termination sequences:
4771 MenuBar | File | Exit:
4772 Select Quit from App menubar:
4774 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4777 Select Quit from Dock menu:
4780 Cancel -> Nothing else
4784 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4789 - (void) terminate: (id)sender
4791 struct frame *emacsframe = SELECTED_FRAME ();
4796 emacs_event->kind = NS_NONKEY_EVENT;
4797 emacs_event->code = KEY_NS_POWER_OFF;
4798 emacs_event->arg = Qt; /* mark as non-key event */
4799 EV_TRAILER ((id)nil);
4803 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4807 if (NILP (ns_confirm_quit)) // || ns_shutdown_properly --> TO DO
4808 return NSTerminateNow;
4810 ret = NSRunAlertPanel(ns_app_name,
4811 @"Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?",
4812 @"Save Buffers and Exit", @"Cancel", nil);
4814 if (ret == NSAlertDefaultReturn)
4815 return NSTerminateNow;
4816 else if (ret == NSAlertAlternateReturn)
4817 return NSTerminateCancel;
4818 return NSTerminateNow; /* just in case */
4822 not_in_argv (NSString *arg)
4825 const char *a = [arg UTF8String];
4826 for (k = 1; k < initial_argc; ++k)
4827 if (strcmp (a, initial_argv[k]) == 0) return 0;
4831 /* Notification from the Workspace to open a file */
4832 - (BOOL)application: sender openFile: (NSString *)file
4834 if (ns_do_open_file || not_in_argv (file))
4835 [ns_pending_files addObject: file];
4840 /* Open a file as a temporary file */
4841 - (BOOL)application: sender openTempFile: (NSString *)file
4843 if (ns_do_open_file || not_in_argv (file))
4844 [ns_pending_files addObject: file];
4849 /* Notification from the Workspace to open a file noninteractively (?) */
4850 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4852 if (ns_do_open_file || not_in_argv (file))
4853 [ns_pending_files addObject: file];
4857 /* Notification from the Workspace to open multiple files */
4858 - (void)application: sender openFiles: (NSArray *)fileList
4860 NSEnumerator *files = [fileList objectEnumerator];
4862 /* Don't open files from the command line unconditionally,
4863 Cocoa parses the command line wrong, --option value tries to open value
4864 if --option is the last option. */
4865 while ((file = [files nextObject]) != nil)
4866 if (ns_do_open_file || not_in_argv (file))
4867 [ns_pending_files addObject: file];
4869 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4874 /* Handle dock menu requests. */
4875 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4881 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4882 - (void)applicationWillBecomeActive: (NSNotification *)notification
4884 //ns_app_active=YES;
4886 - (void)applicationDidBecomeActive: (NSNotification *)notification
4888 NSTRACE (applicationDidBecomeActive);
4890 #ifdef NS_IMPL_GNUSTEP
4891 if (! applicationDidFinishLaunchingCalled)
4892 [self applicationDidFinishLaunching:notification];
4894 //ns_app_active=YES;
4896 ns_update_auto_hide_menu_bar ();
4897 // No constraining takes place when the application is not active.
4898 ns_constrain_all_frames ();
4900 - (void)applicationDidResignActive: (NSNotification *)notification
4903 ns_send_appdefined (-1);
4908 /* ==========================================================================
4910 EmacsApp aux handlers for managing event loop
4912 ========================================================================== */
4915 - (void)timeout_handler: (NSTimer *)timedEntry
4916 /* --------------------------------------------------------------------------
4917 The timeout specified to ns_select has passed.
4918 -------------------------------------------------------------------------- */
4920 /*NSTRACE (timeout_handler); */
4921 ns_send_appdefined (-2);
4924 #ifdef NS_IMPL_GNUSTEP
4925 - (void)sendFromMainThread:(id)unused
4927 ns_send_appdefined (nextappdefined);
4931 - (void)fd_handler:(id)unused
4932 /* --------------------------------------------------------------------------
4933 Check data waiting on file descriptors and terminate if so
4934 -------------------------------------------------------------------------- */
4937 int waiting = 1, nfds;
4940 fd_set readfds, writefds, *wfds;
4941 struct timespec timeout, *tmo;
4942 NSAutoreleasePool *pool = nil;
4944 /* NSTRACE (fd_handler); */
4949 pool = [[NSAutoreleasePool alloc] init];
4955 FD_SET (selfds[0], &fds);
4956 result = select (selfds[0]+1, &fds, NULL, NULL, NULL);
4957 if (result > 0 && read (selfds[0], &c, 1) == 1 && c == 'g')
4962 pthread_mutex_lock (&select_mutex);
4965 if (select_valid & SELECT_HAVE_READ)
4966 readfds = select_readfds;
4970 if (select_valid & SELECT_HAVE_WRITE)
4972 writefds = select_writefds;
4977 if (select_valid & SELECT_HAVE_TMO)
4979 timeout = select_timeout;
4985 pthread_mutex_unlock (&select_mutex);
4987 FD_SET (selfds[0], &readfds);
4988 if (selfds[0] >= nfds) nfds = selfds[0]+1;
4990 result = pselect (nfds, &readfds, wfds, NULL, tmo, NULL);
4993 ns_send_appdefined (-2);
4994 else if (result > 0)
4996 if (FD_ISSET (selfds[0], &readfds))
4998 if (read (selfds[0], &c, 1) == 1 && c == 's')
5003 pthread_mutex_lock (&select_mutex);
5004 if (select_valid & SELECT_HAVE_READ)
5005 select_readfds = readfds;
5006 if (select_valid & SELECT_HAVE_WRITE)
5007 select_writefds = writefds;
5008 if (select_valid & SELECT_HAVE_TMO)
5009 select_timeout = timeout;
5010 pthread_mutex_unlock (&select_mutex);
5012 ns_send_appdefined (result);
5022 /* ==========================================================================
5026 ========================================================================== */
5028 /* called from system: queue for next pass through event loop */
5029 - (void)requestService: (NSPasteboard *)pboard
5030 userData: (NSString *)userData
5031 error: (NSString **)error
5033 [ns_pending_service_names addObject: userData];
5034 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
5035 SSDATA (ns_string_from_pasteboard (pboard))]];
5039 /* called from ns_read_socket to clear queue */
5040 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
5042 struct frame *emacsframe = SELECTED_FRAME ();
5043 NSEvent *theEvent = [NSApp currentEvent];
5048 emacs_event->kind = NS_NONKEY_EVENT;
5049 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
5050 ns_input_spi_name = build_string ([name UTF8String]);
5051 ns_input_spi_arg = build_string ([arg UTF8String]);
5052 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5053 EV_TRAILER (theEvent);
5063 /* ==========================================================================
5065 EmacsView implementation
5067 ========================================================================== */
5070 @implementation EmacsView
5072 /* needed to inform when window closed from LISP */
5073 - (void) setWindowClosing: (BOOL)closing
5075 windowClosing = closing;
5081 NSTRACE (EmacsView_dealloc);
5083 if (fs_state == FULLSCREEN_BOTH)
5084 [nonfs_window release];
5089 /* called on font panel selection */
5090 - (void)changeFont: (id)sender
5092 NSEvent *e = [[self window] currentEvent];
5093 struct face *face = FRAME_DEFAULT_FACE (emacsframe);
5094 struct font *font = face->font;
5099 NSTRACE (changeFont);
5104 #ifdef NS_IMPL_GNUSTEP
5105 nsfont = ((struct nsfont_info *)font)->nsfont;
5107 #ifdef NS_IMPL_COCOA
5108 nsfont = (NSFont *) macfont_get_nsctfont (font);
5111 if ((newFont = [sender convertFont: nsfont]))
5113 SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
5115 emacs_event->kind = NS_NONKEY_EVENT;
5116 emacs_event->modifiers = 0;
5117 emacs_event->code = KEY_NS_CHANGE_FONT;
5119 size = [newFont pointSize];
5120 ns_input_fontsize = make_number (lrint (size));
5121 ns_input_font = build_string ([[newFont familyName] UTF8String]);
5127 - (BOOL)acceptsFirstResponder
5129 NSTRACE (acceptsFirstResponder);
5134 - (void)resetCursorRects
5136 NSRect visible = [self visibleRect];
5137 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
5138 NSTRACE (resetCursorRects);
5140 if (currentCursor == nil)
5141 currentCursor = [NSCursor arrowCursor];
5143 if (!NSIsEmptyRect (visible))
5144 [self addCursorRect: visible cursor: currentCursor];
5145 [currentCursor setOnMouseEntered: YES];
5150 /*****************************************************************************/
5151 /* Keyboard handling. */
5154 - (void)keyDown: (NSEvent *)theEvent
5156 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5158 unsigned fnKeysym = 0;
5159 static NSMutableArray *nsEvArray;
5160 #ifdef NS_IMPL_GNUSTEP
5161 static BOOL firstTime = YES;
5164 unsigned int flags = [theEvent modifierFlags];
5168 /* Rhapsody and OS X give up and down events for the arrow keys */
5169 if (ns_fake_keydown == YES)
5170 ns_fake_keydown = NO;
5171 else if ([theEvent type] != NSKeyDown)
5177 if (![[self window] isKeyWindow]
5178 && [[theEvent window] isKindOfClass: [EmacsWindow class]]
5179 /* we must avoid an infinite loop here. */
5180 && (EmacsView *)[[theEvent window] delegate] != self)
5182 /* XXX: There is an occasional condition in which, when Emacs display
5183 updates a different frame from the current one, and temporarily
5184 selects it, then processes some interrupt-driven input
5185 (dispnew.c:3878), OS will send the event to the correct NSWindow, but
5186 for some reason that window has its first responder set to the NSView
5187 most recently updated (I guess), which is not the correct one. */
5188 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
5192 if (nsEvArray == nil)
5193 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
5195 [NSCursor setHiddenUntilMouseMoves: YES];
5197 if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
5199 clear_mouse_face (hlinfo);
5200 hlinfo->mouse_face_hidden = 1;
5203 if (!processingCompose)
5205 /* When using screen sharing, no left or right information is sent,
5206 so use Left key in those cases. */
5207 int is_left_key, is_right_key;
5209 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
5210 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
5212 /* (Carbon way: [theEvent keyCode]) */
5214 /* is it a "function key"? */
5215 /* Note: Sometimes a plain key will have the NSNumericPadKeyMask
5216 flag set (this is probably a bug in the OS).
5218 if (code < 0x00ff && (flags&NSNumericPadKeyMask))
5220 fnKeysym = ns_convert_key ([theEvent keyCode] | NSNumericPadKeyMask);
5224 fnKeysym = ns_convert_key (code);
5229 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
5230 because Emacs treats Delete and KP-Delete same (in simple.el). */
5231 if ((fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
5232 #ifdef NS_IMPL_GNUSTEP
5233 /* GNUstep uses incompatible keycodes, even for those that are
5234 supposed to be hardware independent. Just check for delete.
5235 Keypad delete does not have keysym 0xFFFF.
5236 See http://savannah.gnu.org/bugs/?25395
5238 || (fnKeysym == 0xFFFF && code == 127)
5241 code = 0xFF08; /* backspace */
5246 /* are there modifiers? */
5247 emacs_event->modifiers = 0;
5249 if (flags & NSHelpKeyMask)
5250 emacs_event->modifiers |= hyper_modifier;
5252 if (flags & NSShiftKeyMask)
5253 emacs_event->modifiers |= shift_modifier;
5255 is_right_key = (flags & NSRightCommandKeyMask) == NSRightCommandKeyMask;
5256 is_left_key = (flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask
5257 || (! is_right_key && (flags & NSCommandKeyMask) == NSCommandKeyMask);
5260 emacs_event->modifiers |= parse_solitary_modifier
5261 (EQ (ns_right_command_modifier, Qleft)
5262 ? ns_command_modifier
5263 : ns_right_command_modifier);
5267 emacs_event->modifiers |= parse_solitary_modifier
5268 (ns_command_modifier);
5270 /* if super (default), take input manager's word so things like
5271 dvorak / qwerty layout work */
5272 if (EQ (ns_command_modifier, Qsuper)
5274 && [[theEvent characters] length] != 0)
5276 /* XXX: the code we get will be unshifted, so if we have
5277 a shift modifier, must convert ourselves */
5278 if (!(flags & NSShiftKeyMask))
5279 code = [[theEvent characters] characterAtIndex: 0];
5281 /* this is ugly and also requires linking w/Carbon framework
5282 (for LMGetKbdType) so for now leave this rare (?) case
5283 undealt with.. in future look into CGEvent methods */
5286 long smv = GetScriptManagerVariable (smKeyScript);
5287 Handle uchrHandle = GetResource
5288 ('uchr', GetScriptVariable (smv, smScriptKeys));
5290 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
5291 [[theEvent characters] characterAtIndex: 0],
5292 kUCKeyActionDisplay,
5293 (flags & ~NSCommandKeyMask) >> 8,
5294 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
5295 &dummy, 1, &dummy, &code);
5302 is_right_key = (flags & NSRightControlKeyMask) == NSRightControlKeyMask;
5303 is_left_key = (flags & NSLeftControlKeyMask) == NSLeftControlKeyMask
5304 || (! is_right_key && (flags & NSControlKeyMask) == NSControlKeyMask);
5307 emacs_event->modifiers |= parse_solitary_modifier
5308 (EQ (ns_right_control_modifier, Qleft)
5309 ? ns_control_modifier
5310 : ns_right_control_modifier);
5313 emacs_event->modifiers |= parse_solitary_modifier
5314 (ns_control_modifier);
5316 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
5317 emacs_event->modifiers |=
5318 parse_solitary_modifier (ns_function_modifier);
5320 left_is_none = NILP (ns_alternate_modifier)
5321 || EQ (ns_alternate_modifier, Qnone);
5323 is_right_key = (flags & NSRightAlternateKeyMask)
5324 == NSRightAlternateKeyMask;
5325 is_left_key = (flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask
5327 && (flags & NSAlternateKeyMask) == NSAlternateKeyMask);
5331 if ((NILP (ns_right_alternate_modifier)
5332 || EQ (ns_right_alternate_modifier, Qnone)
5333 || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
5335 { /* accept pre-interp alt comb */
5336 if ([[theEvent characters] length] > 0)
5337 code = [[theEvent characters] characterAtIndex: 0];
5338 /*HACK: clear lone shift modifier to stop next if from firing */
5339 if (emacs_event->modifiers == shift_modifier)
5340 emacs_event->modifiers = 0;
5343 emacs_event->modifiers |= parse_solitary_modifier
5344 (EQ (ns_right_alternate_modifier, Qleft)
5345 ? ns_alternate_modifier
5346 : ns_right_alternate_modifier);
5349 if (is_left_key) /* default = meta */
5351 if (left_is_none && !fnKeysym)
5352 { /* accept pre-interp alt comb */
5353 if ([[theEvent characters] length] > 0)
5354 code = [[theEvent characters] characterAtIndex: 0];
5355 /*HACK: clear lone shift modifier to stop next if from firing */
5356 if (emacs_event->modifiers == shift_modifier)
5357 emacs_event->modifiers = 0;
5360 emacs_event->modifiers |=
5361 parse_solitary_modifier (ns_alternate_modifier);
5365 fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
5366 code, fnKeysym, flags, emacs_event->modifiers);
5368 /* if it was a function key or had modifiers, pass it directly to emacs */
5369 if (fnKeysym || (emacs_event->modifiers
5370 && (emacs_event->modifiers != shift_modifier)
5371 && [[theEvent charactersIgnoringModifiers] length] > 0))
5372 /*[[theEvent characters] length] */
5374 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5376 code |= (1<<28)|(3<<16);
5377 else if (code == 0x7f)
5378 code |= (1<<28)|(3<<16);
5380 emacs_event->kind = code > 0xFF
5381 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5383 emacs_event->code = code;
5384 EV_TRAILER (theEvent);
5385 processingCompose = NO;
5391 #ifdef NS_IMPL_GNUSTEP
5392 /* if we get here we should send the key for input manager processing */
5393 /* Disable warning, there is nothing a user can do about it anyway, and
5394 it does not seem to matter. */
5396 if (firstTime && [[NSInputManager currentInputManager]
5397 wantsToDelayTextChangeNotifications] == NO)
5399 "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
5403 if (NS_KEYLOG && !processingCompose)
5404 fprintf (stderr, "keyDown: Begin compose sequence.\n");
5406 processingCompose = YES;
5407 [nsEvArray addObject: theEvent];
5408 [self interpretKeyEvents: nsEvArray];
5409 [nsEvArray removeObject: theEvent];
5413 #ifdef NS_IMPL_COCOA
5414 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
5415 decided not to send key-down for.
5416 See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
5417 This only applies on Tiger and earlier.
5418 If it matches one of these, send it on to keyDown. */
5419 -(void)keyUp: (NSEvent *)theEvent
5421 int flags = [theEvent modifierFlags];
5422 int code = [theEvent keyCode];
5423 if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
5424 code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
5427 fprintf (stderr, "keyUp: passed test");
5428 ns_fake_keydown = YES;
5429 [self keyDown: theEvent];
5435 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
5438 /* <NSTextInput>: called when done composing;
5439 NOTE: also called when we delete over working text, followed immed.
5440 by doCommandBySelector: deleteBackward: */
5441 - (void)insertText: (id)aString
5444 int len = [(NSString *)aString length];
5448 NSLog (@"insertText '%@'\tlen = %d", aString, len);
5449 processingCompose = NO;
5454 /* first, clear any working text */
5455 if (workingText != nil)
5456 [self deleteWorkingText];
5458 /* now insert the string as keystrokes */
5459 for (i =0; i<len; i++)
5461 code = [aString characterAtIndex: i];
5462 /* TODO: still need this? */
5464 code = '~'; /* 0x7E */
5465 if (code != 32) /* Space */
5466 emacs_event->modifiers = 0;
5468 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5469 emacs_event->code = code;
5470 EV_TRAILER ((id)nil);
5475 /* <NSTextInput>: inserts display of composing characters */
5476 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
5478 NSString *str = [aString respondsToSelector: @selector (string)] ?
5479 [aString string] : aString;
5481 NSLog (@"setMarkedText '%@' len =%lu range %lu from %lu",
5482 str, (unsigned long)[str length],
5483 (unsigned long)selRange.length,
5484 (unsigned long)selRange.location);
5486 if (workingText != nil)
5487 [self deleteWorkingText];
5488 if ([str length] == 0)
5494 processingCompose = YES;
5495 workingText = [str copy];
5496 ns_working_text = build_string ([workingText UTF8String]);
5498 emacs_event->kind = NS_TEXT_EVENT;
5499 emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
5500 EV_TRAILER ((id)nil);
5504 /* delete display of composing characters [not in <NSTextInput>] */
5505 - (void)deleteWorkingText
5507 if (workingText == nil)
5510 NSLog(@"deleteWorkingText len =%lu\n", (unsigned long)[workingText length]);
5511 [workingText release];
5513 processingCompose = NO;
5518 emacs_event->kind = NS_TEXT_EVENT;
5519 emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
5520 EV_TRAILER ((id)nil);
5524 - (BOOL)hasMarkedText
5526 return workingText != nil;
5530 - (NSRange)markedRange
5532 NSRange rng = workingText != nil
5533 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
5535 NSLog (@"markedRange request");
5543 NSLog (@"unmark (accept) text");
5544 [self deleteWorkingText];
5545 processingCompose = NO;
5549 /* used to position char selection windows, etc. */
5550 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
5554 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
5556 NSLog (@"firstRectForCharRange request");
5558 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
5559 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
5560 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
5561 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
5562 +FRAME_LINE_HEIGHT (emacsframe));
5564 pt = [self convertPoint: pt toView: nil];
5565 pt = [[self window] convertBaseToScreen: pt];
5571 - (NSInteger)conversationIdentifier
5573 return (NSInteger)self;
5577 - (void)doCommandBySelector: (SEL)aSelector
5580 NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
5582 processingCompose = NO;
5583 if (aSelector == @selector (deleteBackward:))
5585 /* happens when user backspaces over an ongoing composition:
5586 throw a 'delete' into the event queue */
5589 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5590 emacs_event->code = 0xFF08;
5591 EV_TRAILER ((id)nil);
5595 - (NSArray *)validAttributesForMarkedText
5597 static NSArray *arr = nil;
5598 if (arr == nil) arr = [NSArray new];
5599 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
5603 - (NSRange)selectedRange
5606 NSLog (@"selectedRange request");
5607 return NSMakeRange (NSNotFound, 0);
5610 #if defined (NS_IMPL_COCOA) || GNUSTEP_GUI_MAJOR_VERSION > 0 || \
5611 GNUSTEP_GUI_MINOR_VERSION > 22
5612 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
5614 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
5618 NSLog (@"characterIndexForPoint request");
5622 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
5624 static NSAttributedString *str = nil;
5625 if (str == nil) str = [NSAttributedString new];
5627 NSLog (@"attributedSubstringFromRange request");
5631 /* End <NSTextInput> impl. */
5632 /*****************************************************************************/
5635 /* This is what happens when the user presses a mouse button. */
5636 - (void)mouseDown: (NSEvent *)theEvent
5638 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
5639 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5641 NSTRACE (mouseDown);
5643 [self deleteWorkingText];
5648 dpyinfo->last_mouse_frame = emacsframe;
5649 /* appears to be needed to prevent spurious movement events generated on
5651 emacsframe->mouse_moved = 0;
5653 if ([theEvent type] == NSScrollWheel)
5655 CGFloat delta = [theEvent deltaY];
5656 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
5659 delta = [theEvent deltaX];
5662 NSTRACE (deltaIsZero);
5665 emacs_event->kind = HORIZ_WHEEL_EVENT;
5668 emacs_event->kind = WHEEL_EVENT;
5670 emacs_event->code = 0;
5671 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
5672 ((delta > 0) ? up_modifier : down_modifier);
5676 emacs_event->kind = MOUSE_CLICK_EVENT;
5677 emacs_event->code = EV_BUTTON (theEvent);
5678 emacs_event->modifiers = EV_MODIFIERS (theEvent)
5679 | EV_UDMODIFIERS (theEvent);
5681 XSETINT (emacs_event->x, lrint (p.x));
5682 XSETINT (emacs_event->y, lrint (p.y));
5683 EV_TRAILER (theEvent);
5687 - (void)rightMouseDown: (NSEvent *)theEvent
5689 NSTRACE (rightMouseDown);
5690 [self mouseDown: theEvent];
5694 - (void)otherMouseDown: (NSEvent *)theEvent
5696 NSTRACE (otherMouseDown);
5697 [self mouseDown: theEvent];
5701 - (void)mouseUp: (NSEvent *)theEvent
5704 [self mouseDown: theEvent];
5708 - (void)rightMouseUp: (NSEvent *)theEvent
5710 NSTRACE (rightMouseUp);
5711 [self mouseDown: theEvent];
5715 - (void)otherMouseUp: (NSEvent *)theEvent
5717 NSTRACE (otherMouseUp);
5718 [self mouseDown: theEvent];
5722 - (void) scrollWheel: (NSEvent *)theEvent
5724 NSTRACE (scrollWheel);
5725 [self mouseDown: theEvent];
5729 /* Tell emacs the mouse has moved. */
5730 - (void)mouseMoved: (NSEvent *)e
5732 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5733 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
5737 // NSTRACE (mouseMoved);
5739 dpyinfo->last_mouse_movement_time = EV_TIMESTAMP (e);
5740 pt = [self convertPoint: [e locationInWindow] fromView: nil];
5741 dpyinfo->last_mouse_motion_x = pt.x;
5742 dpyinfo->last_mouse_motion_y = pt.y;
5744 /* update any mouse face */
5745 if (hlinfo->mouse_face_hidden)
5747 hlinfo->mouse_face_hidden = 0;
5748 clear_mouse_face (hlinfo);
5751 /* tooltip handling */
5752 previous_help_echo_string = help_echo_string;
5753 help_echo_string = Qnil;
5755 if (!NILP (Vmouse_autoselect_window))
5757 NSTRACE (mouse_autoselect_window);
5758 static Lisp_Object last_mouse_window;
5760 = window_from_coordinates (emacsframe, pt.x, pt.y, 0, 0);
5762 if (WINDOWP (window)
5763 && !EQ (window, last_mouse_window)
5764 && !EQ (window, selected_window)
5765 && (focus_follows_mouse
5766 || (EQ (XWINDOW (window)->frame,
5767 XWINDOW (selected_window)->frame))))
5769 NSTRACE (in_window);
5770 emacs_event->kind = SELECT_WINDOW_EVENT;
5771 emacs_event->frame_or_window = window;
5774 /* Remember the last window where we saw the mouse. */
5775 last_mouse_window = window;
5778 if (!note_mouse_movement (emacsframe, pt.x, pt.y))
5779 help_echo_string = previous_help_echo_string;
5781 XSETFRAME (frame, emacsframe);
5782 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
5784 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
5785 (note_mouse_highlight), which is called through the
5786 note_mouse_movement () call above */
5787 any_help_event_p = YES;
5788 gen_help_event (help_echo_string, frame, help_echo_window,
5789 help_echo_object, help_echo_pos);
5792 if (emacsframe->mouse_moved && send_appdefined)
5793 ns_send_appdefined (-1);
5797 - (void)mouseDragged: (NSEvent *)e
5799 NSTRACE (mouseDragged);
5800 [self mouseMoved: e];
5804 - (void)rightMouseDragged: (NSEvent *)e
5806 NSTRACE (rightMouseDragged);
5807 [self mouseMoved: e];
5811 - (void)otherMouseDragged: (NSEvent *)e
5813 NSTRACE (otherMouseDragged);
5814 [self mouseMoved: e];
5818 - (BOOL)windowShouldClose: (id)sender
5820 NSEvent *e =[[self window] currentEvent];
5822 NSTRACE (windowShouldClose);
5823 windowClosing = YES;
5826 emacs_event->kind = DELETE_WINDOW_EVENT;
5827 emacs_event->modifiers = 0;
5828 emacs_event->code = 0;
5830 /* Don't close this window, let this be done from lisp code. */
5834 - (void) updateFrameSize: (BOOL) delay;
5836 NSWindow *window = [self window];
5837 NSRect wr = [window frame];
5839 int oldc = cols, oldr = rows;
5840 int oldw = FRAME_PIXEL_WIDTH (emacsframe);
5841 int oldh = FRAME_PIXEL_HEIGHT (emacsframe);
5844 NSTRACE (updateFrameSize);
5845 NSTRACE_SIZE ("Original size", NSMakeSize (oldw, oldh));
5847 if (! [self isFullscreen])
5849 #ifdef NS_IMPL_GNUSTEP
5850 // GNUstep does not always update the tool bar height. Force it.
5851 if (toolbar && [toolbar isVisible])
5852 update_frame_tool_bar (emacsframe);
5855 extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5856 + FRAME_TOOLBAR_HEIGHT (emacsframe);
5859 if (wait_for_tool_bar)
5861 if (FRAME_TOOLBAR_HEIGHT (emacsframe) == 0)
5863 wait_for_tool_bar = NO;
5866 neww = (int)wr.size.width - emacsframe->border_width;
5867 newh = (int)wr.size.height - extra;
5869 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, neww);
5870 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, newh);
5872 if (cols < MINWIDTH)
5875 if (rows < MINHEIGHT)
5878 if (oldr != rows || oldc != cols || neww != oldw || newh != oldh)
5880 NSView *view = FRAME_NS_VIEW (emacsframe);
5881 NSWindow *win = [view window];
5882 NSSize sz = [win resizeIncrements];
5884 change_frame_size (emacsframe,
5885 FRAME_PIXEL_TO_TEXT_WIDTH (emacsframe, neww),
5886 FRAME_PIXEL_TO_TEXT_HEIGHT (emacsframe, newh),
5888 SET_FRAME_GARBAGED (emacsframe);
5889 cancel_mouse_face (emacsframe);
5891 // Did resize increments change because of a font change?
5892 if (sz.width != FRAME_COLUMN_WIDTH (emacsframe) ||
5893 sz.height != FRAME_LINE_HEIGHT (emacsframe) ||
5894 (frame_resize_pixelwise && sz.width != 1))
5896 sz.width = frame_resize_pixelwise
5897 ? 1 : FRAME_COLUMN_WIDTH (emacsframe);
5898 sz.height = frame_resize_pixelwise
5899 ? 1 : FRAME_LINE_HEIGHT (emacsframe);
5900 [win setResizeIncrements: sz];
5902 NSTRACE_SIZE ("New size", NSMakeSize (neww, newh));
5905 [view setFrame: NSMakeRect (0, 0, neww, newh)];
5906 [self windowDidMove:nil]; // Update top/left.
5910 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
5911 /* normalize frame to gridded text size */
5915 NSTRACE (windowWillResize);
5916 NSTRACE_SIZE ("Original size", frameSize);
5917 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
5919 if (fs_state == FULLSCREEN_MAXIMIZED
5920 && (maximized_width != (int)frameSize.width
5921 || maximized_height != (int)frameSize.height))
5922 [self setFSValue: FULLSCREEN_NONE];
5923 else if (fs_state == FULLSCREEN_WIDTH
5924 && maximized_width != (int)frameSize.width)
5925 [self setFSValue: FULLSCREEN_NONE];
5926 else if (fs_state == FULLSCREEN_HEIGHT
5927 && maximized_height != (int)frameSize.height)
5928 [self setFSValue: FULLSCREEN_NONE];
5929 if (fs_state == FULLSCREEN_NONE)
5930 maximized_width = maximized_height = -1;
5932 if (! [self isFullscreen])
5934 extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5935 + FRAME_TOOLBAR_HEIGHT (emacsframe);
5938 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, frameSize.width);
5939 if (cols < MINWIDTH)
5942 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe,
5943 frameSize.height - extra);
5944 if (rows < MINHEIGHT)
5946 #ifdef NS_IMPL_COCOA
5948 /* this sets window title to have size in it; the wm does this under GS */
5949 NSRect r = [[self window] frame];
5950 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
5958 else if (fs_state == FULLSCREEN_NONE && ! maximizing_resize)
5961 NSWindow *window = [self window];
5964 char *t = strdup ([[[self window] title] UTF8String]);
5965 char *pos = strstr (t, " — ");
5970 size_title = xmalloc (strlen (old_title) + 40);
5971 esprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
5972 [window setTitle: [NSString stringWithUTF8String: size_title]];
5977 #endif /* NS_IMPL_COCOA */
5978 /*fprintf (stderr," ...size became %.0f x %.0f (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
5984 - (void)windowDidResize: (NSNotification *)notification
5986 if (! [self fsIsNative])
5988 NSWindow *theWindow = [notification object];
5989 /* We can get notification on the non-FS window when in
5991 if ([self window] != theWindow) return;
5994 #ifdef NS_IMPL_GNUSTEP
5995 NSWindow *theWindow = [notification object];
5997 /* In GNUstep, at least currently, it's possible to get a didResize
5998 without getting a willResize.. therefore we need to act as if we got
5999 the willResize now */
6000 NSSize sz = [theWindow frame].size;
6001 sz = [self windowWillResize: theWindow toSize: sz];
6002 #endif /* NS_IMPL_GNUSTEP */
6004 NSTRACE (windowDidResize);
6005 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
6007 if (cols > 0 && rows > 0)
6009 [self updateFrameSize: YES];
6012 ns_send_appdefined (-1);
6015 #ifdef NS_IMPL_COCOA
6016 - (void)viewDidEndLiveResize
6018 [super viewDidEndLiveResize];
6021 [[self window] setTitle: [NSString stringWithUTF8String: old_title]];
6025 maximizing_resize = NO;
6027 #endif /* NS_IMPL_COCOA */
6030 - (void)windowDidBecomeKey: (NSNotification *)notification
6031 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6033 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6034 struct frame *old_focus = dpyinfo->x_focus_frame;
6036 NSTRACE (windowDidBecomeKey);
6038 if (emacsframe != old_focus)
6039 dpyinfo->x_focus_frame = emacsframe;
6041 ns_frame_rehighlight (emacsframe);
6045 emacs_event->kind = FOCUS_IN_EVENT;
6046 EV_TRAILER ((id)nil);
6051 - (void)windowDidResignKey: (NSNotification *)notification
6052 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6054 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6055 BOOL is_focus_frame = dpyinfo->x_focus_frame == emacsframe;
6056 NSTRACE (windowDidResignKey);
6059 dpyinfo->x_focus_frame = 0;
6061 emacsframe->mouse_moved = 0;
6062 ns_frame_rehighlight (emacsframe);
6064 /* FIXME: for some reason needed on second and subsequent clicks away
6065 from sole-frame Emacs to get hollow box to show */
6066 if (!windowClosing && [[self window] isVisible] == YES)
6068 x_update_cursor (emacsframe, 1);
6069 x_set_frame_alpha (emacsframe);
6072 if (any_help_event_p)
6075 XSETFRAME (frame, emacsframe);
6076 help_echo_string = Qnil;
6077 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
6080 if (emacs_event && is_focus_frame)
6082 [self deleteWorkingText];
6083 emacs_event->kind = FOCUS_OUT_EVENT;
6084 EV_TRAILER ((id)nil);
6089 - (void)windowWillMiniaturize: sender
6091 NSTRACE (windowWillMiniaturize);
6107 - initFrameFromEmacs: (struct frame *)f
6116 NSTRACE (initFrameFromEmacs);
6119 processingCompose = NO;
6120 scrollbarsNeedingUpdate = 0;
6121 fs_state = FULLSCREEN_NONE;
6122 fs_before_fs = next_maximized = -1;
6123 #ifdef HAVE_NATIVE_FS
6124 fs_is_native = ns_use_native_fullscreen;
6128 maximized_width = maximized_height = -1;
6131 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
6133 ns_userRect = NSMakeRect (0, 0, 0, 0);
6134 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
6135 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
6136 [self initWithFrame: r];
6137 [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
6139 FRAME_NS_VIEW (f) = self;
6141 #ifdef NS_IMPL_COCOA
6143 maximizing_resize = NO;
6146 win = [[EmacsWindow alloc]
6147 initWithContentRect: r
6148 styleMask: (NSResizableWindowMask |
6149 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6150 NSTitledWindowMask |
6152 NSMiniaturizableWindowMask |
6153 NSClosableWindowMask)
6154 backing: NSBackingStoreBuffered
6157 #ifdef HAVE_NATIVE_FS
6158 [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
6162 bwidth = f->border_width = wr.size.width - r.size.width;
6163 tibar_height = FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
6165 [win setAcceptsMouseMovedEvents: YES];
6166 [win setDelegate: self];
6167 [win useOptimizedDrawing: YES];
6169 sz.width = frame_resize_pixelwise ? 1 : FRAME_COLUMN_WIDTH (f);
6170 sz.height = frame_resize_pixelwise ? 1 : FRAME_LINE_HEIGHT (f);
6171 [win setResizeIncrements: sz];
6173 [[win contentView] addSubview: self];
6176 [self registerForDraggedTypes: ns_drag_types];
6179 name = [NSString stringWithUTF8String:
6180 NILP (tem) ? "Emacs" : SSDATA (tem)];
6181 [win setTitle: name];
6183 /* toolbar support */
6184 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
6185 [NSString stringWithFormat: @"Emacs Frame %d",
6187 [win setToolbar: toolbar];
6188 [toolbar setVisible: NO];
6190 /* Don't set frame garbaged until tool bar is up to date?
6191 This avoids an extra clear and redraw (flicker) at frame creation. */
6192 if (FRAME_EXTERNAL_TOOL_BAR (f)) wait_for_tool_bar = YES;
6193 else wait_for_tool_bar = NO;
6196 #ifdef NS_IMPL_COCOA
6198 NSButton *toggleButton;
6199 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
6200 [toggleButton setTarget: self];
6201 [toggleButton setAction: @selector (toggleToolbar: )];
6204 FRAME_TOOLBAR_HEIGHT (f) = 0;
6208 [win setMiniwindowTitle:
6209 [NSString stringWithUTF8String: SSDATA (tem)]];
6212 NSScreen *screen = [win screen];
6215 [win setFrameTopLeftPoint: NSMakePoint
6216 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
6217 IN_BOUND (-SCREENMAX,
6218 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
6221 [win makeFirstResponder: self];
6223 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6224 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
6225 [win setBackgroundColor: col];
6226 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6227 [win setOpaque: NO];
6229 [self allocateGState];
6231 [NSApp registerServicesMenuSendTypes: ns_send_types
6239 - (void)windowDidMove: sender
6241 NSWindow *win = [self window];
6242 NSRect r = [win frame];
6243 NSArray *screens = [NSScreen screens];
6244 NSScreen *screen = [screens objectAtIndex: 0];
6246 NSTRACE (windowDidMove);
6248 if (!emacsframe->output_data.ns)
6252 emacsframe->left_pos = r.origin.x;
6253 emacsframe->top_pos =
6254 [screen frame].size.height - (r.origin.y + r.size.height);
6259 /* Called AFTER method below, but before our windowWillResize call there leads
6260 to windowDidResize -> x_set_window_size. Update emacs' notion of frame
6261 location so set_window_size moves the frame. */
6262 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
6264 emacsframe->output_data.ns->zooming = 1;
6269 /* Override to do something slightly nonstandard, but nice. First click on
6270 zoom button will zoom vertically. Second will zoom completely. Third
6271 returns to original. */
6272 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
6273 defaultFrame:(NSRect)defaultFrame
6275 NSRect result = [sender frame];
6277 NSTRACE (windowWillUseStandardFrame);
6279 if (fs_before_fs != -1) /* Entering fullscreen */
6281 result = defaultFrame;
6283 else if (next_maximized == FULLSCREEN_HEIGHT
6284 || (next_maximized == -1
6285 && abs (defaultFrame.size.height - result.size.height)
6286 > FRAME_LINE_HEIGHT (emacsframe)))
6289 ns_userRect = result;
6290 maximized_height = result.size.height = defaultFrame.size.height;
6291 maximized_width = -1;
6292 result.origin.y = defaultFrame.origin.y;
6293 [self setFSValue: FULLSCREEN_HEIGHT];
6294 #ifdef NS_IMPL_COCOA
6295 maximizing_resize = YES;
6298 else if (next_maximized == FULLSCREEN_WIDTH)
6300 ns_userRect = result;
6301 maximized_width = result.size.width = defaultFrame.size.width;
6302 maximized_height = -1;
6303 result.origin.x = defaultFrame.origin.x;
6304 [self setFSValue: FULLSCREEN_WIDTH];
6306 else if (next_maximized == FULLSCREEN_MAXIMIZED
6307 || (next_maximized == -1
6308 && abs (defaultFrame.size.width - result.size.width)
6309 > FRAME_COLUMN_WIDTH (emacsframe)))
6311 result = defaultFrame; /* second click */
6312 maximized_width = result.size.width;
6313 maximized_height = result.size.height;
6314 [self setFSValue: FULLSCREEN_MAXIMIZED];
6315 #ifdef NS_IMPL_COCOA
6316 maximizing_resize = YES;
6322 result = ns_userRect.size.height ? ns_userRect : result;
6323 ns_userRect = NSMakeRect (0, 0, 0, 0);
6324 #ifdef NS_IMPL_COCOA
6325 maximizing_resize = fs_state != FULLSCREEN_NONE;
6327 [self setFSValue: FULLSCREEN_NONE];
6328 maximized_width = maximized_height = -1;
6331 if (fs_before_fs == -1) next_maximized = -1;
6332 [self windowWillResize: sender toSize: result.size];
6337 - (void)windowDidDeminiaturize: sender
6339 NSTRACE (windowDidDeminiaturize);
6340 if (!emacsframe->output_data.ns)
6343 SET_FRAME_ICONIFIED (emacsframe, 0);
6344 SET_FRAME_VISIBLE (emacsframe, 1);
6345 windows_or_buffers_changed = 63;
6349 emacs_event->kind = DEICONIFY_EVENT;
6350 EV_TRAILER ((id)nil);
6355 - (void)windowDidExpose: sender
6357 NSTRACE (windowDidExpose);
6358 if (!emacsframe->output_data.ns)
6361 SET_FRAME_VISIBLE (emacsframe, 1);
6362 SET_FRAME_GARBAGED (emacsframe);
6364 if (send_appdefined)
6365 ns_send_appdefined (-1);
6369 - (void)windowDidMiniaturize: sender
6371 NSTRACE (windowDidMiniaturize);
6372 if (!emacsframe->output_data.ns)
6375 SET_FRAME_ICONIFIED (emacsframe, 1);
6376 SET_FRAME_VISIBLE (emacsframe, 0);
6380 emacs_event->kind = ICONIFY_EVENT;
6381 EV_TRAILER ((id)nil);
6385 #ifdef HAVE_NATIVE_FS
6386 - (NSApplicationPresentationOptions)window:(NSWindow *)window
6387 willUseFullScreenPresentationOptions:
6388 (NSApplicationPresentationOptions)proposedOptions
6390 return proposedOptions|NSApplicationPresentationAutoHideToolbar;
6394 - (void)windowWillEnterFullScreen:(NSNotification *)notification
6396 fs_before_fs = fs_state;
6399 - (void)windowDidEnterFullScreen:(NSNotification *)notification
6401 [self setFSValue: FULLSCREEN_BOTH];
6402 if (! [self fsIsNative])
6404 [self windowDidBecomeKey:notification];
6405 [nonfs_window orderOut:self];
6409 BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (emacsframe) ? YES : NO;
6410 #ifdef NS_IMPL_COCOA
6411 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6412 unsigned val = (unsigned)[NSApp presentationOptions];
6414 // OSX 10.7 bug fix, the menu won't appear without this.
6415 // val is non-zero on other OSX versions.
6418 NSApplicationPresentationOptions options
6419 = NSApplicationPresentationAutoHideDock
6420 | NSApplicationPresentationAutoHideMenuBar
6421 | NSApplicationPresentationFullScreen
6422 | NSApplicationPresentationAutoHideToolbar;
6424 [NSApp setPresentationOptions: options];
6428 [toolbar setVisible:tbar_visible];
6432 - (void)windowWillExitFullScreen:(NSNotification *)notification
6434 if (next_maximized != -1)
6435 fs_before_fs = next_maximized;
6438 - (void)windowDidExitFullScreen:(NSNotification *)notification
6440 [self setFSValue: fs_before_fs];
6442 #ifdef HAVE_NATIVE_FS
6443 [self updateCollectionBehavior];
6445 if (FRAME_EXTERNAL_TOOL_BAR (emacsframe))
6447 [toolbar setVisible:YES];
6448 update_frame_tool_bar (emacsframe);
6449 [self updateFrameSize:YES];
6450 [[self window] display];
6453 [toolbar setVisible:NO];
6455 if (next_maximized != -1)
6456 [[self window] performZoom:self];
6461 return fs_is_native;
6464 - (BOOL)isFullscreen
6466 if (! fs_is_native) return nonfs_window != nil;
6467 #ifdef HAVE_NATIVE_FS
6468 return ([[self window] styleMask] & NSFullScreenWindowMask) != 0;
6474 #ifdef HAVE_NATIVE_FS
6475 - (void)updateCollectionBehavior
6477 if (! [self isFullscreen])
6479 NSWindow *win = [self window];
6480 NSWindowCollectionBehavior b = [win collectionBehavior];
6481 if (ns_use_native_fullscreen)
6482 b |= NSWindowCollectionBehaviorFullScreenPrimary;
6484 b &= ~NSWindowCollectionBehaviorFullScreenPrimary;
6486 [win setCollectionBehavior: b];
6487 fs_is_native = ns_use_native_fullscreen;
6492 - (void)toggleFullScreen: (id)sender
6503 #ifdef HAVE_NATIVE_FS
6504 [[self window] toggleFullScreen:sender];
6510 onFirstScreen = [[w screen] isEqual:[[NSScreen screens] objectAtIndex:0]];
6513 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6514 (FRAME_DEFAULT_FACE (f)),
6517 sz.width = frame_resize_pixelwise ? 1 : FRAME_COLUMN_WIDTH (f);
6518 sz.height = frame_resize_pixelwise ? 1 : FRAME_LINE_HEIGHT (f);
6520 if (fs_state != FULLSCREEN_BOTH)
6522 NSScreen *screen = [w screen];
6524 #if defined (NS_IMPL_COCOA) && \
6525 MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
6526 /* Hide ghost menu bar on secondary monitor? */
6527 if (! onFirstScreen)
6528 onFirstScreen = [NSScreen screensHaveSeparateSpaces];
6530 /* Hide dock and menubar if we are on the primary screen. */
6533 #ifdef NS_IMPL_COCOA
6534 NSApplicationPresentationOptions options
6535 = NSApplicationPresentationAutoHideDock
6536 | NSApplicationPresentationAutoHideMenuBar;
6538 [NSApp setPresentationOptions: options];
6540 [NSMenu setMenuBarVisible:NO];
6544 fw = [[EmacsFSWindow alloc]
6545 initWithContentRect:[w contentRectForFrameRect:wr]
6546 styleMask:NSBorderlessWindowMask
6547 backing:NSBackingStoreBuffered
6551 [fw setContentView:[w contentView]];
6552 [fw setTitle:[w title]];
6553 [fw setDelegate:self];
6554 [fw setAcceptsMouseMovedEvents: YES];
6555 [fw useOptimizedDrawing: YES];
6556 [fw setResizeIncrements: sz];
6557 [fw setBackgroundColor: col];
6558 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6561 f->border_width = 0;
6562 FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
6563 tobar_height = FRAME_TOOLBAR_HEIGHT (f);
6564 FRAME_TOOLBAR_HEIGHT (f) = 0;
6568 [self windowWillEnterFullScreen:nil];
6569 [fw makeKeyAndOrderFront:NSApp];
6570 [fw makeFirstResponder:self];
6572 r = [fw frameRectForContentRect:[screen frame]];
6573 [fw setFrame: r display:YES animate:ns_use_fullscreen_animation];
6574 [self windowDidEnterFullScreen:nil];
6585 #ifdef NS_IMPL_COCOA
6586 [NSApp setPresentationOptions: NSApplicationPresentationDefault];
6588 [NSMenu setMenuBarVisible:YES];
6592 [w setContentView:[fw contentView]];
6593 [w setResizeIncrements: sz];
6594 [w setBackgroundColor: col];
6595 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6598 f->border_width = bwidth;
6599 FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
6600 if (FRAME_EXTERNAL_TOOL_BAR (f))
6601 FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
6603 [self windowWillExitFullScreen:nil];
6604 [fw setFrame: [w frame] display:YES animate:ns_use_fullscreen_animation];
6606 [w makeKeyAndOrderFront:NSApp];
6607 [self windowDidExitFullScreen:nil];
6608 [self updateFrameSize:YES];
6614 if (fs_state != emacsframe->want_fullscreen)
6616 if (fs_state == FULLSCREEN_BOTH)
6618 [self toggleFullScreen:self];
6621 switch (emacsframe->want_fullscreen)
6623 case FULLSCREEN_BOTH:
6624 [self toggleFullScreen:self];
6626 case FULLSCREEN_WIDTH:
6627 next_maximized = FULLSCREEN_WIDTH;
6628 if (fs_state != FULLSCREEN_BOTH)
6629 [[self window] performZoom:self];
6631 case FULLSCREEN_HEIGHT:
6632 next_maximized = FULLSCREEN_HEIGHT;
6633 if (fs_state != FULLSCREEN_BOTH)
6634 [[self window] performZoom:self];
6636 case FULLSCREEN_MAXIMIZED:
6637 next_maximized = FULLSCREEN_MAXIMIZED;
6638 if (fs_state != FULLSCREEN_BOTH)
6639 [[self window] performZoom:self];
6641 case FULLSCREEN_NONE:
6642 if (fs_state != FULLSCREEN_BOTH)
6644 next_maximized = FULLSCREEN_NONE;
6645 [[self window] performZoom:self];
6650 emacsframe->want_fullscreen = FULLSCREEN_NONE;
6655 - (void) setFSValue: (int)value
6657 Lisp_Object lval = Qnil;
6660 case FULLSCREEN_BOTH:
6663 case FULLSCREEN_WIDTH:
6666 case FULLSCREEN_HEIGHT:
6669 case FULLSCREEN_MAXIMIZED:
6673 store_frame_param (emacsframe, Qfullscreen, lval);
6677 - (void)mouseEntered: (NSEvent *)theEvent
6679 NSTRACE (mouseEntered);
6681 FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
6682 = EV_TIMESTAMP (theEvent);
6686 - (void)mouseExited: (NSEvent *)theEvent
6688 Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
6690 NSTRACE (mouseExited);
6695 FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
6696 = EV_TIMESTAMP (theEvent);
6698 if (emacsframe == hlinfo->mouse_face_mouse_frame)
6700 clear_mouse_face (hlinfo);
6701 hlinfo->mouse_face_mouse_frame = 0;
6709 if (context_menu_value == -1)
6710 context_menu_value = [sender tag];
6713 NSInteger tag = [sender tag];
6714 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
6715 emacsframe->menu_bar_vector,
6719 ns_send_appdefined (-1);
6724 - (EmacsToolbar *)toolbar
6730 /* this gets called on toolbar button click */
6731 - toolbarClicked: (id)item
6734 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
6736 NSTRACE (toolbarClicked);
6741 /* send first event (for some reason two needed) */
6742 theEvent = [[self window] currentEvent];
6743 emacs_event->kind = TOOL_BAR_EVENT;
6744 XSETFRAME (emacs_event->arg, emacsframe);
6745 EV_TRAILER (theEvent);
6747 emacs_event->kind = TOOL_BAR_EVENT;
6748 /* XSETINT (emacs_event->code, 0); */
6749 emacs_event->arg = AREF (emacsframe->tool_bar_items,
6750 idx + TOOL_BAR_ITEM_KEY);
6751 emacs_event->modifiers = EV_MODIFIERS (theEvent);
6752 EV_TRAILER (theEvent);
6757 - toggleToolbar: (id)sender
6762 emacs_event->kind = NS_NONKEY_EVENT;
6763 emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
6764 EV_TRAILER ((id)nil);
6769 - (void)drawRect: (NSRect)rect
6771 int x = NSMinX (rect), y = NSMinY (rect);
6772 int width = NSWidth (rect), height = NSHeight (rect);
6776 if (!emacsframe || !emacsframe->output_data.ns)
6779 ns_clear_frame_area (emacsframe, x, y, width, height);
6780 expose_frame (emacsframe, x, y, width, height);
6783 drawRect: may be called (at least in OS X 10.5) for invisible
6784 views as well for some reason. Thus, do not infer visibility
6787 emacsframe->async_visible = 1;
6788 emacsframe->async_iconified = 0;
6793 /* NSDraggingDestination protocol methods. Actually this is not really a
6794 protocol, but a category of Object. O well... */
6796 -(NSUInteger) draggingEntered: (id <NSDraggingInfo>) sender
6798 NSTRACE (draggingEntered);
6799 return NSDragOperationGeneric;
6803 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
6809 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
6814 NSEvent *theEvent = [[self window] currentEvent];
6816 NSDragOperation op = [sender draggingSourceOperationMask];
6819 NSTRACE (performDragOperation);
6824 position = [self convertPoint: [sender draggingLocation] fromView: nil];
6825 x = lrint (position.x); y = lrint (position.y);
6827 pb = [sender draggingPasteboard];
6828 type = [pb availableTypeFromArray: ns_drag_types];
6830 if (! (op & (NSDragOperationMove|NSDragOperationDelete)) &&
6831 // URL drags contain all operations (0xf), don't allow all to be set.
6834 if (op & NSDragOperationLink)
6835 modifiers |= NSControlKeyMask;
6836 if (op & NSDragOperationCopy)
6837 modifiers |= NSAlternateKeyMask;
6838 if (op & NSDragOperationGeneric)
6839 modifiers |= NSCommandKeyMask;
6842 modifiers = EV_MODIFIERS2 (modifiers);
6847 else if ([type isEqualToString: NSFilenamesPboardType])
6850 NSEnumerator *fenum;
6853 if (!(files = [pb propertyListForType: type]))
6856 fenum = [files objectEnumerator];
6857 while ( (file = [fenum nextObject]) )
6859 emacs_event->kind = DRAG_N_DROP_EVENT;
6860 XSETINT (emacs_event->x, x);
6861 XSETINT (emacs_event->y, y);
6862 ns_input_file = append2 (ns_input_file,
6863 build_string ([file UTF8String]));
6864 emacs_event->modifiers = modifiers;
6865 emacs_event->arg = list2 (Qfile, build_string ([file UTF8String]));
6866 EV_TRAILER (theEvent);
6870 else if ([type isEqualToString: NSURLPboardType])
6872 NSURL *url = [NSURL URLFromPasteboard: pb];
6873 if (url == nil) return NO;
6875 emacs_event->kind = DRAG_N_DROP_EVENT;
6876 XSETINT (emacs_event->x, x);
6877 XSETINT (emacs_event->y, y);
6878 emacs_event->modifiers = modifiers;
6879 emacs_event->arg = list2 (Qurl,
6880 build_string ([[url absoluteString]
6882 EV_TRAILER (theEvent);
6884 if ([url isFileURL] != NO)
6886 NSString *file = [url path];
6887 ns_input_file = append2 (ns_input_file,
6888 build_string ([file UTF8String]));
6892 else if ([type isEqualToString: NSStringPboardType]
6893 || [type isEqualToString: NSTabularTextPboardType])
6897 if (! (data = [pb stringForType: type]))
6900 emacs_event->kind = DRAG_N_DROP_EVENT;
6901 XSETINT (emacs_event->x, x);
6902 XSETINT (emacs_event->y, y);
6903 emacs_event->modifiers = modifiers;
6904 emacs_event->arg = list2 (Qnil, build_string ([data UTF8String]));
6905 EV_TRAILER (theEvent);
6910 fprintf (stderr, "Invalid data type in dragging pasteboard");
6916 - (id) validRequestorForSendType: (NSString *)typeSent
6917 returnType: (NSString *)typeReturned
6919 NSTRACE (validRequestorForSendType);
6920 if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
6921 && typeReturned == nil)
6923 if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
6927 return [super validRequestorForSendType: typeSent
6928 returnType: typeReturned];
6932 /* The next two methods are part of NSServicesRequests informal protocol,
6933 supposedly called when a services menu item is chosen from this app.
6934 But this should not happen because we override the services menu with our
6935 own entries which call ns-perform-service.
6936 Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
6937 So let's at least stub them out until further investigation can be done. */
6939 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
6941 /* we could call ns_string_from_pasteboard(pboard) here but then it should
6942 be written into the buffer in place of the existing selection..
6943 ordinary service calls go through functions defined in ns-win.el */
6947 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
6949 NSArray *typesDeclared;
6952 /* We only support NSStringPboardType */
6953 if ([types containsObject:NSStringPboardType] == NO) {
6957 val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
6958 if (CONSP (val) && SYMBOLP (XCAR (val)))
6961 if (CONSP (val) && NILP (XCDR (val)))
6964 if (! STRINGP (val))
6967 typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
6968 [pb declareTypes:typesDeclared owner:nil];
6969 ns_string_to_pasteboard (pb, val);
6974 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
6975 (gives a miniaturized version of the window); currently we use the latter for
6976 frames whose active buffer doesn't correspond to any file
6977 (e.g., '*scratch*') */
6978 - setMiniwindowImage: (BOOL) setMini
6980 id image = [[self window] miniwindowImage];
6981 NSTRACE (setMiniwindowImage);
6983 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
6984 about "AppleDockIconEnabled" notwithstanding, however the set message
6985 below has its effect nonetheless. */
6986 if (image != emacsframe->output_data.ns->miniimage)
6988 if (image && [image isKindOfClass: [EmacsImage class]])
6990 [[self window] setMiniwindowImage:
6991 setMini ? emacsframe->output_data.ns->miniimage : nil];
6998 - (void) setRows: (int) r andColumns: (int) c
7004 @end /* EmacsView */
7008 /* ==========================================================================
7010 EmacsWindow implementation
7012 ========================================================================== */
7014 @implementation EmacsWindow
7016 #ifdef NS_IMPL_COCOA
7017 - (id)accessibilityAttributeValue:(NSString *)attribute
7019 Lisp_Object str = Qnil;
7020 struct frame *f = SELECTED_FRAME ();
7021 struct buffer *curbuf = XBUFFER (XWINDOW (f->selected_window)->contents);
7023 if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
7024 return NSAccessibilityTextFieldRole;
7026 if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]
7027 && curbuf && ! NILP (BVAR (curbuf, mark_active)))
7029 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7031 else if (curbuf && [attribute isEqualToString:NSAccessibilityValueAttribute])
7033 if (! NILP (BVAR (curbuf, mark_active)))
7034 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7038 ptrdiff_t start_byte = BUF_BEGV_BYTE (curbuf);
7039 ptrdiff_t byte_range = BUF_ZV_BYTE (curbuf) - start_byte;
7040 ptrdiff_t range = BUF_ZV (curbuf) - BUF_BEGV (curbuf);
7042 if (! NILP (BVAR (curbuf, enable_multibyte_characters)))
7043 str = make_uninit_multibyte_string (range, byte_range);
7045 str = make_uninit_string (range);
7046 /* To check: This returns emacs-utf-8, which is a superset of utf-8.
7047 Is this a problem? */
7048 memcpy (SDATA (str), BYTE_POS_ADDR (start_byte), byte_range);
7055 if (CONSP (str) && SYMBOLP (XCAR (str)))
7058 if (CONSP (str) && NILP (XCDR (str)))
7063 const char *utfStr = SSDATA (str);
7064 NSString *nsStr = [NSString stringWithUTF8String: utfStr];
7069 return [super accessibilityAttributeValue:attribute];
7071 #endif /* NS_IMPL_COCOA */
7073 /* If we have multiple monitors, one above the other, we don't want to
7074 restrict the height to just one monitor. So we override this. */
7075 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
7077 /* When making the frame visible for the first time or if there is just
7078 one screen, we want to constrain. Other times not. */
7079 NSArray *screens = [NSScreen screens];
7080 NSUInteger nr_screens = [screens count], nr_eff_screens = 0, i;
7081 struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
7082 NSTRACE (constrainFrameRect);
7083 NSTRACE_RECT ("input", frameRect);
7085 if (ns_menu_bar_should_be_hidden ())
7088 if (nr_screens == 1)
7089 return [super constrainFrameRect:frameRect toScreen:screen];
7091 #ifdef NS_IMPL_COCOA
7092 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7093 // If separate spaces is on, it is like each screen is independent. There is
7094 // no spanning of frames across screens.
7095 if ([NSScreen screensHaveSeparateSpaces])
7096 return [super constrainFrameRect:frameRect toScreen:screen];
7100 for (i = 0; i < nr_screens; ++i)
7102 NSScreen *s = [screens objectAtIndex: i];
7103 NSRect scrrect = [s frame];
7104 NSRect intersect = NSIntersectionRect (frameRect, scrrect);
7106 if (intersect.size.width > 0 || intersect.size.height > 0)
7110 if (nr_eff_screens == 1)
7111 return [super constrainFrameRect:frameRect toScreen:screen];
7113 /* The default implementation does two things 1) ensure that the top
7114 of the rectangle is below the menu bar (or below the top of the
7115 screen) and 2) resizes windows larger than the screen. As we
7116 don't want the latter, a smaller rectangle is used. */
7117 #define FAKE_HEIGHT 64
7118 float old_top = frameRect.origin.y + frameRect.size.height;
7120 r.size.height = FAKE_HEIGHT;
7121 r.size.width = frameRect.size.width;
7122 r.origin.x = frameRect.origin.x;
7123 r.origin.y = old_top - FAKE_HEIGHT;
7125 NSTRACE_RECT ("input to super", r);
7127 r = [super constrainFrameRect:r toScreen:screen];
7129 NSTRACE_RECT ("output from super", r);
7131 float new_top = r.origin.y + FAKE_HEIGHT;
7132 if (new_top < old_top)
7134 frameRect.origin.y = new_top - frameRect.size.height;
7137 NSTRACE_RECT ("output", frameRect);
7143 @end /* EmacsWindow */
7146 @implementation EmacsFSWindow
7148 - (BOOL)canBecomeKeyWindow
7153 - (BOOL)canBecomeMainWindow
7160 /* ==========================================================================
7162 EmacsScroller implementation
7164 ========================================================================== */
7167 @implementation EmacsScroller
7169 /* for repeat button push */
7170 #define SCROLL_BAR_FIRST_DELAY 0.5
7171 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
7173 + (CGFloat) scrollerWidth
7175 /* TODO: if we want to allow variable widths, this is the place to do it,
7176 however neither GNUstep nor Cocoa support it very well */
7177 return [NSScroller scrollerWidth];
7181 - initFrame: (NSRect )r window: (Lisp_Object)nwin
7183 NSTRACE (EmacsScroller_initFrame);
7185 r.size.width = [EmacsScroller scrollerWidth];
7186 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
7187 [self setContinuous: YES];
7188 [self setEnabled: YES];
7190 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
7191 locked against the top and bottom edges, and right edge on OS X, where
7192 scrollers are on right. */
7193 #ifdef NS_IMPL_GNUSTEP
7194 [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
7196 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
7199 window = XWINDOW (nwin);
7201 pixel_height = NSHeight (r);
7202 if (pixel_height == 0) pixel_height = 1;
7203 min_portion = 20 / pixel_height;
7205 frame = XFRAME (window->frame);
7206 if (FRAME_LIVE_P (frame))
7209 EmacsView *view = FRAME_NS_VIEW (frame);
7210 NSView *sview = [[view window] contentView];
7211 NSArray *subs = [sview subviews];
7213 /* disable optimization stopping redraw of other scrollbars */
7214 view->scrollbarsNeedingUpdate = 0;
7215 for (i =[subs count]-1; i >= 0; i--)
7216 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
7217 view->scrollbarsNeedingUpdate++;
7218 [sview addSubview: self];
7221 /* [self setFrame: r]; */
7227 - (void)setFrame: (NSRect)newRect
7229 NSTRACE (EmacsScroller_setFrame);
7230 /* block_input (); */
7231 pixel_height = NSHeight (newRect);
7232 if (pixel_height == 0) pixel_height = 1;
7233 min_portion = 20 / pixel_height;
7234 [super setFrame: newRect];
7235 /* unblock_input (); */
7241 NSTRACE (EmacsScroller_dealloc);
7243 wset_vertical_scroll_bar (window, Qnil);
7268 bool ret = condemned;
7273 /* ensure other scrollbar updates after deletion */
7274 view = (EmacsView *)FRAME_NS_VIEW (frame);
7276 view->scrollbarsNeedingUpdate++;
7278 wset_vertical_scroll_bar (window, Qnil);
7280 [self removeFromSuperview];
7288 - (void)resetCursorRects
7290 NSRect visible = [self visibleRect];
7291 NSTRACE (resetCursorRects);
7293 if (!NSIsEmptyRect (visible))
7294 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
7295 [[NSCursor arrowCursor] setOnMouseEntered: YES];
7299 - (int) checkSamePosition: (int) position portion: (int) portion
7302 return em_position ==position && em_portion ==portion && em_whole ==whole
7303 && portion != whole; /* needed for resize empty buf */
7307 - setPosition: (int)position portion: (int)portion whole: (int)whole
7309 NSTRACE (setPosition);
7311 em_position = position;
7312 em_portion = portion;
7315 if (portion >= whole)
7317 #ifdef NS_IMPL_COCOA
7318 [self setKnobProportion: 1.0];
7319 [self setDoubleValue: 1.0];
7321 [self setFloatValue: 0.0 knobProportion: 1.0];
7328 portion = max ((float)whole*min_portion/pixel_height, portion);
7329 pos = (float)position / (whole - portion);
7330 por = (CGFloat)portion/whole;
7331 #ifdef NS_IMPL_COCOA
7332 [self setKnobProportion: por];
7333 [self setDoubleValue: pos];
7335 [self setFloatValue: pos knobProportion: por];
7342 /* set up emacs_event */
7343 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
7349 emacs_event->part = last_hit_part;
7350 emacs_event->code = 0;
7351 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
7352 XSETWINDOW (win, window);
7353 emacs_event->frame_or_window = win;
7354 emacs_event->timestamp = EV_TIMESTAMP (e);
7355 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
7356 emacs_event->arg = Qnil;
7357 XSETINT (emacs_event->x, loc * pixel_height);
7358 XSETINT (emacs_event->y, pixel_height-20);
7362 n_emacs_events_pending++;
7363 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
7366 hold_event (emacs_event);
7367 EVENT_INIT (*emacs_event);
7368 ns_send_appdefined (-1);
7372 /* called manually thru timer to implement repeated button action w/hold-down */
7373 - repeatScroll: (NSTimer *)scrollEntry
7375 NSEvent *e = [[self window] currentEvent];
7376 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
7377 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
7379 /* clear timer if need be */
7380 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
7382 [scroll_repeat_entry invalidate];
7383 [scroll_repeat_entry release];
7384 scroll_repeat_entry = nil;
7390 = [[NSTimer scheduledTimerWithTimeInterval:
7391 SCROLL_BAR_CONTINUOUS_DELAY
7393 selector: @selector (repeatScroll:)
7399 [self sendScrollEventAtLoc: 0 fromEvent: e];
7404 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
7405 mouseDragged events without going into a modal loop. */
7406 - (void)mouseDown: (NSEvent *)e
7409 /* hitPart is only updated AFTER event is passed on */
7410 NSScrollerPart part = [self testPart: [e locationInWindow]];
7411 CGFloat inc = 0.0, loc, kloc, pos;
7414 NSTRACE (EmacsScroller_mouseDown);
7418 case NSScrollerDecrementPage:
7419 last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
7420 case NSScrollerIncrementPage:
7421 last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
7422 case NSScrollerDecrementLine:
7423 last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
7424 case NSScrollerIncrementLine:
7425 last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
7426 case NSScrollerKnob:
7427 last_hit_part = scroll_bar_handle; break;
7428 case NSScrollerKnobSlot: /* GNUstep-only */
7429 last_hit_part = scroll_bar_move_ratio; break;
7430 default: /* NSScrollerNoPart? */
7431 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
7438 pos = 0; /* ignored */
7440 /* set a timer to repeat, as we can't let superclass do this modally */
7442 = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
7444 selector: @selector (repeatScroll:)
7451 /* handle, or on GNUstep possibly slot */
7452 NSEvent *fake_event;
7454 /* compute float loc in slot and mouse offset on knob */
7455 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
7457 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
7463 else if (loc >= NSHeight (sr))
7465 loc = NSHeight (sr);
7473 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
7475 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
7477 last_mouse_offset = kloc;
7479 /* if knob, tell emacs a location offset by knob pos
7480 (to indicate top of handle) */
7481 if (part == NSScrollerKnob)
7482 pos = (loc - last_mouse_offset) / NSHeight (sr);
7484 /* else this is a slot click on GNUstep: go straight there */
7485 pos = loc / NSHeight (sr);
7487 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
7488 fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
7489 location: [e locationInWindow]
7490 modifierFlags: [e modifierFlags]
7491 timestamp: [e timestamp]
7492 windowNumber: [e windowNumber]
7493 context: [e context]
7494 eventNumber: [e eventNumber]
7495 clickCount: [e clickCount]
7496 pressure: [e pressure]];
7497 [super mouseUp: fake_event];
7500 if (part != NSScrollerKnob)
7501 [self sendScrollEventAtLoc: pos fromEvent: e];
7505 /* Called as we manually track scroller drags, rather than superclass. */
7506 - (void)mouseDragged: (NSEvent *)e
7511 NSTRACE (EmacsScroller_mouseDragged);
7513 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
7515 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
7521 else if (loc >= NSHeight (sr) + last_mouse_offset)
7523 loc = NSHeight (sr) + last_mouse_offset;
7526 pos = (loc - last_mouse_offset) / NSHeight (sr);
7527 [self sendScrollEventAtLoc: pos fromEvent: e];
7531 - (void)mouseUp: (NSEvent *)e
7533 if (scroll_repeat_entry)
7535 [scroll_repeat_entry invalidate];
7536 [scroll_repeat_entry release];
7537 scroll_repeat_entry = nil;
7539 last_hit_part = scroll_bar_above_handle;
7543 /* treat scrollwheel events in the bar as though they were in the main window */
7544 - (void) scrollWheel: (NSEvent *)theEvent
7546 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
7547 [view mouseDown: theEvent];
7550 @end /* EmacsScroller */
7553 #ifdef NS_IMPL_GNUSTEP
7554 /* Dummy class to get rid of startup warnings. */
7555 @implementation EmacsDocument
7561 /* ==========================================================================
7563 Font-related functions; these used to be in nsfaces.m
7565 ========================================================================== */
7569 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
7571 struct font *font = XFONT_OBJECT (font_object);
7572 EmacsView *view = FRAME_NS_VIEW (f);
7575 fontset = fontset_from_font (font_object);
7576 FRAME_FONTSET (f) = fontset;
7578 if (FRAME_FONT (f) == font)
7579 /* This font is already set in frame F. There's nothing more to
7583 FRAME_FONT (f) = font;
7585 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
7586 FRAME_COLUMN_WIDTH (f) = font->average_width;
7587 FRAME_LINE_HEIGHT (f) = font->height;
7589 /* Compute the scroll bar width in character columns. */
7590 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
7592 int wid = FRAME_COLUMN_WIDTH (f);
7593 FRAME_CONFIG_SCROLL_BAR_COLS (f)
7594 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
7598 int wid = FRAME_COLUMN_WIDTH (f);
7599 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
7602 /* Compute the scroll bar height in character lines. */
7603 if (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) > 0)
7605 int height = FRAME_LINE_HEIGHT (f);
7606 FRAME_CONFIG_SCROLL_BAR_LINES (f)
7607 = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + height - 1) / height;
7611 int height = FRAME_LINE_HEIGHT (f);
7612 FRAME_CONFIG_SCROLL_BAR_LINES (f) = (14 + height - 1) / height;
7615 /* Now make the frame display the given font. */
7616 if (FRAME_NS_WINDOW (f) != 0 && ! [view isFullscreen])
7617 x_set_window_size (f, false, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
7618 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), true);
7624 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
7625 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
7629 ns_xlfd_to_fontname (const char *xlfd)
7630 /* --------------------------------------------------------------------------
7631 Convert an X font name (XLFD) to an NS font name.
7632 Only family is used.
7633 The string returned is temporarily allocated.
7634 -------------------------------------------------------------------------- */
7636 char *name = xmalloc (180);
7640 if (!strncmp (xlfd, "--", 2))
7641 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
7643 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
7645 /* stopgap for malformed XLFD input */
7646 if (strlen (name) == 0)
7647 strcpy (name, "Monaco");
7649 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
7650 also uppercase after '-' or ' ' */
7651 name[0] = c_toupper (name[0]);
7652 for (len =strlen (name), i =0; i<len; i++)
7658 name[i+1] = c_toupper (name[i+1]);
7660 else if (name[i] == '_')
7664 name[i+1] = c_toupper (name[i+1]);
7667 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
7668 ret = [[NSString stringWithUTF8String: name] UTF8String];
7675 syms_of_nsterm (void)
7677 NSTRACE (syms_of_nsterm);
7679 ns_antialias_threshold = 10.0;
7681 /* from 23+ we need to tell emacs what modifiers there are.. */
7682 DEFSYM (Qmodifier_value, "modifier-value");
7683 DEFSYM (Qalt, "alt");
7684 DEFSYM (Qhyper, "hyper");
7685 DEFSYM (Qmeta, "meta");
7686 DEFSYM (Qsuper, "super");
7687 DEFSYM (Qcontrol, "control");
7688 DEFSYM (QUTF8_STRING, "UTF8_STRING");
7690 DEFSYM (Qfile, "file");
7691 DEFSYM (Qurl, "url");
7693 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
7694 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
7695 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
7696 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
7697 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
7699 DEFVAR_LISP ("ns-input-file", ns_input_file,
7700 "The file specified in the last NS event.");
7701 ns_input_file =Qnil;
7703 DEFVAR_LISP ("ns-working-text", ns_working_text,
7704 "String for visualizing working composition sequence.");
7705 ns_working_text =Qnil;
7707 DEFVAR_LISP ("ns-input-font", ns_input_font,
7708 "The font specified in the last NS event.");
7709 ns_input_font =Qnil;
7711 DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
7712 "The fontsize specified in the last NS event.");
7713 ns_input_fontsize =Qnil;
7715 DEFVAR_LISP ("ns-input-line", ns_input_line,
7716 "The line specified in the last NS event.");
7717 ns_input_line =Qnil;
7719 DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
7720 "The service name specified in the last NS event.");
7721 ns_input_spi_name =Qnil;
7723 DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
7724 "The service argument specified in the last NS event.");
7725 ns_input_spi_arg =Qnil;
7727 DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
7728 "This variable describes the behavior of the alternate or option key.\n\
7729 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7730 Set to none means that the alternate / option key is not interpreted by Emacs\n\
7731 at all, allowing it to be used at a lower level for accented character entry.");
7732 ns_alternate_modifier = Qmeta;
7734 DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
7735 "This variable describes the behavior of the right alternate or option key.\n\
7736 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7737 Set to left means be the same key as `ns-alternate-modifier'.\n\
7738 Set to none means that the alternate / option key is not interpreted by Emacs\n\
7739 at all, allowing it to be used at a lower level for accented character entry.");
7740 ns_right_alternate_modifier = Qleft;
7742 DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
7743 "This variable describes the behavior of the command key.\n\
7744 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
7745 ns_command_modifier = Qsuper;
7747 DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
7748 "This variable describes the behavior of the right command key.\n\
7749 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7750 Set to left means be the same key as `ns-command-modifier'.\n\
7751 Set to none means that the command / option key is not interpreted by Emacs\n\
7752 at all, allowing it to be used at a lower level for accented character entry.");
7753 ns_right_command_modifier = Qleft;
7755 DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
7756 "This variable describes the behavior of the control key.\n\
7757 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
7758 ns_control_modifier = Qcontrol;
7760 DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
7761 "This variable describes the behavior of the right control key.\n\
7762 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7763 Set to left means be the same key as `ns-control-modifier'.\n\
7764 Set to none means that the control / option key is not interpreted by Emacs\n\
7765 at all, allowing it to be used at a lower level for accented character entry.");
7766 ns_right_control_modifier = Qleft;
7768 DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
7769 "This variable describes the behavior of the function key (on laptops).\n\
7770 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7771 Set to none means that the function key is not interpreted by Emacs at all,\n\
7772 allowing it to be used at a lower level for accented character entry.");
7773 ns_function_modifier = Qnone;
7775 DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
7776 "Non-nil (the default) means to render text antialiased.");
7777 ns_antialias_text = Qt;
7779 DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
7780 "Whether to confirm application quit using dialog.");
7781 ns_confirm_quit = Qnil;
7783 DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
7784 doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
7785 Only works on OSX 10.6 or later. */);
7786 ns_auto_hide_menu_bar = Qnil;
7788 DEFVAR_BOOL ("ns-use-native-fullscreen", ns_use_native_fullscreen,
7789 doc: /*Non-nil means to use native fullscreen on OSX >= 10.7.
7790 Nil means use fullscreen the old (< 10.7) way. The old way works better with
7791 multiple monitors, but lacks tool bar. This variable is ignored on OSX < 10.7.
7792 Default is t for OSX >= 10.7, nil otherwise. */);
7793 #ifdef HAVE_NATIVE_FS
7794 ns_use_native_fullscreen = YES;
7796 ns_use_native_fullscreen = NO;
7798 ns_last_use_native_fullscreen = ns_use_native_fullscreen;
7800 DEFVAR_BOOL ("ns-use-fullscreen-animation", ns_use_fullscreen_animation,
7801 doc: /*Non-nil means use animation on non-native fullscreen.
7802 For native fullscreen, this does nothing.
7803 Default is nil. */);
7804 ns_use_fullscreen_animation = NO;
7806 DEFVAR_BOOL ("ns-use-srgb-colorspace", ns_use_srgb_colorspace,
7807 doc: /*Non-nil means to use sRGB colorspace on OSX >= 10.7.
7808 Note that this does not apply to images.
7809 This variable is ignored on OSX < 10.7 and GNUstep. */);
7810 ns_use_srgb_colorspace = YES;
7812 /* TODO: move to common code */
7813 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
7814 doc: /* Which toolkit scroll bars Emacs uses, if any.
7815 A value of nil means Emacs doesn't use toolkit scroll bars.
7816 With the X Window system, the value is a symbol describing the
7817 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
7818 With MS Windows or Nextstep, the value is t. */);
7819 Vx_toolkit_scroll_bars = Qt;
7821 DEFVAR_BOOL ("x-use-underline-position-properties",
7822 x_use_underline_position_properties,
7823 doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
7824 A value of nil means ignore them. If you encounter fonts with bogus
7825 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
7826 to 4.1, set this to nil. */);
7827 x_use_underline_position_properties = 0;
7829 DEFVAR_BOOL ("x-underline-at-descent-line",
7830 x_underline_at_descent_line,
7831 doc: /* Non-nil means to draw the underline at the same place as the descent line.
7832 A value of nil means to draw the underline according to the value of the
7833 variable `x-use-underline-position-properties', which is usually at the
7834 baseline level. The default value is nil. */);
7835 x_underline_at_descent_line = 0;
7837 /* Tell Emacs about this window system. */
7838 Fprovide (Qns, Qnil);
7840 DEFSYM (Qcocoa, "cocoa");
7841 DEFSYM (Qgnustep, "gnustep");
7843 #ifdef NS_IMPL_COCOA
7844 Fprovide (Qcocoa, Qnil);
7847 Fprovide (Qgnustep, Qnil);