1 /* NeXT/Open/GNUstep / MacOSX communication module. -*- coding: utf-8 -*-
3 Copyright (C) 1989, 1993-1994, 2005-2006, 2008-2015 Free Software
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 Originally by Carl Edman
23 Updated by Christian Limpach (chris@nice.ch)
24 OpenStep/Rhapsody port by Scott Bender (sbender@harmony-ds.com)
25 MacOSX/Aqua port by Christophe de Dinechin (descubes@earthlink.net)
26 GNUstep port and post-20 update by Adrian Robert (arobert@cogsci.ucsd.edu)
29 /* This should be the first include, as it may set up #defines affecting
30 interpretation of even the system includes. */
36 #include <sys/types.h>
42 #include <c-strcase.h>
46 #include "blockinput.h"
47 #include "sysselect.h"
50 #include "character.h"
52 #include "composite.h"
55 #include "termhooks.h"
63 #ifdef NS_IMPL_GNUSTEP
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 Lisp_Object tem = Vinhibit_quit; \
377 Vinhibit_quit = Qt; \
378 n_emacs_events_pending++; \
379 kbd_buffer_store_event_hold (emacs_event, q_event_ptr); \
380 Vinhibit_quit = tem; \
383 hold_event (emacs_event); \
384 EVENT_INIT (*emacs_event); \
385 ns_send_appdefined (-1); \
388 /* TODO: get rid of need for these forward declarations */
389 static void ns_condemn_scroll_bars (struct frame *f);
390 static void ns_judge_scroll_bars (struct frame *f);
391 void x_set_frame_alpha (struct frame *f);
394 /* ==========================================================================
398 ========================================================================== */
401 ns_set_represented_filename (NSString* fstr, struct frame *f)
403 represented_filename = [fstr retain];
404 represented_frame = f;
408 ns_init_events (struct input_event* ev)
421 hold_event (struct input_event *event)
423 if (hold_event_q.nr == hold_event_q.cap)
425 if (hold_event_q.cap == 0) hold_event_q.cap = 10;
426 else hold_event_q.cap *= 2;
428 xrealloc (hold_event_q.q, hold_event_q.cap * sizeof *hold_event_q.q);
431 hold_event_q.q[hold_event_q.nr++] = *event;
432 /* Make sure ns_read_socket is called, i.e. we have input. */
434 send_appdefined = YES;
438 append2 (Lisp_Object list, Lisp_Object item)
439 /* --------------------------------------------------------------------------
440 Utility to append to a list
441 -------------------------------------------------------------------------- */
443 return CALLN (Fnconc, list, list1 (item));
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;
1333 int orig_height = wr.size.height;
1335 NSTRACE (x_set_window_size);
1340 /*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));*/
1346 pixelwidth = FRAME_TEXT_TO_PIXEL_WIDTH (f, width);
1347 pixelheight = FRAME_TEXT_TO_PIXEL_HEIGHT (f, height);
1348 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, pixelwidth);
1349 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, pixelheight);
1353 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, width);
1354 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, height);
1359 /* If we have a toolbar, take its height into account. */
1360 if (tb && ! [view isFullscreen])
1362 /* NOTE: previously this would generate wrong result if toolbar not
1363 yet displayed and fixing toolbar_height=32 helped, but
1364 now (200903) seems no longer needed */
1365 FRAME_TOOLBAR_HEIGHT (f) =
1366 NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1367 - FRAME_NS_TITLEBAR_HEIGHT (f);
1368 #ifdef NS_IMPL_GNUSTEP
1369 FRAME_TOOLBAR_HEIGHT (f) -= 3;
1373 FRAME_TOOLBAR_HEIGHT (f) = 0;
1375 wr.size.width = pixelwidth + f->border_width;
1376 wr.size.height = pixelheight;
1377 if (! [view isFullscreen])
1378 wr.size.height += FRAME_NS_TITLEBAR_HEIGHT (f)
1379 + FRAME_TOOLBAR_HEIGHT (f);
1381 /* Do not try to constrain to this screen. We may have multiple
1382 screens, and want Emacs to span those. Constraining to screen
1383 prevents that, and that is not nice to the user. */
1384 if (f->output_data.ns->zooming)
1385 f->output_data.ns->zooming = 0;
1387 wr.origin.y += orig_height - wr.size.height;
1389 [view setRows: rows andColumns: cols];
1390 [window setFrame: wr display: YES];
1392 /* This is a trick to compensate for Emacs' managing the scrollbar area
1393 as a fixed number of standard character columns. Instead of leaving
1394 blank space for the extra, we chopped it off above. Now for
1395 left-hand scrollbars, we shift all rendering to the left by the
1396 difference between the real width and Emacs' imagined one. For
1397 right-hand bars, don't worry about it since the extra is never used.
1398 (Obviously doesn't work for vertically split windows tho..) */
1400 NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1401 ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1402 - NS_SCROLL_BAR_WIDTH (f), 0)
1403 : NSMakePoint (0, 0);
1404 [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1405 [view setBoundsOrigin: origin];
1408 [view updateFrameSize: NO];
1414 ns_fullscreen_hook (struct frame *f)
1416 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (f);
1418 if (!FRAME_VISIBLE_P (f))
1421 if (! [view fsIsNative] && f->want_fullscreen == FULLSCREEN_BOTH)
1423 /* Old style fs don't initiate correctly if created from
1424 init/default-frame alist, so use a timer (not nice...).
1426 [NSTimer scheduledTimerWithTimeInterval: 0.5 target: view
1427 selector: @selector (handleFS)
1428 userInfo: nil repeats: NO];
1437 /* ==========================================================================
1441 ========================================================================== */
1445 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1447 struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1448 if (idx < 1 || idx >= color_table->avail)
1450 return color_table->colors[idx];
1455 ns_index_color (NSColor *color, struct frame *f)
1457 struct ns_color_table *color_table = FRAME_DISPLAY_INFO (f)->color_table;
1461 if (!color_table->colors)
1463 color_table->size = NS_COLOR_CAPACITY;
1464 color_table->avail = 1; /* skip idx=0 as marker */
1465 color_table->colors = xmalloc (color_table->size * sizeof (NSColor *));
1466 color_table->colors[0] = nil;
1467 color_table->empty_indices = [[NSMutableSet alloc] init];
1470 /* Do we already have this color? */
1471 for (i = 1; i < color_table->avail; i++)
1472 if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1475 if ([color_table->empty_indices count] > 0)
1477 NSNumber *index = [color_table->empty_indices anyObject];
1478 [color_table->empty_indices removeObject: index];
1479 idx = [index unsignedLongValue];
1483 if (color_table->avail == color_table->size)
1484 color_table->colors =
1485 xpalloc (color_table->colors, &color_table->size, 1,
1486 min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1487 idx = color_table->avail++;
1490 color_table->colors[idx] = color;
1492 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1498 ns_free_indexed_color (unsigned long idx, struct frame *f)
1500 struct ns_color_table *color_table;
1507 color_table = FRAME_DISPLAY_INFO (f)->color_table;
1509 if (idx <= 0 || idx >= color_table->size) {
1510 message1 ("ns_free_indexed_color: Color index out of range.\n");
1514 index = [NSNumber numberWithUnsignedInt: idx];
1515 if ([color_table->empty_indices containsObject: index]) {
1516 message1 ("ns_free_indexed_color: attempt to free already freed color.\n");
1520 color = color_table->colors[idx];
1522 color_table->colors[idx] = nil;
1523 [color_table->empty_indices addObject: index];
1524 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1529 ns_get_color (const char *name, NSColor **col)
1530 /* --------------------------------------------------------------------------
1532 -------------------------------------------------------------------------- */
1533 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1534 X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1535 See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1538 static char hex[20];
1540 float r = -1.0, g, b;
1541 NSString *nsname = [NSString stringWithUTF8String: name];
1543 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1546 if ([nsname isEqualToString: @"ns_selection_bg_color"])
1548 #ifdef NS_IMPL_COCOA
1549 NSString *defname = [[NSUserDefaults standardUserDefaults]
1550 stringForKey: @"AppleHighlightColor"];
1555 if ((new = [NSColor selectedTextBackgroundColor]) != nil)
1557 *col = [new colorUsingDefaultColorSpace];
1562 nsname = NS_SELECTION_BG_COLOR_DEFAULT;
1564 name = [nsname UTF8String];
1566 else if ([nsname isEqualToString: @"ns_selection_fg_color"])
1568 /* NOTE: OSX applications normally don't set foreground selection, but
1569 text may be unreadable if we don't.
1571 if ((new = [NSColor selectedTextColor]) != nil)
1573 *col = [new colorUsingDefaultColorSpace];
1578 nsname = NS_SELECTION_FG_COLOR_DEFAULT;
1579 name = [nsname UTF8String];
1582 /* First, check for some sort of numeric specification. */
1585 if (name[0] == '0' || name[0] == '1' || name[0] == '.') /* RGB decimal */
1587 NSScanner *scanner = [NSScanner scannerWithString: nsname];
1588 [scanner scanFloat: &r];
1589 [scanner scanFloat: &g];
1590 [scanner scanFloat: &b];
1592 else if (!strncmp(name, "rgb:", 4)) /* A newer X11 format -- rgb:r/g/b */
1593 scaling = (snprintf (hex, sizeof hex, "%s", name + 4) - 2) / 3;
1594 else if (name[0] == '#') /* An old X11 format; convert to newer */
1596 int len = (strlen(name) - 1);
1597 int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1599 scaling = strlen(name+start) / 3;
1600 for (i = 0; i < 3; i++)
1601 sprintf (hex + i * (scaling + 1), "%.*s/", scaling,
1602 name + start + i * scaling);
1603 hex[3 * (scaling + 1) - 1] = '\0';
1609 float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1610 if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1620 *col = [NSColor colorForEmacsRed: r green: g blue: b alpha: 1.0];
1625 /* Otherwise, color is expected to be from a list */
1627 NSEnumerator *lenum, *cenum;
1631 #ifdef NS_IMPL_GNUSTEP
1632 /* XXX: who is wrong, the requestor or the implementation? */
1633 if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1635 nsname = @"highlightColor";
1638 lenum = [[NSColorList availableColorLists] objectEnumerator];
1639 while ( (clist = [lenum nextObject]) && new == nil)
1641 cenum = [[clist allKeys] objectEnumerator];
1642 while ( (name = [cenum nextObject]) && new == nil )
1644 if ([name compare: nsname
1645 options: NSCaseInsensitiveSearch] == NSOrderedSame )
1646 new = [clist colorWithKey: name];
1652 *col = [new colorUsingDefaultColorSpace];
1659 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1660 /* --------------------------------------------------------------------------
1661 Convert a Lisp string object to a NS color
1662 -------------------------------------------------------------------------- */
1664 NSTRACE (ns_lisp_to_color);
1665 if (STRINGP (color))
1666 return ns_get_color (SSDATA (color), col);
1667 else if (SYMBOLP (color))
1668 return ns_get_color (SSDATA (SYMBOL_NAME (color)), col);
1674 ns_color_to_lisp (NSColor *col)
1675 /* --------------------------------------------------------------------------
1676 Convert a color to a lisp string with the RGB equivalent
1677 -------------------------------------------------------------------------- */
1679 EmacsCGFloat red, green, blue, alpha, gray;
1682 NSTRACE (ns_color_to_lisp);
1685 if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1687 if ((str =[[col colorNameComponent] UTF8String]))
1690 return build_string ((char *)str);
1693 [[col colorUsingDefaultColorSpace]
1694 getRed: &red green: &green blue: &blue alpha: &alpha];
1695 if (red == green && red == blue)
1697 [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1698 getWhite: &gray alpha: &alpha];
1699 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1700 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1702 return build_string (buf);
1705 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1706 lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1709 return build_string (buf);
1714 ns_query_color(void *col, XColor *color_def, int setPixel)
1715 /* --------------------------------------------------------------------------
1716 Get ARGB values out of NSColor col and put them into color_def.
1717 If setPixel, set the pixel to a concatenated version.
1718 and set color_def pixel to the resulting index.
1719 -------------------------------------------------------------------------- */
1721 EmacsCGFloat r, g, b, a;
1723 [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1724 color_def->red = r * 65535;
1725 color_def->green = g * 65535;
1726 color_def->blue = b * 65535;
1728 if (setPixel == YES)
1730 = ARGB_TO_ULONG((int)(a*255),
1731 (int)(r*255), (int)(g*255), (int)(b*255));
1736 ns_defined_color (struct frame *f,
1741 /* --------------------------------------------------------------------------
1742 Return true if named color found, and set color_def rgb accordingly.
1743 If makeIndex and alloc are nonzero put the color in the color_table,
1744 and set color_def pixel to the resulting index.
1745 If makeIndex is zero, set color_def pixel to ARGB.
1746 Return false if not found
1747 -------------------------------------------------------------------------- */
1750 NSTRACE (ns_defined_color);
1753 if (ns_get_color (name, &col) != 0) /* Color not found */
1758 if (makeIndex && alloc)
1759 color_def->pixel = ns_index_color (col, f);
1760 ns_query_color (col, color_def, !makeIndex);
1767 x_set_frame_alpha (struct frame *f)
1768 /* --------------------------------------------------------------------------
1769 change the entire-frame transparency
1770 -------------------------------------------------------------------------- */
1772 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1774 double alpha_min = 1.0;
1776 if (dpyinfo->x_highlight_frame == f)
1777 alpha = f->alpha[0];
1779 alpha = f->alpha[1];
1781 if (FLOATP (Vframe_alpha_lower_limit))
1782 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1783 else if (INTEGERP (Vframe_alpha_lower_limit))
1784 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1788 else if (1.0 < alpha)
1790 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1793 #ifdef NS_IMPL_COCOA
1795 EmacsView *view = FRAME_NS_VIEW (f);
1796 [[view window] setAlphaValue: alpha];
1802 /* ==========================================================================
1806 ========================================================================== */
1810 frame_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1811 /* --------------------------------------------------------------------------
1812 Programmatically reposition mouse pointer in pixel coordinates
1813 -------------------------------------------------------------------------- */
1815 NSTRACE (frame_set_mouse_pixel_position);
1818 /* FIXME: this does not work, and what about GNUstep? */
1819 #ifdef NS_IMPL_COCOA
1820 [FRAME_NS_VIEW (f) lockFocus];
1821 PSsetmouse ((float)pix_x, (float)pix_y);
1822 [FRAME_NS_VIEW (f) unlockFocus];
1828 note_mouse_movement (struct frame *frame, CGFloat x, CGFloat y)
1829 /* ------------------------------------------------------------------------
1830 Called by EmacsView on mouseMovement events. Passes on
1831 to emacs mainstream code if we moved off of a rect of interest
1832 known as last_mouse_glyph.
1833 ------------------------------------------------------------------------ */
1835 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
1838 // NSTRACE (note_mouse_movement);
1840 dpyinfo->last_mouse_motion_frame = frame;
1841 r = &dpyinfo->last_mouse_glyph;
1843 /* Note, this doesn't get called for enter/leave, since we don't have a
1844 position. Those are taken care of in the corresponding NSView methods. */
1846 /* has movement gone beyond last rect we were tracking? */
1847 if (x < r->origin.x || x >= r->origin.x + r->size.width
1848 || y < r->origin.y || y >= r->origin.y + r->size.height)
1850 ns_update_begin (frame);
1851 frame->mouse_moved = 1;
1852 note_mouse_highlight (frame, x, y);
1853 remember_mouse_glyph (frame, x, y, r);
1854 ns_update_end (frame);
1863 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1864 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1866 /* --------------------------------------------------------------------------
1867 External (hook): inform emacs about mouse position and hit parts.
1868 If a scrollbar is being dragged, set bar_window, part, x, y, time.
1869 x & y should be position in the scrollbar (the whole bar, not the handle)
1870 and length of scrollbar respectively
1871 -------------------------------------------------------------------------- */
1875 Lisp_Object frame, tail;
1877 struct ns_display_info *dpyinfo;
1879 NSTRACE (ns_mouse_position);
1883 fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1887 dpyinfo = FRAME_DISPLAY_INFO (*fp);
1891 /* Clear the mouse-moved flag for every frame on this display. */
1892 FOR_EACH_FRAME (tail, frame)
1893 if (FRAME_NS_P (XFRAME (frame))
1894 && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1895 XFRAME (frame)->mouse_moved = 0;
1897 dpyinfo->last_mouse_scroll_bar = nil;
1898 if (dpyinfo->last_mouse_frame
1899 && FRAME_LIVE_P (dpyinfo->last_mouse_frame))
1900 f = dpyinfo->last_mouse_frame;
1902 f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame : SELECTED_FRAME ();
1904 if (f && FRAME_NS_P (f))
1906 view = FRAME_NS_VIEW (*fp);
1908 position = [[view window] mouseLocationOutsideOfEventStream];
1909 position = [view convertPoint: position fromView: nil];
1910 remember_mouse_glyph (f, position.x, position.y,
1911 &dpyinfo->last_mouse_glyph);
1912 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1914 if (bar_window) *bar_window = Qnil;
1915 if (part) *part = scroll_bar_above_handle;
1917 if (x) XSETINT (*x, lrint (position.x));
1918 if (y) XSETINT (*y, lrint (position.y));
1920 *time = dpyinfo->last_mouse_movement_time;
1929 ns_frame_up_to_date (struct frame *f)
1930 /* --------------------------------------------------------------------------
1931 External (hook): Fix up mouse highlighting right after a full update.
1932 Can't use FRAME_MOUSE_UPDATE due to ns_frame_begin and ns_frame_end calls.
1933 -------------------------------------------------------------------------- */
1935 NSTRACE (ns_frame_up_to_date);
1939 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1940 if (f == hlinfo->mouse_face_mouse_frame)
1944 note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
1945 hlinfo->mouse_face_mouse_x,
1946 hlinfo->mouse_face_mouse_y);
1955 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1956 /* --------------------------------------------------------------------------
1957 External (RIF): set frame mouse pointer type.
1958 -------------------------------------------------------------------------- */
1960 NSTRACE (ns_define_frame_cursor);
1961 if (FRAME_POINTER_TYPE (f) != cursor)
1963 EmacsView *view = FRAME_NS_VIEW (f);
1964 FRAME_POINTER_TYPE (f) = cursor;
1965 [[view window] invalidateCursorRectsForView: view];
1966 /* Redisplay assumes this function also draws the changed frame
1967 cursor, but this function doesn't, so do it explicitly. */
1968 x_update_cursor (f, 1);
1974 /* ==========================================================================
1978 ========================================================================== */
1982 ns_convert_key (unsigned code)
1983 /* --------------------------------------------------------------------------
1984 Internal call used by NSView-keyDown.
1985 -------------------------------------------------------------------------- */
1987 const unsigned last_keysym = ARRAYELTS (convert_ns_to_X_keysym);
1989 /* An array would be faster, but less easy to read. */
1990 for (keysym = 0; keysym < last_keysym; keysym += 2)
1991 if (code == convert_ns_to_X_keysym[keysym])
1992 return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
1994 /* if decide to use keyCode and Carbon table, use this line:
1995 return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
2000 x_get_keysym_name (int keysym)
2001 /* --------------------------------------------------------------------------
2002 Called by keyboard.c. Not sure if the return val is important, except
2004 -------------------------------------------------------------------------- */
2006 static char value[16];
2007 NSTRACE (x_get_keysym_name);
2008 sprintf (value, "%d", keysym);
2014 /* ==========================================================================
2016 Block drawing operations
2018 ========================================================================== */
2022 ns_redraw_scroll_bars (struct frame *f)
2026 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
2027 NSTRACE (ns_redraw_scroll_bars);
2028 for (i =[subviews count]-1; i >= 0; i--)
2030 view = [subviews objectAtIndex: i];
2031 if (![view isKindOfClass: [EmacsScroller class]]) continue;
2038 ns_clear_frame (struct frame *f)
2039 /* --------------------------------------------------------------------------
2040 External (hook): Erase the entire frame
2041 -------------------------------------------------------------------------- */
2043 NSView *view = FRAME_NS_VIEW (f);
2046 NSTRACE (ns_clear_frame);
2048 /* comes on initial frame because we have
2049 after-make-frame-functions = select-frame */
2050 if (!FRAME_DEFAULT_FACE (f))
2053 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2058 ns_focus (f, &r, 1);
2059 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
2063 /* as of 2006/11 or so this is now needed */
2064 ns_redraw_scroll_bars (f);
2070 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2071 /* --------------------------------------------------------------------------
2072 External (RIF): Clear section of frame
2073 -------------------------------------------------------------------------- */
2075 NSRect r = NSMakeRect (x, y, width, height);
2076 NSView *view = FRAME_NS_VIEW (f);
2077 struct face *face = FRAME_DEFAULT_FACE (f);
2082 NSTRACE (ns_clear_frame_area);
2084 r = NSIntersectionRect (r, [view frame]);
2085 ns_focus (f, &r, 1);
2086 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2095 ns_copy_bits (struct frame *f, NSRect src, NSRect dest)
2097 if (FRAME_NS_VIEW (f))
2099 ns_focus (f, &dest, 1);
2100 [FRAME_NS_VIEW (f) scrollRect: src
2101 by: NSMakeSize (dest.origin.x - src.origin.x,
2102 dest.origin.y - src.origin.y)];
2108 ns_scroll_run (struct window *w, struct run *run)
2109 /* --------------------------------------------------------------------------
2110 External (RIF): Insert or delete n lines at line vpos
2111 -------------------------------------------------------------------------- */
2113 struct frame *f = XFRAME (w->frame);
2114 int x, y, width, height, from_y, to_y, bottom_y;
2116 NSTRACE (ns_scroll_run);
2118 /* begin copy from other terms */
2119 /* Get frame-relative bounding box of the text display area of W,
2120 without mode lines. Include in this box the left and right
2122 window_box (w, ANY_AREA, &x, &y, &width, &height);
2124 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2125 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2126 bottom_y = y + height;
2130 /* Scrolling up. Make sure we don't copy part of the mode
2131 line at the bottom. */
2132 if (from_y + run->height > bottom_y)
2133 height = bottom_y - from_y;
2135 height = run->height;
2139 /* Scrolling down. Make sure we don't copy over the mode line.
2141 if (to_y + run->height > bottom_y)
2142 height = bottom_y - to_y;
2144 height = run->height;
2146 /* end copy from other terms */
2156 NSRect srcRect = NSMakeRect (x, from_y, width, height);
2157 NSRect dstRect = NSMakeRect (x, to_y, width, height);
2159 ns_copy_bits (f, srcRect , dstRect);
2167 ns_after_update_window_line (struct window *w, struct glyph_row *desired_row)
2168 /* --------------------------------------------------------------------------
2169 External (RIF): preparatory to fringe update after text was updated
2170 -------------------------------------------------------------------------- */
2175 NSTRACE (ns_after_update_window_line);
2177 /* begin copy from other terms */
2180 if (!desired_row->mode_line_p && !w->pseudo_window_p)
2181 desired_row->redraw_fringe_bitmaps_p = 1;
2183 /* When a window has disappeared, make sure that no rest of
2184 full-width rows stays visible in the internal border. */
2185 if (windows_or_buffers_changed
2186 && desired_row->full_width_p
2187 && (f = XFRAME (w->frame),
2188 width = FRAME_INTERNAL_BORDER_WIDTH (f),
2190 && (height = desired_row->visible_height,
2193 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2196 ns_clear_frame_area (f, 0, y, width, height);
2197 ns_clear_frame_area (f,
2198 FRAME_PIXEL_WIDTH (f) - width,
2206 ns_shift_glyphs_for_insert (struct frame *f,
2207 int x, int y, int width, int height,
2209 /* --------------------------------------------------------------------------
2210 External (RIF): copy an area horizontally, don't worry about clearing src
2211 -------------------------------------------------------------------------- */
2213 NSRect srcRect = NSMakeRect (x, y, width, height);
2214 NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2216 NSTRACE (ns_shift_glyphs_for_insert);
2218 ns_copy_bits (f, srcRect, dstRect);
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)
2466 case DEFAULT_CURSOR:
2469 case FILLED_BOX_CURSOR:
2472 case HOLLOW_BOX_CURSOR:
2475 NSRectFill (NSInsetRect (r, 1, 1));
2476 [FRAME_CURSOR_COLOR (f) set];
2483 /* If the character under cursor is R2L, draw the bar cursor
2484 on the right of its glyph, rather than on the left. */
2485 cursor_glyph = get_phys_cursor_glyph (w);
2486 if ((cursor_glyph->resolved_level & 1) != 0)
2487 s.origin.x += cursor_glyph->pixel_width - s.size.width;
2494 /* draw the character under the cursor */
2495 if (cursor_type != NO_CURSOR)
2496 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2498 #ifdef NS_IMPL_COCOA
2499 NSEnableScreenUpdates ();
2506 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2507 /* --------------------------------------------------------------------------
2508 External (RIF): Draw a vertical line.
2509 -------------------------------------------------------------------------- */
2511 struct frame *f = XFRAME (WINDOW_FRAME (w));
2513 NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2515 NSTRACE (ns_draw_vertical_window_border);
2517 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2519 [ns_lookup_indexed_color(face->foreground, f) set];
2521 ns_focus (f, &r, 1);
2528 ns_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
2529 /* --------------------------------------------------------------------------
2530 External (RIF): Draw a window divider.
2531 -------------------------------------------------------------------------- */
2533 struct frame *f = XFRAME (WINDOW_FRAME (w));
2535 NSRect r = NSMakeRect (x0, y0, x1-x0, y1-y0);
2537 NSTRACE (ns_draw_window_divider);
2539 face = FACE_FROM_ID (f, WINDOW_DIVIDER_FACE_ID);
2541 [ns_lookup_indexed_color(face->foreground, f) set];
2543 ns_focus (f, &r, 1);
2549 ns_show_hourglass (struct frame *f)
2551 /* TODO: add NSProgressIndicator to all frames. */
2555 ns_hide_hourglass (struct frame *f)
2557 /* TODO: remove NSProgressIndicator from all frames. */
2560 /* ==========================================================================
2562 Glyph drawing operations
2564 ========================================================================== */
2567 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2568 /* --------------------------------------------------------------------------
2569 Wrapper utility to account for internal border width on full-width lines,
2570 and allow top full-width rows to hit the frame top. nr should be pointer
2571 to two successive NSRects. Number of rects actually used is returned.
2572 -------------------------------------------------------------------------- */
2574 int n = get_glyph_string_clip_rects (s, nr, 2);
2578 /* --------------------------------------------------------------------
2579 Draw a wavy line under glyph string s. The wave fills wave_height
2586 wave_height = 3 | * * * *
2587 --------------------------------------------------------------------- */
2590 ns_draw_underwave (struct glyph_string *s, EmacsCGFloat width, EmacsCGFloat x)
2592 int wave_height = 3, wave_length = 2;
2593 int y, dx, dy, odd, xmax;
2598 dy = wave_height - 1;
2599 y = s->ybase - wave_height + 3;
2602 /* Find and set clipping rectangle */
2603 waveClip = NSMakeRect (x, y, width, wave_height);
2604 [[NSGraphicsContext currentContext] saveGraphicsState];
2605 NSRectClip (waveClip);
2607 /* Draw the waves */
2608 a.x = x - ((int)(x) % dx) + (EmacsCGFloat) 0.5;
2610 odd = (int)(a.x/dx) % 2;
2611 a.y = b.y = y + 0.5;
2620 [NSBezierPath strokeLineFromPoint:a toPoint:b];
2621 a.x = b.x, a.y = b.y;
2622 b.x += dx, b.y = y + 0.5 + odd*dy;
2626 /* Restore previous clipping rectangle(s) */
2627 [[NSGraphicsContext currentContext] restoreGraphicsState];
2633 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
2634 NSColor *defaultCol, CGFloat width, CGFloat x)
2635 /* --------------------------------------------------------------------------
2636 Draw underline, overline, and strike-through on glyph string s.
2637 -------------------------------------------------------------------------- */
2639 if (s->for_overlaps)
2643 if (face->underline_p)
2645 if (s->face->underline_type == FACE_UNDER_WAVE)
2647 if (face->underline_defaulted_p)
2650 [ns_lookup_indexed_color (face->underline_color, s->f) set];
2652 ns_draw_underwave (s, width, x);
2654 else if (s->face->underline_type == FACE_UNDER_LINE)
2658 unsigned long thickness, position;
2660 /* If the prev was underlined, match its appearance. */
2661 if (s->prev && s->prev->face->underline_p
2662 && s->prev->face->underline_type == FACE_UNDER_LINE
2663 && s->prev->underline_thickness > 0)
2665 thickness = s->prev->underline_thickness;
2666 position = s->prev->underline_position;
2671 unsigned long descent;
2674 descent = s->y + s->height - s->ybase;
2676 /* Use underline thickness of font, defaulting to 1. */
2677 thickness = (font && font->underline_thickness > 0)
2678 ? font->underline_thickness : 1;
2680 /* Determine the offset of underlining from the baseline. */
2681 if (x_underline_at_descent_line)
2682 position = descent - thickness;
2683 else if (x_use_underline_position_properties
2684 && font && font->underline_position >= 0)
2685 position = font->underline_position;
2687 position = lround (font->descent / 2);
2689 position = underline_minimum_offset;
2691 position = max (position, underline_minimum_offset);
2693 /* Ensure underlining is not cropped. */
2694 if (descent <= position)
2696 position = descent - 1;
2699 else if (descent < position + thickness)
2703 s->underline_thickness = thickness;
2704 s->underline_position = position;
2706 r = NSMakeRect (x, s->ybase + position, width, thickness);
2708 if (face->underline_defaulted_p)
2711 [ns_lookup_indexed_color (face->underline_color, s->f) set];
2715 /* Do overline. We follow other terms in using a thickness of 1
2716 and ignoring overline_margin. */
2717 if (face->overline_p)
2720 r = NSMakeRect (x, s->y, width, 1);
2722 if (face->overline_color_defaulted_p)
2725 [ns_lookup_indexed_color (face->overline_color, s->f) set];
2729 /* Do strike-through. We follow other terms for thickness and
2730 vertical position.*/
2731 if (face->strike_through_p)
2736 dy = lrint ((s->height - 1) / 2);
2737 r = NSMakeRect (x, s->y + dy, width, 1);
2739 if (face->strike_through_color_defaulted_p)
2742 [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
2748 ns_draw_box (NSRect r, CGFloat thickness, NSColor *col,
2749 char left_p, char right_p)
2750 /* --------------------------------------------------------------------------
2751 Draw an unfilled rect inside r, optionally leaving left and/or right open.
2752 Note we can't just use an NSDrawRect command, because of the possibility
2753 of some sides not being drawn, and because the rect will be filled.
2754 -------------------------------------------------------------------------- */
2760 s.size.height = thickness;
2762 s.origin.y += r.size.height - thickness;
2765 s.size.height = r.size.height;
2766 s.origin.y = r.origin.y;
2768 /* left, right (optional) */
2769 s.size.width = thickness;
2774 s.origin.x += r.size.width - thickness;
2781 ns_draw_relief (NSRect r, int thickness, char raised_p,
2782 char top_p, char bottom_p, char left_p, char right_p,
2783 struct glyph_string *s)
2784 /* --------------------------------------------------------------------------
2785 Draw a relief rect inside r, optionally leaving some sides open.
2786 Note we can't just use an NSDrawBezel command, because of the possibility
2787 of some sides not being drawn, and because the rect will be filled.
2788 -------------------------------------------------------------------------- */
2790 static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2791 NSColor *newBaseCol = nil;
2794 NSTRACE (ns_draw_relief);
2798 if (s->face->use_box_color_for_shadows_p)
2800 newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2802 /* else if (s->first_glyph->type == IMAGE_GLYPH
2804 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2806 newBaseCol = IMAGE_BACKGROUND (s->img, s->f, 0);
2810 newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2813 if (newBaseCol == nil)
2814 newBaseCol = [NSColor grayColor];
2816 if (newBaseCol != baseCol) /* TODO: better check */
2819 baseCol = [newBaseCol retain];
2821 lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2823 darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2826 [(raised_p ? lightCol : darkCol) set];
2828 /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2831 sr.size.height = thickness;
2832 if (top_p) NSRectFill (sr);
2835 sr.size.height = r.size.height;
2836 sr.size.width = thickness;
2837 if (left_p) NSRectFill (sr);
2839 [(raised_p ? darkCol : lightCol) set];
2842 sr.size.width = r.size.width;
2843 sr.size.height = thickness;
2844 sr.origin.y += r.size.height - thickness;
2845 if (bottom_p) NSRectFill (sr);
2848 sr.size.height = r.size.height;
2849 sr.origin.y = r.origin.y;
2850 sr.size.width = thickness;
2851 sr.origin.x += r.size.width - thickness;
2852 if (right_p) NSRectFill (sr);
2857 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2858 /* --------------------------------------------------------------------------
2859 Function modeled after x_draw_glyph_string_box ().
2860 Sets up parameters for drawing.
2861 -------------------------------------------------------------------------- */
2863 int right_x, last_x;
2864 char left_p, right_p;
2865 struct glyph *last_glyph;
2870 if (s->hl == DRAW_MOUSE_FACE)
2872 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2874 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2879 thickness = face->box_line_width;
2881 NSTRACE (ns_dumpglyphs_box_or_relief);
2883 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2884 ? WINDOW_RIGHT_EDGE_X (s->w)
2885 : window_box_right (s->w, s->area));
2886 last_glyph = (s->cmp || s->img
2887 ? s->first_glyph : s->first_glyph + s->nchars-1);
2889 right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2890 ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2892 left_p = (s->first_glyph->left_box_line_p
2893 || (s->hl == DRAW_MOUSE_FACE
2894 && (s->prev == NULL || s->prev->hl != s->hl)));
2895 right_p = (last_glyph->right_box_line_p
2896 || (s->hl == DRAW_MOUSE_FACE
2897 && (s->next == NULL || s->next->hl != s->hl)));
2899 r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2901 /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
2902 if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
2904 ns_draw_box (r, abs (thickness),
2905 ns_lookup_indexed_color (face->box_color, s->f),
2910 ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2911 1, 1, left_p, right_p, s);
2917 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2918 /* --------------------------------------------------------------------------
2919 Modeled after x_draw_glyph_string_background, which draws BG in
2920 certain cases. Others are left to the text rendering routine.
2921 -------------------------------------------------------------------------- */
2923 NSTRACE (ns_maybe_dumpglyphs_background);
2925 if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2927 int box_line_width = max (s->face->box_line_width, 0);
2928 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2929 /* When xdisp.c ignores FONT_HEIGHT, we cannot trust font
2930 dimensions, since the actual glyphs might be much
2931 smaller. So in that case we always clear the rectangle
2932 with background color. */
2933 || FONT_TOO_HIGH (s->font)
2934 || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2937 if (s->hl == DRAW_MOUSE_FACE)
2939 face = FACE_FROM_ID (s->f,
2940 MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2942 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2945 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2947 [(NS_FACE_BACKGROUND (face) != 0
2948 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2949 : FRAME_BACKGROUND_COLOR (s->f)) set];
2952 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (s->f);
2953 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2956 if (s->hl != DRAW_CURSOR)
2958 NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2959 s->background_width,
2960 s->height-2*box_line_width);
2964 s->background_filled_p = 1;
2971 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2972 /* --------------------------------------------------------------------------
2973 Renders an image and associated borders.
2974 -------------------------------------------------------------------------- */
2976 EmacsImage *img = s->img->pixmap;
2977 int box_line_vwidth = max (s->face->box_line_width, 0);
2978 int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2979 int bg_x, bg_y, bg_height;
2986 NSTRACE (ns_dumpglyphs_image);
2988 if (s->face->box != FACE_NO_BOX
2989 && s->first_glyph->left_box_line_p && s->slice.x == 0)
2990 x += abs (s->face->box_line_width);
2993 bg_y = s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2994 bg_height = s->height;
2995 /* other terms have this, but was causing problems w/tabbar mode */
2996 /* - 2 * box_line_vwidth; */
2998 if (s->slice.x == 0) x += s->img->hmargin;
2999 if (s->slice.y == 0) y += s->img->vmargin;
3001 /* Draw BG: if we need larger area than image itself cleared, do that,
3002 otherwise, since we composite the image under NS (instead of mucking
3003 with its background color), we must clear just the image area. */
3004 if (s->hl == DRAW_MOUSE_FACE)
3006 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3008 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3011 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3013 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
3015 if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
3016 || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
3018 br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
3019 s->background_filled_p = 1;
3023 br = NSMakeRect (x, y, s->slice.width, s->slice.height);
3028 /* Draw the image.. do we need to draw placeholder if img ==nil? */
3031 #ifdef NS_IMPL_COCOA
3032 NSRect dr = NSMakeRect (x, y, s->slice.width, s->slice.height);
3033 NSRect ir = NSMakeRect (s->slice.x, s->slice.y,
3034 s->slice.width, s->slice.height);
3037 operation: NSCompositeSourceOver
3042 [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3043 operation: NSCompositeSourceOver];
3047 if (s->hl == DRAW_CURSOR)
3049 [FRAME_CURSOR_COLOR (s->f) set];
3050 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3051 tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3053 /* Currently on NS img->mask is always 0. Since
3054 get_window_cursor_type specifies a hollow box cursor when on
3055 a non-masked image we never reach this clause. But we put it
3056 in in anticipation of better support for image masks on
3058 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3062 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3065 /* Draw underline, overline, strike-through. */
3066 ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3068 /* Draw relief, if requested */
3069 if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3071 if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3073 th = tool_bar_button_relief >= 0 ?
3074 tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3075 raised_p = (s->hl == DRAW_IMAGE_RAISED);
3079 th = abs (s->img->relief);
3080 raised_p = (s->img->relief > 0);
3083 r.origin.x = x - th;
3084 r.origin.y = y - th;
3085 r.size.width = s->slice.width + 2*th-1;
3086 r.size.height = s->slice.height + 2*th-1;
3087 ns_draw_relief (r, th, raised_p,
3089 s->slice.y + s->slice.height == s->img->height,
3091 s->slice.x + s->slice.width == s->img->width, s);
3094 /* If there is no mask, the background won't be seen,
3095 so draw a rectangle on the image for the cursor.
3096 Do this for all images, getting transparency right is not reliable. */
3097 if (s->hl == DRAW_CURSOR)
3099 int thickness = abs (s->img->relief);
3100 if (thickness == 0) thickness = 1;
3101 ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3107 ns_dumpglyphs_stretch (struct glyph_string *s)
3112 NSColor *fgCol, *bgCol;
3114 if (!s->background_filled_p)
3116 n = ns_get_glyph_string_clip_rect (s, r);
3117 *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3119 ns_focus (s->f, r, n);
3121 if (s->hl == DRAW_MOUSE_FACE)
3123 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3125 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3128 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3130 bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3131 fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3133 for (i = 0; i < n; ++i)
3135 if (!s->row->full_width_p)
3137 int overrun, leftoverrun;
3139 /* truncate to avoid overwriting fringe and/or scrollbar */
3140 overrun = max (0, (s->x + s->background_width)
3141 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3142 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3143 r[i].size.width -= overrun;
3145 /* truncate to avoid overwriting to left of the window box */
3146 leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3147 + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3149 if (leftoverrun > 0)
3151 r[i].origin.x += leftoverrun;
3152 r[i].size.width -= leftoverrun;
3155 /* XXX: Try to work between problem where a stretch glyph on
3156 a partially-visible bottom row will clear part of the
3157 modeline, and another where list-buffers headers and similar
3158 rows erroneously have visible_height set to 0. Not sure
3159 where this is coming from as other terms seem not to show. */
3160 r[i].size.height = min (s->height, s->row->visible_height);
3165 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3166 overwriting cursor (usually when cursor on a tab) */
3167 if (s->hl == DRAW_CURSOR)
3172 width = s->w->phys_cursor_width;
3173 r[i].size.width -= width;
3174 r[i].origin.x += width;
3178 /* Draw overlining, etc. on the cursor. */
3179 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3180 ns_draw_text_decoration (s, face, bgCol, width, x);
3182 ns_draw_text_decoration (s, face, fgCol, width, x);
3189 /* Draw overlining, etc. on the stretch glyph (or the part
3190 of the stretch glyph after the cursor). */
3191 ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3195 s->background_filled_p = 1;
3201 ns_draw_composite_glyph_string_foreground (struct glyph_string *s)
3204 struct font *font = s->font;
3206 /* If first glyph of S has a left box line, start drawing the text
3207 of S to the right of that box line. */
3208 if (s->face && s->face->box != FACE_NO_BOX
3209 && s->first_glyph->left_box_line_p)
3210 x = s->x + eabs (s->face->box_line_width);
3214 /* S is a glyph string for a composition. S->cmp_from is the index
3215 of the first character drawn for glyphs of this composition.
3216 S->cmp_from == 0 means we are drawing the very first character of
3217 this composition. */
3219 /* Draw a rectangle for the composition if the font for the very
3220 first character of the composition could not be loaded. */
3221 if (s->font_not_found_p)
3223 if (s->cmp_from == 0)
3225 NSRect r = NSMakeRect (s->x, s->y, s->width-1, s->height -1);
3226 ns_draw_box (r, 1, FRAME_CURSOR_COLOR (s->f), 1, 1);
3229 else if (! s->first_glyph->u.cmp.automatic)
3233 for (i = 0, j = s->cmp_from; i < s->nchars; i++, j++)
3234 /* TAB in a composition means display glyphs with padding
3235 space on the left or right. */
3236 if (COMPOSITION_GLYPH (s->cmp, j) != '\t')
3238 int xx = x + s->cmp->offsets[j * 2];
3239 int yy = y - s->cmp->offsets[j * 2 + 1];
3241 font->driver->draw (s, j, j + 1, xx, yy, false);
3242 if (s->face->overstrike)
3243 font->driver->draw (s, j, j + 1, xx + 1, yy, false);
3248 Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
3253 for (i = j = s->cmp_from; i < s->cmp_to; i++)
3255 glyph = LGSTRING_GLYPH (gstring, i);
3256 if (NILP (LGLYPH_ADJUSTMENT (glyph)))
3257 width += LGLYPH_WIDTH (glyph);
3260 int xoff, yoff, wadjust;
3264 font->driver->draw (s, j, i, x, y, false);
3265 if (s->face->overstrike)
3266 font->driver->draw (s, j, i, x + 1, y, false);
3269 xoff = LGLYPH_XOFF (glyph);
3270 yoff = LGLYPH_YOFF (glyph);
3271 wadjust = LGLYPH_WADJUST (glyph);
3272 font->driver->draw (s, i, i + 1, x + xoff, y + yoff, false);
3273 if (s->face->overstrike)
3274 font->driver->draw (s, i, i + 1, x + xoff + 1, y + yoff,
3283 font->driver->draw (s, j, i, x, y, false);
3284 if (s->face->overstrike)
3285 font->driver->draw (s, j, i, x + 1, y, false);
3291 ns_draw_glyph_string (struct glyph_string *s)
3292 /* --------------------------------------------------------------------------
3293 External (RIF): Main draw-text call.
3294 -------------------------------------------------------------------------- */
3296 /* TODO (optimize): focus for box and contents draw */
3299 char box_drawn_p = 0;
3300 struct font *font = s->face->font;
3301 if (! font) font = FRAME_FONT (s->f);
3303 NSTRACE (ns_draw_glyph_string);
3305 if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3308 struct glyph_string *next;
3310 for (width = 0, next = s->next;
3311 next && width < s->right_overhang;
3312 width += next->width, next = next->next)
3313 if (next->first_glyph->type != IMAGE_GLYPH)
3315 if (next->first_glyph->type != STRETCH_GLYPH)
3317 n = ns_get_glyph_string_clip_rect (s->next, r);
3318 ns_focus (s->f, r, n);
3319 ns_maybe_dumpglyphs_background (s->next, 1);
3324 ns_dumpglyphs_stretch (s->next);
3326 next->num_clips = 0;
3330 if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3331 && (s->first_glyph->type == CHAR_GLYPH
3332 || s->first_glyph->type == COMPOSITE_GLYPH))
3334 n = ns_get_glyph_string_clip_rect (s, r);
3335 ns_focus (s->f, r, n);
3336 ns_maybe_dumpglyphs_background (s, 1);
3337 ns_dumpglyphs_box_or_relief (s);
3342 switch (s->first_glyph->type)
3346 n = ns_get_glyph_string_clip_rect (s, r);
3347 ns_focus (s->f, r, n);
3348 ns_dumpglyphs_image (s, r[0]);
3353 ns_dumpglyphs_stretch (s);
3357 case COMPOSITE_GLYPH:
3358 n = ns_get_glyph_string_clip_rect (s, r);
3359 ns_focus (s->f, r, n);
3361 if (s->for_overlaps || (s->cmp_from > 0
3362 && ! s->first_glyph->u.cmp.automatic))
3363 s->background_filled_p = 1;
3365 ns_maybe_dumpglyphs_background
3366 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3368 flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3369 (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3370 (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3371 NS_DUMPGLYPH_NORMAL));
3373 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3375 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3376 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3377 NS_FACE_FOREGROUND (s->face) = tmp;
3381 BOOL isComposite = s->first_glyph->type == COMPOSITE_GLYPH;
3384 ns_draw_composite_glyph_string_foreground (s);
3387 (s, s->cmp_from, s->nchars, s->x, s->ybase,
3388 (flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3389 || flags == NS_DUMPGLYPH_MOUSEFACE);
3393 NSColor *col = (NS_FACE_FOREGROUND (s->face) != 0
3394 ? ns_lookup_indexed_color (NS_FACE_FOREGROUND (s->face),
3396 : FRAME_FOREGROUND_COLOR (s->f));
3399 /* Draw underline, overline, strike-through. */
3400 ns_draw_text_decoration (s, s->face, col, s->width, s->x);
3403 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3405 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3406 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3407 NS_FACE_FOREGROUND (s->face) = tmp;
3413 case GLYPHLESS_GLYPH:
3414 n = ns_get_glyph_string_clip_rect (s, r);
3415 ns_focus (s->f, r, n);
3417 if (s->for_overlaps || (s->cmp_from > 0
3418 && ! s->first_glyph->u.cmp.automatic))
3419 s->background_filled_p = 1;
3421 ns_maybe_dumpglyphs_background
3422 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3424 /* Not yet implemented. */
3433 /* Draw box if not done already. */
3434 if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3436 n = ns_get_glyph_string_clip_rect (s, r);
3437 ns_focus (s->f, r, n);
3438 ns_dumpglyphs_box_or_relief (s);
3447 /* ==========================================================================
3451 ========================================================================== */
3455 ns_send_appdefined (int value)
3456 /* --------------------------------------------------------------------------
3457 Internal: post an appdefined event which EmacsApp-sendEvent will
3458 recognize and take as a command to halt the event loop.
3459 -------------------------------------------------------------------------- */
3461 /*NSTRACE (ns_send_appdefined); */
3463 #ifdef NS_IMPL_GNUSTEP
3464 // GNUstep needs postEvent to happen on the main thread.
3465 if (! [[NSThread currentThread] isMainThread])
3467 EmacsApp *app = (EmacsApp *)NSApp;
3468 app->nextappdefined = value;
3469 [app performSelectorOnMainThread:@selector (sendFromMainThread:)
3476 /* Only post this event if we haven't already posted one. This will end
3477 the [NXApp run] main loop after having processed all events queued at
3480 #ifdef NS_IMPL_COCOA
3481 if (! send_appdefined)
3483 /* OSX 10.10.1 swallows the AppDefined event we are sending ourselves
3484 in certain situations (rapid incoming events).
3485 So check if we have one, if not add one. */
3486 NSEvent *appev = [NSApp nextEventMatchingMask:NSApplicationDefinedMask
3487 untilDate:[NSDate distantPast]
3488 inMode:NSDefaultRunLoopMode
3490 if (! appev) send_appdefined = YES;
3494 if (send_appdefined)
3498 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
3499 send_appdefined = NO;
3501 /* Don't need wakeup timer any more */
3504 [timed_entry invalidate];
3505 [timed_entry release];
3509 nxev = [NSEvent otherEventWithType: NSApplicationDefined
3510 location: NSMakePoint (0, 0)
3513 windowNumber: [[NSApp mainWindow] windowNumber]
3514 context: [NSApp context]
3519 /* Post an application defined event on the event queue. When this is
3520 received the [NXApp run] will return, thus having processed all
3521 events which are currently queued. */
3522 [NSApp postEvent: nxev atStart: NO];
3526 #ifdef HAVE_NATIVE_FS
3530 Lisp_Object frame, tail;
3532 if (ns_last_use_native_fullscreen == ns_use_native_fullscreen)
3535 ns_last_use_native_fullscreen = ns_use_native_fullscreen;
3537 FOR_EACH_FRAME (tail, frame)
3539 struct frame *f = XFRAME (frame);
3542 EmacsView *view = FRAME_NS_VIEW (f);
3543 [view updateCollectionBehavior];
3549 /* GNUstep does not have cancelTracking. */
3550 #ifdef NS_IMPL_COCOA
3551 /* Check if menu open should be canceled or continued as normal. */
3553 ns_check_menu_open (NSMenu *menu)
3555 /* Click in menu bar? */
3556 NSArray *a = [[NSApp mainMenu] itemArray];
3560 if (menu == nil) // Menu tracking ended.
3562 if (menu_will_open_state == MENU_OPENING)
3563 menu_will_open_state = MENU_NONE;
3567 for (i = 0; ! found && i < [a count]; i++)
3568 found = menu == [[a objectAtIndex:i] submenu];
3571 if (menu_will_open_state == MENU_NONE && emacs_event)
3573 NSEvent *theEvent = [NSApp currentEvent];
3574 struct frame *emacsframe = SELECTED_FRAME ();
3576 [menu cancelTracking];
3577 menu_will_open_state = MENU_PENDING;
3578 emacs_event->kind = MENU_BAR_ACTIVATE_EVENT;
3579 EV_TRAILER (theEvent);
3581 CGEventRef ourEvent = CGEventCreate (NULL);
3582 menu_mouse_point = CGEventGetLocation (ourEvent);
3583 CFRelease (ourEvent);
3585 else if (menu_will_open_state == MENU_OPENING)
3587 menu_will_open_state = MENU_NONE;
3592 /* Redo saved menu click if state is MENU_PENDING. */
3594 ns_check_pending_open_menu ()
3596 if (menu_will_open_state == MENU_PENDING)
3598 CGEventSourceRef source
3599 = CGEventSourceCreate (kCGEventSourceStateHIDSystemState);
3601 CGEventRef event = CGEventCreateMouseEvent (source,
3602 kCGEventLeftMouseDown,
3604 kCGMouseButtonLeft);
3605 CGEventSetType (event, kCGEventLeftMouseDown);
3606 CGEventPost (kCGHIDEventTap, event);
3610 menu_will_open_state = MENU_OPENING;
3613 #endif /* NS_IMPL_COCOA */
3616 unwind_apploopnr (Lisp_Object not_used)
3619 n_emacs_events_pending = 0;
3620 ns_finish_events ();
3625 ns_read_socket (struct terminal *terminal, struct input_event *hold_quit)
3626 /* --------------------------------------------------------------------------
3627 External (hook): Post an event to ourself and keep reading events until
3628 we read it back again. In effect process all events which were waiting.
3629 From 21+ we have to manage the event buffer ourselves.
3630 -------------------------------------------------------------------------- */
3632 struct input_event ev;
3635 /* NSTRACE (ns_read_socket); */
3637 #ifdef HAVE_NATIVE_FS
3641 if ([NSApp modalWindow] != nil)
3644 if (hold_event_q.nr > 0)
3647 for (i = 0; i < hold_event_q.nr; ++i)
3648 kbd_buffer_store_event_hold (&hold_event_q.q[i], hold_quit);
3649 hold_event_q.nr = 0;
3654 n_emacs_events_pending = 0;
3655 ns_init_events (&ev);
3656 q_event_ptr = hold_quit;
3658 /* we manage autorelease pools by allocate/reallocate each time around
3659 the loop; strict nesting is occasionally violated but seems not to
3660 matter.. earlier methods using full nesting caused major memory leaks */
3661 [outerpool release];
3662 outerpool = [[NSAutoreleasePool alloc] init];
3664 /* If have pending open-file requests, attend to the next one of those. */
3665 if (ns_pending_files && [ns_pending_files count] != 0
3666 && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3668 [ns_pending_files removeObjectAtIndex: 0];
3670 /* Deal with pending service requests. */
3671 else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3673 NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3674 withArg: [ns_pending_service_args objectAtIndex: 0]])
3676 [ns_pending_service_names removeObjectAtIndex: 0];
3677 [ns_pending_service_args removeObjectAtIndex: 0];
3681 ptrdiff_t specpdl_count = SPECPDL_INDEX ();
3682 /* Run and wait for events. We must always send one NX_APPDEFINED event
3683 to ourself, otherwise [NXApp run] will never exit. */
3684 send_appdefined = YES;
3685 ns_send_appdefined (-1);
3687 if (++apploopnr != 1)
3691 record_unwind_protect (unwind_apploopnr, Qt);
3693 unbind_to (specpdl_count, Qnil); /* calls unwind_apploopnr */
3696 nevents = n_emacs_events_pending;
3697 n_emacs_events_pending = 0;
3698 ns_finish_events ();
3707 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3708 fd_set *exceptfds, struct timespec const *timeout,
3709 sigset_t const *sigmask)
3710 /* --------------------------------------------------------------------------
3711 Replacement for select, checking for events
3712 -------------------------------------------------------------------------- */
3716 struct input_event event;
3719 /* NSTRACE (ns_select); */
3721 #ifdef HAVE_NATIVE_FS
3725 if (hold_event_q.nr > 0)
3727 /* We already have events pending. */
3733 for (k = 0; k < nfds+1; k++)
3735 if (readfds && FD_ISSET(k, readfds)) ++nr;
3736 if (writefds && FD_ISSET(k, writefds)) ++nr;
3740 || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0))
3741 return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
3743 [outerpool release];
3744 outerpool = [[NSAutoreleasePool alloc] init];
3747 send_appdefined = YES;
3750 pthread_mutex_lock (&select_mutex);
3755 select_readfds = *readfds;
3756 select_valid += SELECT_HAVE_READ;
3760 select_writefds = *writefds;
3761 select_valid += SELECT_HAVE_WRITE;
3766 select_timeout = *timeout;
3767 select_valid += SELECT_HAVE_TMO;
3770 pthread_mutex_unlock (&select_mutex);
3772 /* Inform fd_handler that select should be called */
3774 emacs_write_sig (selfds[1], &c, 1);
3776 else if (nr == 0 && timeout)
3778 /* No file descriptor, just a timeout, no need to wake fd_handler */
3779 double time = timespectod (*timeout);
3780 timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3783 @selector (timeout_handler:)
3788 else /* No timeout and no file descriptors, can this happen? */
3790 /* Send appdefined so we exit from the loop */
3791 ns_send_appdefined (-1);
3795 ns_init_events (&event);
3796 if (++apploopnr != 1)
3802 ptrdiff_t specpdl_count = SPECPDL_INDEX ();
3803 record_unwind_protect (unwind_apploopnr, Qt);
3805 unbind_to (specpdl_count, Qnil); /* calls unwind_apploopnr */
3808 ns_finish_events ();
3809 if (nr > 0 && readfds)
3812 emacs_write_sig (selfds[1], &c, 1);
3816 t = last_appdefined_event_data;
3818 if (t != NO_APPDEFINED_DATA)
3820 last_appdefined_event_data = NO_APPDEFINED_DATA;
3824 /* The NX_APPDEFINED event we received was a timeout. */
3829 /* The NX_APPDEFINED event we received was the result of
3830 at least one real input event arriving. */
3836 /* Received back from select () in fd_handler; copy the results */
3837 pthread_mutex_lock (&select_mutex);
3838 if (readfds) *readfds = select_readfds;
3839 if (writefds) *writefds = select_writefds;
3840 pthread_mutex_unlock (&select_mutex);
3855 /* ==========================================================================
3859 ========================================================================== */
3863 ns_set_vertical_scroll_bar (struct window *window,
3864 int portion, int whole, int position)
3865 /* --------------------------------------------------------------------------
3866 External (hook): Update or add scrollbar
3867 -------------------------------------------------------------------------- */
3871 struct frame *f = XFRAME (WINDOW_FRAME (window));
3872 EmacsView *view = FRAME_NS_VIEW (f);
3874 int window_y, window_height;
3875 int top, left, height, width;
3876 BOOL update_p = YES;
3878 /* optimization; display engine sends WAY too many of these.. */
3879 if (!NILP (window->vertical_scroll_bar))
3881 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3882 if ([bar checkSamePosition: position portion: portion whole: whole])
3884 if (view->scrollbarsNeedingUpdate == 0)
3886 if (!windows_or_buffers_changed)
3890 view->scrollbarsNeedingUpdate--;
3895 NSTRACE (ns_set_vertical_scroll_bar);
3897 /* Get dimensions. */
3898 window_box (window, ANY_AREA, 0, &window_y, 0, &window_height);
3900 height = window_height;
3901 width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3902 left = WINDOW_SCROLL_BAR_AREA_X (window);
3904 r = NSMakeRect (left, top, width, height);
3905 /* the parent view is flipped, so we need to flip y value */
3907 r.origin.y = (v.size.height - r.size.height - r.origin.y);
3909 XSETWINDOW (win, window);
3912 /* we want at least 5 lines to display a scrollbar */
3913 if (WINDOW_TOTAL_LINES (window) < 5)
3915 if (!NILP (window->vertical_scroll_bar))
3917 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3918 [bar removeFromSuperview];
3919 wset_vertical_scroll_bar (window, Qnil);
3922 ns_clear_frame_area (f, left, top, width, height);
3927 if (NILP (window->vertical_scroll_bar))
3929 if (width > 0 && height > 0)
3930 ns_clear_frame_area (f, left, top, width, height);
3932 bar = [[EmacsScroller alloc] initFrame: r window: win];
3933 wset_vertical_scroll_bar (window, make_save_ptr (bar));
3939 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3940 oldRect = [bar frame];
3941 r.size.width = oldRect.size.width;
3942 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3944 if (oldRect.origin.x != r.origin.x)
3945 ns_clear_frame_area (f, left, top, width, height);
3951 [bar setPosition: position portion: portion whole: whole];
3957 ns_set_horizontal_scroll_bar (struct window *window,
3958 int portion, int whole, int position)
3959 /* --------------------------------------------------------------------------
3960 External (hook): Update or add scrollbar
3961 -------------------------------------------------------------------------- */
3965 struct frame *f = XFRAME (WINDOW_FRAME (window));
3966 EmacsView *view = FRAME_NS_VIEW (f);
3968 int top, height, left, width;
3969 int window_x, window_width;
3970 BOOL update_p = YES;
3972 /* optimization; display engine sends WAY too many of these.. */
3973 if (!NILP (window->horizontal_scroll_bar))
3975 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
3976 if ([bar checkSamePosition: position portion: portion whole: whole])
3978 if (view->scrollbarsNeedingUpdate == 0)
3980 if (!windows_or_buffers_changed)
3984 view->scrollbarsNeedingUpdate--;
3989 NSTRACE (ns_set_horizontal_scroll_bar);
3991 /* Get dimensions. */
3992 window_box (window, ANY_AREA, 0, &window_x, &window_width, 0);
3994 width = window_width;
3995 height = WINDOW_CONFIG_SCROLL_BAR_LINES (window) * FRAME_LINE_HEIGHT (f);
3996 top = WINDOW_SCROLL_BAR_AREA_Y (window);
3998 r = NSMakeRect (left, top, width, height);
3999 /* the parent view is flipped, so we need to flip y value */
4001 /* ??????? PXW/scrollbars !!!!!!!!!!!!!!!!!!!! */
4002 r.origin.y = (v.size.height - r.size.height - r.origin.y);
4004 XSETWINDOW (win, window);
4007 if (WINDOW_TOTAL_COLS (window) < 5)
4009 if (!NILP (window->horizontal_scroll_bar))
4011 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4012 [bar removeFromSuperview];
4013 wset_horizontal_scroll_bar (window, Qnil);
4015 ns_clear_frame_area (f, left, top, width, height);
4020 if (NILP (window->horizontal_scroll_bar))
4022 if (width > 0 && height > 0)
4023 ns_clear_frame_area (f, left, top, width, height);
4025 bar = [[EmacsScroller alloc] initFrame: r window: win];
4026 wset_horizontal_scroll_bar (window, make_save_ptr (bar));
4032 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4033 oldRect = [bar frame];
4034 r.size.width = oldRect.size.width;
4035 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
4037 if (oldRect.origin.x != r.origin.x)
4038 ns_clear_frame_area (f, left, top, width, height);
4045 [bar setPosition: position portion: portion whole: whole];
4051 ns_condemn_scroll_bars (struct frame *f)
4052 /* --------------------------------------------------------------------------
4053 External (hook): arrange for all frame's scrollbars to be removed
4054 at next call to judge_scroll_bars, except for those redeemed.
4055 -------------------------------------------------------------------------- */
4059 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
4061 NSTRACE (ns_condemn_scroll_bars);
4063 for (i =[subviews count]-1; i >= 0; i--)
4065 view = [subviews objectAtIndex: i];
4066 if ([view isKindOfClass: [EmacsScroller class]])
4073 ns_redeem_scroll_bar (struct window *window)
4074 /* --------------------------------------------------------------------------
4075 External (hook): arrange to spare this window's scrollbar
4076 at next call to judge_scroll_bars.
4077 -------------------------------------------------------------------------- */
4080 NSTRACE (ns_redeem_scroll_bar);
4081 if (!NILP (window->vertical_scroll_bar))
4083 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
4087 if (!NILP (window->horizontal_scroll_bar))
4089 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
4096 ns_judge_scroll_bars (struct frame *f)
4097 /* --------------------------------------------------------------------------
4098 External (hook): destroy all scrollbars on frame that weren't
4099 redeemed after call to condemn_scroll_bars.
4100 -------------------------------------------------------------------------- */
4104 EmacsView *eview = FRAME_NS_VIEW (f);
4105 NSArray *subviews = [[eview superview] subviews];
4108 NSTRACE (ns_judge_scroll_bars);
4109 for (i = [subviews count]-1; i >= 0; --i)
4111 view = [subviews objectAtIndex: i];
4112 if (![view isKindOfClass: [EmacsScroller class]]) continue;
4118 [eview updateFrameSize: NO];
4121 /* ==========================================================================
4125 ========================================================================== */
4128 x_display_pixel_height (struct ns_display_info *dpyinfo)
4130 NSArray *screens = [NSScreen screens];
4131 NSEnumerator *enumerator = [screens objectEnumerator];
4136 while ((screen = [enumerator nextObject]) != nil)
4137 frame = NSUnionRect (frame, [screen frame]);
4139 return NSHeight (frame);
4143 x_display_pixel_width (struct ns_display_info *dpyinfo)
4145 NSArray *screens = [NSScreen screens];
4146 NSEnumerator *enumerator = [screens objectEnumerator];
4151 while ((screen = [enumerator nextObject]) != nil)
4152 frame = NSUnionRect (frame, [screen frame]);
4154 return NSWidth (frame);
4158 static Lisp_Object ns_string_to_lispmod (const char *s)
4159 /* --------------------------------------------------------------------------
4160 Convert modifier name to lisp symbol
4161 -------------------------------------------------------------------------- */
4163 if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
4165 else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
4167 else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
4169 else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
4171 else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
4173 else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
4181 ns_default (const char *parameter, Lisp_Object *result,
4182 Lisp_Object yesval, Lisp_Object noval,
4183 BOOL is_float, BOOL is_modstring)
4184 /* --------------------------------------------------------------------------
4185 Check a parameter value in user's preferences
4186 -------------------------------------------------------------------------- */
4188 const char *value = ns_get_defaults_value (parameter);
4194 if (c_strcasecmp (value, "YES") == 0)
4196 else if (c_strcasecmp (value, "NO") == 0)
4198 else if (is_float && (f = strtod (value, &pos), pos != value))
4199 *result = make_float (f);
4200 else if (is_modstring && value)
4201 *result = ns_string_to_lispmod (value);
4202 else fprintf (stderr,
4203 "Bad value for default \"%s\": \"%s\"\n", parameter, value);
4209 ns_initialize_display_info (struct ns_display_info *dpyinfo)
4210 /* --------------------------------------------------------------------------
4211 Initialize global info and storage for display.
4212 -------------------------------------------------------------------------- */
4214 NSScreen *screen = [NSScreen mainScreen];
4215 NSWindowDepth depth = [screen depth];
4217 dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
4218 dpyinfo->resy = 72.27;
4219 dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
4220 NSColorSpaceFromDepth (depth)]
4221 && ![NSCalibratedWhiteColorSpace isEqualToString:
4222 NSColorSpaceFromDepth (depth)];
4223 dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
4224 dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
4225 dpyinfo->color_table->colors = NULL;
4226 dpyinfo->root_window = 42; /* a placeholder.. */
4227 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
4228 dpyinfo->n_fonts = 0;
4229 dpyinfo->smallest_font_height = 1;
4230 dpyinfo->smallest_char_width = 1;
4232 reset_mouse_highlight (&dpyinfo->mouse_highlight);
4236 /* This and next define (many of the) public functions in this file. */
4237 /* x_... are generic versions in xdisp.c that we, and other terms, get away
4238 with using despite presence in the "system dependent" redisplay
4239 interface. In addition, many of the ns_ methods have code that is
4240 shared with all terms, indicating need for further refactoring. */
4241 extern frame_parm_handler ns_frame_parm_handlers[];
4242 static struct redisplay_interface ns_redisplay_interface =
4244 ns_frame_parm_handlers,
4248 x_clear_end_of_line,
4250 ns_after_update_window_line,
4251 ns_update_window_begin,
4252 ns_update_window_end,
4253 0, /* flush_display */
4254 x_clear_window_mouse_face,
4255 x_get_glyph_overhangs,
4256 x_fix_overlapping_area,
4257 ns_draw_fringe_bitmap,
4258 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
4259 0, /* destroy_fringe_bitmap */
4260 ns_compute_glyph_string_overhangs,
4261 ns_draw_glyph_string,
4262 ns_define_frame_cursor,
4263 ns_clear_frame_area,
4264 ns_draw_window_cursor,
4265 ns_draw_vertical_window_border,
4266 ns_draw_window_divider,
4267 ns_shift_glyphs_for_insert,
4274 ns_delete_display (struct ns_display_info *dpyinfo)
4280 /* This function is called when the last frame on a display is deleted. */
4282 ns_delete_terminal (struct terminal *terminal)
4284 struct ns_display_info *dpyinfo = terminal->display_info.ns;
4286 /* Protect against recursive calls. delete_frame in
4287 delete_terminal calls us back when it deletes our last frame. */
4288 if (!terminal->name)
4293 x_destroy_all_bitmaps (dpyinfo);
4294 ns_delete_display (dpyinfo);
4299 static struct terminal *
4300 ns_create_terminal (struct ns_display_info *dpyinfo)
4301 /* --------------------------------------------------------------------------
4302 Set up use of NS before we make the first connection.
4303 -------------------------------------------------------------------------- */
4305 struct terminal *terminal;
4307 NSTRACE (ns_create_terminal);
4309 terminal = create_terminal (output_ns, &ns_redisplay_interface);
4311 terminal->display_info.ns = dpyinfo;
4312 dpyinfo->terminal = terminal;
4314 terminal->clear_frame_hook = ns_clear_frame;
4315 terminal->ring_bell_hook = ns_ring_bell;
4316 terminal->update_begin_hook = ns_update_begin;
4317 terminal->update_end_hook = ns_update_end;
4318 terminal->read_socket_hook = ns_read_socket;
4319 terminal->frame_up_to_date_hook = ns_frame_up_to_date;
4320 terminal->mouse_position_hook = ns_mouse_position;
4321 terminal->frame_rehighlight_hook = ns_frame_rehighlight;
4322 terminal->frame_raise_lower_hook = ns_frame_raise_lower;
4323 terminal->fullscreen_hook = ns_fullscreen_hook;
4324 terminal->menu_show_hook = ns_menu_show;
4325 terminal->popup_dialog_hook = ns_popup_dialog;
4326 terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
4327 terminal->set_horizontal_scroll_bar_hook = ns_set_horizontal_scroll_bar;
4328 terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
4329 terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
4330 terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
4331 terminal->delete_frame_hook = x_destroy_window;
4332 terminal->delete_terminal_hook = ns_delete_terminal;
4333 /* Other hooks are NULL by default. */
4339 struct ns_display_info *
4340 ns_term_init (Lisp_Object display_name)
4341 /* --------------------------------------------------------------------------
4342 Start the Application and get things rolling.
4343 -------------------------------------------------------------------------- */
4345 struct terminal *terminal;
4346 struct ns_display_info *dpyinfo;
4347 static int ns_initialized = 0;
4350 if (ns_initialized) return x_display_list;
4353 NSTRACE (ns_term_init);
4355 [outerpool release];
4356 outerpool = [[NSAutoreleasePool alloc] init];
4358 /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4359 /*GSDebugAllocationActive (YES); */
4363 Fset_input_interrupt_mode (Qnil);
4365 if (selfds[0] == -1)
4367 if (emacs_pipe (selfds) != 0)
4369 fprintf (stderr, "Failed to create pipe: %s\n",
4370 emacs_strerror (errno));
4374 fcntl (selfds[0], F_SETFL, O_NONBLOCK|fcntl (selfds[0], F_GETFL));
4375 FD_ZERO (&select_readfds);
4376 FD_ZERO (&select_writefds);
4377 pthread_mutex_init (&select_mutex, NULL);
4380 ns_pending_files = [[NSMutableArray alloc] init];
4381 ns_pending_service_names = [[NSMutableArray alloc] init];
4382 ns_pending_service_args = [[NSMutableArray alloc] init];
4384 /* Start app and create the main menu, window, view.
4385 Needs to be here because ns_initialize_display_info () uses AppKit classes.
4386 The view will then ask the NSApp to stop and return to Emacs. */
4387 [EmacsApp sharedApplication];
4390 [NSApp setDelegate: NSApp];
4392 /* Start the select thread. */
4393 [NSThread detachNewThreadSelector:@selector (fd_handler:)
4397 /* debugging: log all notifications */
4398 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
4399 selector: @selector (logNotification:)
4400 name: nil object: nil]; */
4402 dpyinfo = xzalloc (sizeof *dpyinfo);
4404 ns_initialize_display_info (dpyinfo);
4405 terminal = ns_create_terminal (dpyinfo);
4407 terminal->kboard = allocate_kboard (Qns);
4408 /* Don't let the initial kboard remain current longer than necessary.
4409 That would cause problems if a file loaded on startup tries to
4410 prompt in the mini-buffer. */
4411 if (current_kboard == initial_kboard)
4412 current_kboard = terminal->kboard;
4413 terminal->kboard->reference_count++;
4415 dpyinfo->next = x_display_list;
4416 x_display_list = dpyinfo;
4418 dpyinfo->name_list_element = Fcons (display_name, Qnil);
4420 terminal->name = xlispstrdup (display_name);
4424 if (!inhibit_x_resources)
4426 ns_default ("GSFontAntiAlias", &ns_antialias_text,
4429 /* this is a standard variable */
4430 ns_default ("AppleAntiAliasingThreshold", &tmp,
4431 make_float (10.0), make_float (6.0), YES, NO);
4432 ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4436 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4440 Lisp_Object color_file, color_map, color;
4444 color_file = Fexpand_file_name (build_string ("rgb.txt"),
4445 Fsymbol_value (intern ("data-directory")));
4447 color_map = Fx_load_color_file (color_file);
4448 if (NILP (color_map))
4449 fatal ("Could not read %s.\n", SDATA (color_file));
4451 cl = [[NSColorList alloc] initWithName: @"Emacs"];
4452 for ( ; CONSP (color_map); color_map = XCDR (color_map))
4454 color = XCAR (color_map);
4455 name = SSDATA (XCAR (color));
4456 c = XINT (XCDR (color));
4458 [NSColor colorForEmacsRed: RED_FROM_ULONG (c) / 255.0
4459 green: GREEN_FROM_ULONG (c) / 255.0
4460 blue: BLUE_FROM_ULONG (c) / 255.0
4462 forKey: [NSString stringWithUTF8String: name]];
4464 [cl writeToFile: nil];
4469 #ifdef NS_IMPL_GNUSTEP
4470 Vwindow_system_version = build_string (gnustep_base_version);
4472 /*PSnextrelease (128, c); */
4473 char c[DBL_BUFSIZE_BOUND];
4474 int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4475 Vwindow_system_version = make_unibyte_string (c, len);
4479 delete_keyboard_wait_descriptor (0);
4481 ns_app_name = [[NSProcessInfo processInfo] processName];
4483 /* Set up OS X app menu */
4484 #ifdef NS_IMPL_COCOA
4488 /* set up the application menu */
4489 svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4490 [svcsMenu setAutoenablesItems: NO];
4491 appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4492 [appMenu setAutoenablesItems: NO];
4493 mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4494 dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4496 [appMenu insertItemWithTitle: @"About Emacs"
4497 action: @selector (orderFrontStandardAboutPanel:)
4500 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4501 [appMenu insertItemWithTitle: @"Preferences..."
4502 action: @selector (showPreferencesWindow:)
4505 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4506 item = [appMenu insertItemWithTitle: @"Services"
4507 action: @selector (menuDown:)
4510 [appMenu setSubmenu: svcsMenu forItem: item];
4511 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4512 [appMenu insertItemWithTitle: @"Hide Emacs"
4513 action: @selector (hide:)
4516 item = [appMenu insertItemWithTitle: @"Hide Others"
4517 action: @selector (hideOtherApplications:)
4520 [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4521 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4522 [appMenu insertItemWithTitle: @"Quit Emacs"
4523 action: @selector (terminate:)
4527 item = [mainMenu insertItemWithTitle: ns_app_name
4528 action: @selector (menuDown:)
4531 [mainMenu setSubmenu: appMenu forItem: item];
4532 [dockMenu insertItemWithTitle: @"New Frame"
4533 action: @selector (newFrame:)
4537 [NSApp setMainMenu: mainMenu];
4538 [NSApp setAppleMenu: appMenu];
4539 [NSApp setServicesMenu: svcsMenu];
4540 /* Needed at least on Cocoa, to get dock menu to show windows */
4541 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4543 [[NSNotificationCenter defaultCenter]
4544 addObserver: mainMenu
4545 selector: @selector (trackingNotification:)
4546 name: NSMenuDidBeginTrackingNotification object: mainMenu];
4547 [[NSNotificationCenter defaultCenter]
4548 addObserver: mainMenu
4549 selector: @selector (trackingNotification:)
4550 name: NSMenuDidEndTrackingNotification object: mainMenu];
4552 #endif /* MAC OS X menu setup */
4554 /* Register our external input/output types, used for determining
4555 applicable services and also drag/drop eligibility. */
4556 ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
4557 ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
4559 ns_drag_types = [[NSArray arrayWithObjects:
4561 NSTabularTextPboardType,
4562 NSFilenamesPboardType,
4563 NSURLPboardType, nil] retain];
4565 /* If fullscreen is in init/default-frame-alist, focus isn't set
4566 right for fullscreen windows, so set this. */
4567 [NSApp activateIgnoringOtherApps:YES];
4570 ns_do_open_file = YES;
4572 #ifdef NS_IMPL_GNUSTEP
4573 /* GNUstep steals SIGCHLD for use in NSTask, but we don't use NSTask.
4574 We must re-catch it so subprocess works. */
4575 catch_child_signal ();
4582 ns_term_shutdown (int sig)
4584 [[NSUserDefaults standardUserDefaults] synchronize];
4586 /* code not reached in emacs.c after this is called by shut_down_emacs: */
4587 if (STRINGP (Vauto_save_list_file_name))
4588 unlink (SSDATA (Vauto_save_list_file_name));
4590 if (sig == 0 || sig == SIGTERM)
4592 [NSApp terminate: NSApp];
4594 else // force a stack trace to happen
4601 /* ==========================================================================
4603 EmacsApp implementation
4605 ========================================================================== */
4608 @implementation EmacsApp
4612 if ((self = [super init]))
4614 #ifdef NS_IMPL_COCOA
4615 self->isFirst = YES;
4617 #ifdef NS_IMPL_GNUSTEP
4618 self->applicationDidFinishLaunchingCalled = NO;
4625 #ifdef NS_IMPL_COCOA
4628 #ifndef NSAppKitVersionNumber10_9
4629 #define NSAppKitVersionNumber10_9 1265
4632 if ((int)NSAppKitVersionNumber != NSAppKitVersionNumber10_9)
4638 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
4640 if (isFirst) [self finishLaunching];
4643 shouldKeepRunning = YES;
4647 pool = [[NSAutoreleasePool alloc] init];
4650 [self nextEventMatchingMask:NSAnyEventMask
4651 untilDate:[NSDate distantFuture]
4652 inMode:NSDefaultRunLoopMode
4655 [self sendEvent:event];
4656 [self updateWindows];
4657 } while (shouldKeepRunning);
4662 - (void)stop: (id)sender
4664 shouldKeepRunning = NO;
4665 // Stop possible dialog also. Noop if no dialog present.
4666 // The file dialog still leaks 7k - 10k on 10.9 though.
4667 [super stop:sender];
4669 #endif /* NS_IMPL_COCOA */
4671 - (void)logNotification: (NSNotification *)notification
4673 const char *name = [[notification name] UTF8String];
4674 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4675 && !strstr (name, "WindowNumber"))
4676 NSLog (@"notification: '%@'", [notification name]);
4680 - (void)sendEvent: (NSEvent *)theEvent
4681 /* --------------------------------------------------------------------------
4682 Called when NSApp is running for each event received. Used to stop
4683 the loop when we choose, since there's no way to just run one iteration.
4684 -------------------------------------------------------------------------- */
4686 int type = [theEvent type];
4687 NSWindow *window = [theEvent window];
4689 /* NSTRACE (sendEvent); */
4690 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4692 #ifdef NS_IMPL_GNUSTEP
4693 // Keyboard events aren't propagated to file dialogs for some reason.
4694 if ([NSApp modalWindow] != nil &&
4695 (type == NSKeyDown || type == NSKeyUp || type == NSFlagsChanged))
4697 [[NSApp modalWindow] sendEvent: theEvent];
4702 if (represented_filename != nil && represented_frame)
4704 NSString *fstr = represented_filename;
4705 NSView *view = FRAME_NS_VIEW (represented_frame);
4706 #ifdef NS_IMPL_COCOA
4707 /* work around a bug observed on 10.3 and later where
4708 setTitleWithRepresentedFilename does not clear out previous state
4709 if given filename does not exist */
4710 if (! [[NSFileManager defaultManager] fileExistsAtPath: fstr])
4711 [[view window] setRepresentedFilename: @""];
4713 [[view window] setRepresentedFilename: fstr];
4714 [represented_filename release];
4715 represented_filename = nil;
4716 represented_frame = NULL;
4719 if (type == NSApplicationDefined)
4721 switch ([theEvent data2])
4723 #ifdef NS_IMPL_COCOA
4724 case NSAPP_DATA2_RUNASSCRIPT:
4729 case NSAPP_DATA2_RUNFILEDIALOG:
4730 ns_run_file_dialog ();
4736 if (type == NSCursorUpdate && window == nil)
4738 fprintf (stderr, "Dropping external cursor update event.\n");
4742 if (type == NSApplicationDefined)
4744 /* Events posted by ns_send_appdefined interrupt the run loop here.
4745 But, if a modal window is up, an appdefined can still come through,
4746 (e.g., from a makeKeyWindow event) but stopping self also stops the
4747 modal loop. Just defer it until later. */
4748 if ([NSApp modalWindow] == nil)
4750 last_appdefined_event_data = [theEvent data1];
4755 send_appdefined = YES;
4760 #ifdef NS_IMPL_COCOA
4761 /* If no dialog and none of our frames have focus and it is a move, skip it.
4762 It is a mouse move in an auxiliary menu, i.e. on the top right on OSX,
4763 such as Wifi, sound, date or similar.
4764 This prevents "spooky" highlighting in the frame under the menu. */
4765 if (type == NSMouseMoved && [NSApp modalWindow] == nil)
4767 struct ns_display_info *di;
4768 BOOL has_focus = NO;
4769 for (di = x_display_list; ! has_focus && di; di = di->next)
4770 has_focus = di->x_focus_frame != 0;
4776 [super sendEvent: theEvent];
4780 - (void)showPreferencesWindow: (id)sender
4782 struct frame *emacsframe = SELECTED_FRAME ();
4783 NSEvent *theEvent = [NSApp currentEvent];
4787 emacs_event->kind = NS_NONKEY_EVENT;
4788 emacs_event->code = KEY_NS_SHOW_PREFS;
4789 emacs_event->modifiers = 0;
4790 EV_TRAILER (theEvent);
4794 - (void)newFrame: (id)sender
4796 struct frame *emacsframe = SELECTED_FRAME ();
4797 NSEvent *theEvent = [NSApp currentEvent];
4801 emacs_event->kind = NS_NONKEY_EVENT;
4802 emacs_event->code = KEY_NS_NEW_FRAME;
4803 emacs_event->modifiers = 0;
4804 EV_TRAILER (theEvent);
4808 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4809 - (BOOL) openFile: (NSString *)fileName
4811 struct frame *emacsframe = SELECTED_FRAME ();
4812 NSEvent *theEvent = [NSApp currentEvent];
4817 emacs_event->kind = NS_NONKEY_EVENT;
4818 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4819 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4820 ns_input_line = Qnil; /* can be start or cons start,end */
4821 emacs_event->modifiers =0;
4822 EV_TRAILER (theEvent);
4828 /* **************************************************************************
4830 EmacsApp delegate implementation
4832 ************************************************************************** */
4834 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4835 /* --------------------------------------------------------------------------
4836 When application is loaded, terminate event loop in ns_term_init
4837 -------------------------------------------------------------------------- */
4839 NSTRACE (applicationDidFinishLaunching);
4840 #ifdef NS_IMPL_GNUSTEP
4841 ((EmacsApp *)self)->applicationDidFinishLaunchingCalled = YES;
4843 [NSApp setServicesProvider: NSApp];
4845 [self antialiasThresholdDidChange:nil];
4846 #ifdef NS_IMPL_COCOA
4847 [[NSNotificationCenter defaultCenter]
4849 selector:@selector(antialiasThresholdDidChange:)
4850 name:NSAntialiasThresholdChangedNotification
4854 ns_send_appdefined (-2);
4857 - (void)antialiasThresholdDidChange:(NSNotification *)notification
4859 #ifdef NS_IMPL_COCOA
4860 macfont_update_antialias_threshold ();
4865 /* Termination sequences:
4868 MenuBar | File | Exit:
4869 Select Quit from App menubar:
4871 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4874 Select Quit from Dock menu:
4877 Cancel -> Nothing else
4881 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4886 - (void) terminate: (id)sender
4888 struct frame *emacsframe = SELECTED_FRAME ();
4893 emacs_event->kind = NS_NONKEY_EVENT;
4894 emacs_event->code = KEY_NS_POWER_OFF;
4895 emacs_event->arg = Qt; /* mark as non-key event */
4896 EV_TRAILER ((id)nil);
4900 runAlertPanel(NSString *title,
4901 NSString *msgFormat,
4902 NSString *defaultButton,
4903 NSString *alternateButton)
4905 #if !defined (NS_IMPL_COCOA) || \
4906 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
4907 return NSRunAlertPanel(title, msgFormat, defaultButton, alternateButton, nil)
4908 == NSAlertDefaultReturn;
4910 NSAlert *alert = [[NSAlert alloc] init];
4911 [alert setAlertStyle: NSCriticalAlertStyle];
4912 [alert setMessageText: msgFormat];
4913 [alert addButtonWithTitle: defaultButton];
4914 [alert addButtonWithTitle: alternateButton];
4915 NSInteger ret = [alert runModal];
4917 return ret == NSAlertFirstButtonReturn;
4922 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4926 if (NILP (ns_confirm_quit)) // || ns_shutdown_properly --> TO DO
4927 return NSTerminateNow;
4929 ret = runAlertPanel(ns_app_name,
4930 @"Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?",
4931 @"Save Buffers and Exit", @"Cancel");
4934 return NSTerminateNow;
4936 return NSTerminateCancel;
4937 return NSTerminateNow; /* just in case */
4941 not_in_argv (NSString *arg)
4944 const char *a = [arg UTF8String];
4945 for (k = 1; k < initial_argc; ++k)
4946 if (strcmp (a, initial_argv[k]) == 0) return 0;
4950 /* Notification from the Workspace to open a file */
4951 - (BOOL)application: sender openFile: (NSString *)file
4953 if (ns_do_open_file || not_in_argv (file))
4954 [ns_pending_files addObject: file];
4959 /* Open a file as a temporary file */
4960 - (BOOL)application: sender openTempFile: (NSString *)file
4962 if (ns_do_open_file || not_in_argv (file))
4963 [ns_pending_files addObject: file];
4968 /* Notification from the Workspace to open a file noninteractively (?) */
4969 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4971 if (ns_do_open_file || not_in_argv (file))
4972 [ns_pending_files addObject: file];
4976 /* Notification from the Workspace to open multiple files */
4977 - (void)application: sender openFiles: (NSArray *)fileList
4979 NSEnumerator *files = [fileList objectEnumerator];
4981 /* Don't open files from the command line unconditionally,
4982 Cocoa parses the command line wrong, --option value tries to open value
4983 if --option is the last option. */
4984 while ((file = [files nextObject]) != nil)
4985 if (ns_do_open_file || not_in_argv (file))
4986 [ns_pending_files addObject: file];
4988 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4993 /* Handle dock menu requests. */
4994 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
5000 /* TODO: these may help w/IO switching btwn terminal and NSApp */
5001 - (void)applicationWillBecomeActive: (NSNotification *)notification
5003 //ns_app_active=YES;
5005 - (void)applicationDidBecomeActive: (NSNotification *)notification
5007 NSTRACE (applicationDidBecomeActive);
5009 #ifdef NS_IMPL_GNUSTEP
5010 if (! applicationDidFinishLaunchingCalled)
5011 [self applicationDidFinishLaunching:notification];
5013 //ns_app_active=YES;
5015 ns_update_auto_hide_menu_bar ();
5016 // No constraining takes place when the application is not active.
5017 ns_constrain_all_frames ();
5019 - (void)applicationDidResignActive: (NSNotification *)notification
5022 ns_send_appdefined (-1);
5027 /* ==========================================================================
5029 EmacsApp aux handlers for managing event loop
5031 ========================================================================== */
5034 - (void)timeout_handler: (NSTimer *)timedEntry
5035 /* --------------------------------------------------------------------------
5036 The timeout specified to ns_select has passed.
5037 -------------------------------------------------------------------------- */
5039 /*NSTRACE (timeout_handler); */
5040 ns_send_appdefined (-2);
5043 #ifdef NS_IMPL_GNUSTEP
5044 - (void)sendFromMainThread:(id)unused
5046 ns_send_appdefined (nextappdefined);
5050 - (void)fd_handler:(id)unused
5051 /* --------------------------------------------------------------------------
5052 Check data waiting on file descriptors and terminate if so
5053 -------------------------------------------------------------------------- */
5056 int waiting = 1, nfds;
5059 fd_set readfds, writefds, *wfds;
5060 struct timespec timeout, *tmo;
5061 NSAutoreleasePool *pool = nil;
5063 /* NSTRACE (fd_handler); */
5068 pool = [[NSAutoreleasePool alloc] init];
5074 FD_SET (selfds[0], &fds);
5075 result = select (selfds[0]+1, &fds, NULL, NULL, NULL);
5076 if (result > 0 && read (selfds[0], &c, 1) == 1 && c == 'g')
5081 pthread_mutex_lock (&select_mutex);
5084 if (select_valid & SELECT_HAVE_READ)
5085 readfds = select_readfds;
5089 if (select_valid & SELECT_HAVE_WRITE)
5091 writefds = select_writefds;
5096 if (select_valid & SELECT_HAVE_TMO)
5098 timeout = select_timeout;
5104 pthread_mutex_unlock (&select_mutex);
5106 FD_SET (selfds[0], &readfds);
5107 if (selfds[0] >= nfds) nfds = selfds[0]+1;
5109 result = pselect (nfds, &readfds, wfds, NULL, tmo, NULL);
5112 ns_send_appdefined (-2);
5113 else if (result > 0)
5115 if (FD_ISSET (selfds[0], &readfds))
5117 if (read (selfds[0], &c, 1) == 1 && c == 's')
5122 pthread_mutex_lock (&select_mutex);
5123 if (select_valid & SELECT_HAVE_READ)
5124 select_readfds = readfds;
5125 if (select_valid & SELECT_HAVE_WRITE)
5126 select_writefds = writefds;
5127 if (select_valid & SELECT_HAVE_TMO)
5128 select_timeout = timeout;
5129 pthread_mutex_unlock (&select_mutex);
5131 ns_send_appdefined (result);
5141 /* ==========================================================================
5145 ========================================================================== */
5147 /* called from system: queue for next pass through event loop */
5148 - (void)requestService: (NSPasteboard *)pboard
5149 userData: (NSString *)userData
5150 error: (NSString **)error
5152 [ns_pending_service_names addObject: userData];
5153 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
5154 SSDATA (ns_string_from_pasteboard (pboard))]];
5158 /* called from ns_read_socket to clear queue */
5159 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
5161 struct frame *emacsframe = SELECTED_FRAME ();
5162 NSEvent *theEvent = [NSApp currentEvent];
5167 emacs_event->kind = NS_NONKEY_EVENT;
5168 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
5169 ns_input_spi_name = build_string ([name UTF8String]);
5170 ns_input_spi_arg = build_string ([arg UTF8String]);
5171 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5172 EV_TRAILER (theEvent);
5182 /* ==========================================================================
5184 EmacsView implementation
5186 ========================================================================== */
5189 @implementation EmacsView
5191 /* needed to inform when window closed from LISP */
5192 - (void) setWindowClosing: (BOOL)closing
5194 windowClosing = closing;
5200 NSTRACE (EmacsView_dealloc);
5202 if (fs_state == FULLSCREEN_BOTH)
5203 [nonfs_window release];
5208 /* called on font panel selection */
5209 - (void)changeFont: (id)sender
5211 NSEvent *e = [[self window] currentEvent];
5212 struct face *face = FRAME_DEFAULT_FACE (emacsframe);
5213 struct font *font = face->font;
5218 NSTRACE (changeFont);
5223 #ifdef NS_IMPL_GNUSTEP
5224 nsfont = ((struct nsfont_info *)font)->nsfont;
5226 #ifdef NS_IMPL_COCOA
5227 nsfont = (NSFont *) macfont_get_nsctfont (font);
5230 if ((newFont = [sender convertFont: nsfont]))
5232 SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
5234 emacs_event->kind = NS_NONKEY_EVENT;
5235 emacs_event->modifiers = 0;
5236 emacs_event->code = KEY_NS_CHANGE_FONT;
5238 size = [newFont pointSize];
5239 ns_input_fontsize = make_number (lrint (size));
5240 ns_input_font = build_string ([[newFont familyName] UTF8String]);
5246 - (BOOL)acceptsFirstResponder
5248 NSTRACE (acceptsFirstResponder);
5253 - (void)resetCursorRects
5255 NSRect visible = [self visibleRect];
5256 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
5257 NSTRACE (resetCursorRects);
5259 if (currentCursor == nil)
5260 currentCursor = [NSCursor arrowCursor];
5262 if (!NSIsEmptyRect (visible))
5263 [self addCursorRect: visible cursor: currentCursor];
5264 [currentCursor setOnMouseEntered: YES];
5269 /*****************************************************************************/
5270 /* Keyboard handling. */
5273 - (void)keyDown: (NSEvent *)theEvent
5275 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5277 unsigned fnKeysym = 0;
5278 static NSMutableArray *nsEvArray;
5280 unsigned int flags = [theEvent modifierFlags];
5284 /* Rhapsody and OS X give up and down events for the arrow keys */
5285 if (ns_fake_keydown == YES)
5286 ns_fake_keydown = NO;
5287 else if ([theEvent type] != NSKeyDown)
5293 if (![[self window] isKeyWindow]
5294 && [[theEvent window] isKindOfClass: [EmacsWindow class]]
5295 /* we must avoid an infinite loop here. */
5296 && (EmacsView *)[[theEvent window] delegate] != self)
5298 /* XXX: There is an occasional condition in which, when Emacs display
5299 updates a different frame from the current one, and temporarily
5300 selects it, then processes some interrupt-driven input
5301 (dispnew.c:3878), OS will send the event to the correct NSWindow, but
5302 for some reason that window has its first responder set to the NSView
5303 most recently updated (I guess), which is not the correct one. */
5304 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
5308 if (nsEvArray == nil)
5309 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
5311 [NSCursor setHiddenUntilMouseMoves: YES];
5313 if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
5315 clear_mouse_face (hlinfo);
5316 hlinfo->mouse_face_hidden = 1;
5319 if (!processingCompose)
5321 /* When using screen sharing, no left or right information is sent,
5322 so use Left key in those cases. */
5323 int is_left_key, is_right_key;
5325 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
5326 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
5328 /* (Carbon way: [theEvent keyCode]) */
5330 /* is it a "function key"? */
5331 /* Note: Sometimes a plain key will have the NSNumericPadKeyMask
5332 flag set (this is probably a bug in the OS).
5334 if (code < 0x00ff && (flags&NSNumericPadKeyMask))
5336 fnKeysym = ns_convert_key ([theEvent keyCode] | NSNumericPadKeyMask);
5340 fnKeysym = ns_convert_key (code);
5345 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
5346 because Emacs treats Delete and KP-Delete same (in simple.el). */
5347 if ((fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
5348 #ifdef NS_IMPL_GNUSTEP
5349 /* GNUstep uses incompatible keycodes, even for those that are
5350 supposed to be hardware independent. Just check for delete.
5351 Keypad delete does not have keysym 0xFFFF.
5352 See http://savannah.gnu.org/bugs/?25395
5354 || (fnKeysym == 0xFFFF && code == 127)
5357 code = 0xFF08; /* backspace */
5362 /* are there modifiers? */
5363 emacs_event->modifiers = 0;
5365 if (flags & NSHelpKeyMask)
5366 emacs_event->modifiers |= hyper_modifier;
5368 if (flags & NSShiftKeyMask)
5369 emacs_event->modifiers |= shift_modifier;
5371 is_right_key = (flags & NSRightCommandKeyMask) == NSRightCommandKeyMask;
5372 is_left_key = (flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask
5373 || (! is_right_key && (flags & NSCommandKeyMask) == NSCommandKeyMask);
5376 emacs_event->modifiers |= parse_solitary_modifier
5377 (EQ (ns_right_command_modifier, Qleft)
5378 ? ns_command_modifier
5379 : ns_right_command_modifier);
5383 emacs_event->modifiers |= parse_solitary_modifier
5384 (ns_command_modifier);
5386 /* if super (default), take input manager's word so things like
5387 dvorak / qwerty layout work */
5388 if (EQ (ns_command_modifier, Qsuper)
5390 && [[theEvent characters] length] != 0)
5392 /* XXX: the code we get will be unshifted, so if we have
5393 a shift modifier, must convert ourselves */
5394 if (!(flags & NSShiftKeyMask))
5395 code = [[theEvent characters] characterAtIndex: 0];
5397 /* this is ugly and also requires linking w/Carbon framework
5398 (for LMGetKbdType) so for now leave this rare (?) case
5399 undealt with.. in future look into CGEvent methods */
5402 long smv = GetScriptManagerVariable (smKeyScript);
5403 Handle uchrHandle = GetResource
5404 ('uchr', GetScriptVariable (smv, smScriptKeys));
5406 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
5407 [[theEvent characters] characterAtIndex: 0],
5408 kUCKeyActionDisplay,
5409 (flags & ~NSCommandKeyMask) >> 8,
5410 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
5411 &dummy, 1, &dummy, &code);
5418 is_right_key = (flags & NSRightControlKeyMask) == NSRightControlKeyMask;
5419 is_left_key = (flags & NSLeftControlKeyMask) == NSLeftControlKeyMask
5420 || (! is_right_key && (flags & NSControlKeyMask) == NSControlKeyMask);
5423 emacs_event->modifiers |= parse_solitary_modifier
5424 (EQ (ns_right_control_modifier, Qleft)
5425 ? ns_control_modifier
5426 : ns_right_control_modifier);
5429 emacs_event->modifiers |= parse_solitary_modifier
5430 (ns_control_modifier);
5432 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
5433 emacs_event->modifiers |=
5434 parse_solitary_modifier (ns_function_modifier);
5436 left_is_none = NILP (ns_alternate_modifier)
5437 || EQ (ns_alternate_modifier, Qnone);
5439 is_right_key = (flags & NSRightAlternateKeyMask)
5440 == NSRightAlternateKeyMask;
5441 is_left_key = (flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask
5443 && (flags & NSAlternateKeyMask) == NSAlternateKeyMask);
5447 if ((NILP (ns_right_alternate_modifier)
5448 || EQ (ns_right_alternate_modifier, Qnone)
5449 || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
5451 { /* accept pre-interp alt comb */
5452 if ([[theEvent characters] length] > 0)
5453 code = [[theEvent characters] characterAtIndex: 0];
5454 /*HACK: clear lone shift modifier to stop next if from firing */
5455 if (emacs_event->modifiers == shift_modifier)
5456 emacs_event->modifiers = 0;
5459 emacs_event->modifiers |= parse_solitary_modifier
5460 (EQ (ns_right_alternate_modifier, Qleft)
5461 ? ns_alternate_modifier
5462 : ns_right_alternate_modifier);
5465 if (is_left_key) /* default = meta */
5467 if (left_is_none && !fnKeysym)
5468 { /* accept pre-interp alt comb */
5469 if ([[theEvent characters] length] > 0)
5470 code = [[theEvent characters] characterAtIndex: 0];
5471 /*HACK: clear lone shift modifier to stop next if from firing */
5472 if (emacs_event->modifiers == shift_modifier)
5473 emacs_event->modifiers = 0;
5476 emacs_event->modifiers |=
5477 parse_solitary_modifier (ns_alternate_modifier);
5481 fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
5482 code, fnKeysym, flags, emacs_event->modifiers);
5484 /* if it was a function key or had modifiers, pass it directly to emacs */
5485 if (fnKeysym || (emacs_event->modifiers
5486 && (emacs_event->modifiers != shift_modifier)
5487 && [[theEvent charactersIgnoringModifiers] length] > 0))
5488 /*[[theEvent characters] length] */
5490 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5492 code |= (1<<28)|(3<<16);
5493 else if (code == 0x7f)
5494 code |= (1<<28)|(3<<16);
5496 emacs_event->kind = code > 0xFF
5497 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5499 emacs_event->code = code;
5500 EV_TRAILER (theEvent);
5501 processingCompose = NO;
5507 if (NS_KEYLOG && !processingCompose)
5508 fprintf (stderr, "keyDown: Begin compose sequence.\n");
5510 processingCompose = YES;
5511 [nsEvArray addObject: theEvent];
5512 [self interpretKeyEvents: nsEvArray];
5513 [nsEvArray removeObject: theEvent];
5517 #ifdef NS_IMPL_COCOA
5518 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
5519 decided not to send key-down for.
5520 See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
5521 This only applies on Tiger and earlier.
5522 If it matches one of these, send it on to keyDown. */
5523 -(void)keyUp: (NSEvent *)theEvent
5525 int flags = [theEvent modifierFlags];
5526 int code = [theEvent keyCode];
5527 if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
5528 code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
5531 fprintf (stderr, "keyUp: passed test");
5532 ns_fake_keydown = YES;
5533 [self keyDown: theEvent];
5539 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
5542 /* <NSTextInput>: called when done composing;
5543 NOTE: also called when we delete over working text, followed immed.
5544 by doCommandBySelector: deleteBackward: */
5545 - (void)insertText: (id)aString
5548 int len = [(NSString *)aString length];
5552 NSLog (@"insertText '%@'\tlen = %d", aString, len);
5553 processingCompose = NO;
5558 /* first, clear any working text */
5559 if (workingText != nil)
5560 [self deleteWorkingText];
5562 /* now insert the string as keystrokes */
5563 for (i =0; i<len; i++)
5565 code = [aString characterAtIndex: i];
5566 /* TODO: still need this? */
5568 code = '~'; /* 0x7E */
5569 if (code != 32) /* Space */
5570 emacs_event->modifiers = 0;
5572 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5573 emacs_event->code = code;
5574 EV_TRAILER ((id)nil);
5579 /* <NSTextInput>: inserts display of composing characters */
5580 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
5582 NSString *str = [aString respondsToSelector: @selector (string)] ?
5583 [aString string] : aString;
5585 NSLog (@"setMarkedText '%@' len =%lu range %lu from %lu",
5586 str, (unsigned long)[str length],
5587 (unsigned long)selRange.length,
5588 (unsigned long)selRange.location);
5590 if (workingText != nil)
5591 [self deleteWorkingText];
5592 if ([str length] == 0)
5598 processingCompose = YES;
5599 workingText = [str copy];
5600 ns_working_text = build_string ([workingText UTF8String]);
5602 emacs_event->kind = NS_TEXT_EVENT;
5603 emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
5604 EV_TRAILER ((id)nil);
5608 /* delete display of composing characters [not in <NSTextInput>] */
5609 - (void)deleteWorkingText
5611 if (workingText == nil)
5614 NSLog(@"deleteWorkingText len =%lu\n", (unsigned long)[workingText length]);
5615 [workingText release];
5617 processingCompose = NO;
5622 emacs_event->kind = NS_TEXT_EVENT;
5623 emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
5624 EV_TRAILER ((id)nil);
5628 - (BOOL)hasMarkedText
5630 return workingText != nil;
5634 - (NSRange)markedRange
5636 NSRange rng = workingText != nil
5637 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
5639 NSLog (@"markedRange request");
5647 NSLog (@"unmark (accept) text");
5648 [self deleteWorkingText];
5649 processingCompose = NO;
5653 /* used to position char selection windows, etc. */
5654 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
5658 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
5660 NSLog (@"firstRectForCharRange request");
5662 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
5663 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
5664 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
5665 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
5666 +FRAME_LINE_HEIGHT (emacsframe));
5668 pt = [self convertPoint: pt toView: nil];
5669 pt = [[self window] convertBaseToScreen: pt];
5675 - (NSInteger)conversationIdentifier
5677 return (NSInteger)self;
5681 - (void)doCommandBySelector: (SEL)aSelector
5684 NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
5686 processingCompose = NO;
5687 if (aSelector == @selector (deleteBackward:))
5689 /* happens when user backspaces over an ongoing composition:
5690 throw a 'delete' into the event queue */
5693 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5694 emacs_event->code = 0xFF08;
5695 EV_TRAILER ((id)nil);
5699 - (NSArray *)validAttributesForMarkedText
5701 static NSArray *arr = nil;
5702 if (arr == nil) arr = [NSArray new];
5703 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
5707 - (NSRange)selectedRange
5710 NSLog (@"selectedRange request");
5711 return NSMakeRange (NSNotFound, 0);
5714 #if defined (NS_IMPL_COCOA) || GNUSTEP_GUI_MAJOR_VERSION > 0 || \
5715 GNUSTEP_GUI_MINOR_VERSION > 22
5716 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
5718 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
5722 NSLog (@"characterIndexForPoint request");
5726 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
5728 static NSAttributedString *str = nil;
5729 if (str == nil) str = [NSAttributedString new];
5731 NSLog (@"attributedSubstringFromRange request");
5735 /* End <NSTextInput> impl. */
5736 /*****************************************************************************/
5739 /* This is what happens when the user presses a mouse button. */
5740 - (void)mouseDown: (NSEvent *)theEvent
5742 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
5743 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5745 NSTRACE (mouseDown);
5747 [self deleteWorkingText];
5752 dpyinfo->last_mouse_frame = emacsframe;
5753 /* appears to be needed to prevent spurious movement events generated on
5755 emacsframe->mouse_moved = 0;
5757 if ([theEvent type] == NSScrollWheel)
5759 CGFloat delta = [theEvent deltaY];
5760 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
5763 delta = [theEvent deltaX];
5766 NSTRACE (deltaIsZero);
5769 emacs_event->kind = HORIZ_WHEEL_EVENT;
5772 emacs_event->kind = WHEEL_EVENT;
5774 emacs_event->code = 0;
5775 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
5776 ((delta > 0) ? up_modifier : down_modifier);
5780 emacs_event->kind = MOUSE_CLICK_EVENT;
5781 emacs_event->code = EV_BUTTON (theEvent);
5782 emacs_event->modifiers = EV_MODIFIERS (theEvent)
5783 | EV_UDMODIFIERS (theEvent);
5785 XSETINT (emacs_event->x, lrint (p.x));
5786 XSETINT (emacs_event->y, lrint (p.y));
5787 EV_TRAILER (theEvent);
5791 - (void)rightMouseDown: (NSEvent *)theEvent
5793 NSTRACE (rightMouseDown);
5794 [self mouseDown: theEvent];
5798 - (void)otherMouseDown: (NSEvent *)theEvent
5800 NSTRACE (otherMouseDown);
5801 [self mouseDown: theEvent];
5805 - (void)mouseUp: (NSEvent *)theEvent
5808 [self mouseDown: theEvent];
5812 - (void)rightMouseUp: (NSEvent *)theEvent
5814 NSTRACE (rightMouseUp);
5815 [self mouseDown: theEvent];
5819 - (void)otherMouseUp: (NSEvent *)theEvent
5821 NSTRACE (otherMouseUp);
5822 [self mouseDown: theEvent];
5826 - (void) scrollWheel: (NSEvent *)theEvent
5828 NSTRACE (scrollWheel);
5829 [self mouseDown: theEvent];
5833 /* Tell emacs the mouse has moved. */
5834 - (void)mouseMoved: (NSEvent *)e
5836 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5837 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
5841 // NSTRACE (mouseMoved);
5843 dpyinfo->last_mouse_movement_time = EV_TIMESTAMP (e);
5844 pt = [self convertPoint: [e locationInWindow] fromView: nil];
5845 dpyinfo->last_mouse_motion_x = pt.x;
5846 dpyinfo->last_mouse_motion_y = pt.y;
5848 /* update any mouse face */
5849 if (hlinfo->mouse_face_hidden)
5851 hlinfo->mouse_face_hidden = 0;
5852 clear_mouse_face (hlinfo);
5855 /* tooltip handling */
5856 previous_help_echo_string = help_echo_string;
5857 help_echo_string = Qnil;
5859 if (!NILP (Vmouse_autoselect_window))
5861 NSTRACE (mouse_autoselect_window);
5862 static Lisp_Object last_mouse_window;
5864 = window_from_coordinates (emacsframe, pt.x, pt.y, 0, 0);
5866 if (WINDOWP (window)
5867 && !EQ (window, last_mouse_window)
5868 && !EQ (window, selected_window)
5869 && (focus_follows_mouse
5870 || (EQ (XWINDOW (window)->frame,
5871 XWINDOW (selected_window)->frame))))
5873 NSTRACE (in_window);
5874 emacs_event->kind = SELECT_WINDOW_EVENT;
5875 emacs_event->frame_or_window = window;
5878 /* Remember the last window where we saw the mouse. */
5879 last_mouse_window = window;
5882 if (!note_mouse_movement (emacsframe, pt.x, pt.y))
5883 help_echo_string = previous_help_echo_string;
5885 XSETFRAME (frame, emacsframe);
5886 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
5888 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
5889 (note_mouse_highlight), which is called through the
5890 note_mouse_movement () call above */
5891 any_help_event_p = YES;
5892 gen_help_event (help_echo_string, frame, help_echo_window,
5893 help_echo_object, help_echo_pos);
5896 if (emacsframe->mouse_moved && send_appdefined)
5897 ns_send_appdefined (-1);
5901 - (void)mouseDragged: (NSEvent *)e
5903 NSTRACE (mouseDragged);
5904 [self mouseMoved: e];
5908 - (void)rightMouseDragged: (NSEvent *)e
5910 NSTRACE (rightMouseDragged);
5911 [self mouseMoved: e];
5915 - (void)otherMouseDragged: (NSEvent *)e
5917 NSTRACE (otherMouseDragged);
5918 [self mouseMoved: e];
5922 - (BOOL)windowShouldClose: (id)sender
5924 NSEvent *e =[[self window] currentEvent];
5926 NSTRACE (windowShouldClose);
5927 windowClosing = YES;
5930 emacs_event->kind = DELETE_WINDOW_EVENT;
5931 emacs_event->modifiers = 0;
5932 emacs_event->code = 0;
5934 /* Don't close this window, let this be done from lisp code. */
5938 - (void) updateFrameSize: (BOOL) delay;
5940 NSWindow *window = [self window];
5941 NSRect wr = [window frame];
5943 int oldc = cols, oldr = rows;
5944 int oldw = FRAME_PIXEL_WIDTH (emacsframe);
5945 int oldh = FRAME_PIXEL_HEIGHT (emacsframe);
5948 NSTRACE (updateFrameSize);
5949 NSTRACE_SIZE ("Original size", NSMakeSize (oldw, oldh));
5951 if (! [self isFullscreen])
5953 #ifdef NS_IMPL_GNUSTEP
5954 // GNUstep does not always update the tool bar height. Force it.
5955 if (toolbar && [toolbar isVisible])
5956 update_frame_tool_bar (emacsframe);
5959 extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5960 + FRAME_TOOLBAR_HEIGHT (emacsframe);
5963 if (wait_for_tool_bar)
5965 if (FRAME_TOOLBAR_HEIGHT (emacsframe) == 0)
5967 wait_for_tool_bar = NO;
5970 neww = (int)wr.size.width - emacsframe->border_width;
5971 newh = (int)wr.size.height - extra;
5973 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, neww);
5974 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, newh);
5976 if (cols < MINWIDTH)
5979 if (rows < MINHEIGHT)
5982 if (oldr != rows || oldc != cols || neww != oldw || newh != oldh)
5984 NSView *view = FRAME_NS_VIEW (emacsframe);
5985 NSWindow *win = [view window];
5986 NSSize sz = [win resizeIncrements];
5988 change_frame_size (emacsframe,
5989 FRAME_PIXEL_TO_TEXT_WIDTH (emacsframe, neww),
5990 FRAME_PIXEL_TO_TEXT_HEIGHT (emacsframe, newh),
5992 SET_FRAME_GARBAGED (emacsframe);
5993 cancel_mouse_face (emacsframe);
5995 // Did resize increments change because of a font change?
5996 if (sz.width != FRAME_COLUMN_WIDTH (emacsframe) ||
5997 sz.height != FRAME_LINE_HEIGHT (emacsframe) ||
5998 (frame_resize_pixelwise && sz.width != 1))
6000 sz.width = frame_resize_pixelwise
6001 ? 1 : FRAME_COLUMN_WIDTH (emacsframe);
6002 sz.height = frame_resize_pixelwise
6003 ? 1 : FRAME_LINE_HEIGHT (emacsframe);
6004 [win setResizeIncrements: sz];
6006 NSTRACE_SIZE ("New size", NSMakeSize (neww, newh));
6009 [view setFrame: NSMakeRect (0, 0, neww, newh)];
6010 [self windowDidMove:nil]; // Update top/left.
6014 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
6015 /* normalize frame to gridded text size */
6019 NSTRACE (windowWillResize);
6020 NSTRACE_SIZE ("Original size", frameSize);
6021 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
6023 if (fs_state == FULLSCREEN_MAXIMIZED
6024 && (maximized_width != (int)frameSize.width
6025 || maximized_height != (int)frameSize.height))
6026 [self setFSValue: FULLSCREEN_NONE];
6027 else if (fs_state == FULLSCREEN_WIDTH
6028 && maximized_width != (int)frameSize.width)
6029 [self setFSValue: FULLSCREEN_NONE];
6030 else if (fs_state == FULLSCREEN_HEIGHT
6031 && maximized_height != (int)frameSize.height)
6032 [self setFSValue: FULLSCREEN_NONE];
6033 if (fs_state == FULLSCREEN_NONE)
6034 maximized_width = maximized_height = -1;
6036 if (! [self isFullscreen])
6038 extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
6039 + FRAME_TOOLBAR_HEIGHT (emacsframe);
6042 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, frameSize.width);
6043 if (cols < MINWIDTH)
6046 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe,
6047 frameSize.height - extra);
6048 if (rows < MINHEIGHT)
6050 #ifdef NS_IMPL_COCOA
6052 /* this sets window title to have size in it; the wm does this under GS */
6053 NSRect r = [[self window] frame];
6054 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
6062 else if (fs_state == FULLSCREEN_NONE && ! maximizing_resize)
6065 NSWindow *window = [self window];
6068 char *t = strdup ([[[self window] title] UTF8String]);
6069 char *pos = strstr (t, " — ");
6074 size_title = xmalloc (strlen (old_title) + 40);
6075 esprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
6076 [window setTitle: [NSString stringWithUTF8String: size_title]];
6081 #endif /* NS_IMPL_COCOA */
6082 /*fprintf (stderr," ...size became %.0f x %.0f (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
6088 - (void)windowDidResize: (NSNotification *)notification
6090 if (! [self fsIsNative])
6092 NSWindow *theWindow = [notification object];
6093 /* We can get notification on the non-FS window when in
6095 if ([self window] != theWindow) return;
6098 #ifdef NS_IMPL_GNUSTEP
6099 NSWindow *theWindow = [notification object];
6101 /* In GNUstep, at least currently, it's possible to get a didResize
6102 without getting a willResize.. therefore we need to act as if we got
6103 the willResize now */
6104 NSSize sz = [theWindow frame].size;
6105 sz = [self windowWillResize: theWindow toSize: sz];
6106 #endif /* NS_IMPL_GNUSTEP */
6108 NSTRACE (windowDidResize);
6109 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
6111 if (cols > 0 && rows > 0)
6113 [self updateFrameSize: YES];
6116 ns_send_appdefined (-1);
6119 #ifdef NS_IMPL_COCOA
6120 - (void)viewDidEndLiveResize
6122 [super viewDidEndLiveResize];
6125 [[self window] setTitle: [NSString stringWithUTF8String: old_title]];
6129 maximizing_resize = NO;
6131 #endif /* NS_IMPL_COCOA */
6134 - (void)windowDidBecomeKey: (NSNotification *)notification
6135 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6137 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6138 struct frame *old_focus = dpyinfo->x_focus_frame;
6140 NSTRACE (windowDidBecomeKey);
6142 if (emacsframe != old_focus)
6143 dpyinfo->x_focus_frame = emacsframe;
6145 ns_frame_rehighlight (emacsframe);
6149 emacs_event->kind = FOCUS_IN_EVENT;
6150 EV_TRAILER ((id)nil);
6155 - (void)windowDidResignKey: (NSNotification *)notification
6156 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6158 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6159 BOOL is_focus_frame = dpyinfo->x_focus_frame == emacsframe;
6160 NSTRACE (windowDidResignKey);
6163 dpyinfo->x_focus_frame = 0;
6165 emacsframe->mouse_moved = 0;
6166 ns_frame_rehighlight (emacsframe);
6168 /* FIXME: for some reason needed on second and subsequent clicks away
6169 from sole-frame Emacs to get hollow box to show */
6170 if (!windowClosing && [[self window] isVisible] == YES)
6172 x_update_cursor (emacsframe, 1);
6173 x_set_frame_alpha (emacsframe);
6176 if (any_help_event_p)
6179 XSETFRAME (frame, emacsframe);
6180 help_echo_string = Qnil;
6181 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
6184 if (emacs_event && is_focus_frame)
6186 [self deleteWorkingText];
6187 emacs_event->kind = FOCUS_OUT_EVENT;
6188 EV_TRAILER ((id)nil);
6193 - (void)windowWillMiniaturize: sender
6195 NSTRACE (windowWillMiniaturize);
6211 - initFrameFromEmacs: (struct frame *)f
6220 NSTRACE (initFrameFromEmacs);
6223 processingCompose = NO;
6224 scrollbarsNeedingUpdate = 0;
6225 fs_state = FULLSCREEN_NONE;
6226 fs_before_fs = next_maximized = -1;
6227 #ifdef HAVE_NATIVE_FS
6228 fs_is_native = ns_use_native_fullscreen;
6232 maximized_width = maximized_height = -1;
6235 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
6237 ns_userRect = NSMakeRect (0, 0, 0, 0);
6238 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
6239 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
6240 [self initWithFrame: r];
6241 [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
6243 FRAME_NS_VIEW (f) = self;
6245 #ifdef NS_IMPL_COCOA
6247 maximizing_resize = NO;
6250 win = [[EmacsWindow alloc]
6251 initWithContentRect: r
6252 styleMask: (NSResizableWindowMask |
6253 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6254 NSTitledWindowMask |
6256 NSMiniaturizableWindowMask |
6257 NSClosableWindowMask)
6258 backing: NSBackingStoreBuffered
6261 #ifdef HAVE_NATIVE_FS
6262 [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
6266 bwidth = f->border_width = wr.size.width - r.size.width;
6267 tibar_height = FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
6269 [win setAcceptsMouseMovedEvents: YES];
6270 [win setDelegate: self];
6271 #if !defined (NS_IMPL_COCOA) || \
6272 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6273 [win useOptimizedDrawing: YES];
6275 sz.width = frame_resize_pixelwise ? 1 : FRAME_COLUMN_WIDTH (f);
6276 sz.height = frame_resize_pixelwise ? 1 : FRAME_LINE_HEIGHT (f);
6277 [win setResizeIncrements: sz];
6279 [[win contentView] addSubview: self];
6282 [self registerForDraggedTypes: ns_drag_types];
6285 name = [NSString stringWithUTF8String:
6286 NILP (tem) ? "Emacs" : SSDATA (tem)];
6287 [win setTitle: name];
6289 /* toolbar support */
6290 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
6291 [NSString stringWithFormat: @"Emacs Frame %d",
6293 [win setToolbar: toolbar];
6294 [toolbar setVisible: NO];
6296 /* Don't set frame garbaged until tool bar is up to date?
6297 This avoids an extra clear and redraw (flicker) at frame creation. */
6298 if (FRAME_EXTERNAL_TOOL_BAR (f)) wait_for_tool_bar = YES;
6299 else wait_for_tool_bar = NO;
6302 #ifdef NS_IMPL_COCOA
6304 NSButton *toggleButton;
6305 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
6306 [toggleButton setTarget: self];
6307 [toggleButton setAction: @selector (toggleToolbar: )];
6310 FRAME_TOOLBAR_HEIGHT (f) = 0;
6314 [win setMiniwindowTitle:
6315 [NSString stringWithUTF8String: SSDATA (tem)]];
6318 NSScreen *screen = [win screen];
6321 [win setFrameTopLeftPoint: NSMakePoint
6322 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
6323 IN_BOUND (-SCREENMAX,
6324 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
6327 [win makeFirstResponder: self];
6329 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6330 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
6331 [win setBackgroundColor: col];
6332 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6333 [win setOpaque: NO];
6335 #if !defined (NS_IMPL_COCOA) || \
6336 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6337 [self allocateGState];
6339 [NSApp registerServicesMenuSendTypes: ns_send_types
6347 - (void)windowDidMove: sender
6349 NSWindow *win = [self window];
6350 NSRect r = [win frame];
6351 NSArray *screens = [NSScreen screens];
6352 NSScreen *screen = [screens objectAtIndex: 0];
6354 NSTRACE (windowDidMove);
6356 if (!emacsframe->output_data.ns)
6360 emacsframe->left_pos = r.origin.x;
6361 emacsframe->top_pos =
6362 [screen frame].size.height - (r.origin.y + r.size.height);
6367 /* Called AFTER method below, but before our windowWillResize call there leads
6368 to windowDidResize -> x_set_window_size. Update emacs' notion of frame
6369 location so set_window_size moves the frame. */
6370 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
6372 emacsframe->output_data.ns->zooming = 1;
6377 /* Override to do something slightly nonstandard, but nice. First click on
6378 zoom button will zoom vertically. Second will zoom completely. Third
6379 returns to original. */
6380 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
6381 defaultFrame:(NSRect)defaultFrame
6383 NSRect result = [sender frame];
6385 NSTRACE (windowWillUseStandardFrame);
6387 if (fs_before_fs != -1) /* Entering fullscreen */
6389 result = defaultFrame;
6391 else if (next_maximized == FULLSCREEN_HEIGHT
6392 || (next_maximized == -1
6393 && abs ((int)(defaultFrame.size.height - result.size.height))
6394 > FRAME_LINE_HEIGHT (emacsframe)))
6397 ns_userRect = result;
6398 maximized_height = result.size.height = defaultFrame.size.height;
6399 maximized_width = -1;
6400 result.origin.y = defaultFrame.origin.y;
6401 [self setFSValue: FULLSCREEN_HEIGHT];
6402 #ifdef NS_IMPL_COCOA
6403 maximizing_resize = YES;
6406 else if (next_maximized == FULLSCREEN_WIDTH)
6408 ns_userRect = result;
6409 maximized_width = result.size.width = defaultFrame.size.width;
6410 maximized_height = -1;
6411 result.origin.x = defaultFrame.origin.x;
6412 [self setFSValue: FULLSCREEN_WIDTH];
6414 else if (next_maximized == FULLSCREEN_MAXIMIZED
6415 || (next_maximized == -1
6416 && abs ((int)(defaultFrame.size.width - result.size.width))
6417 > FRAME_COLUMN_WIDTH (emacsframe)))
6419 result = defaultFrame; /* second click */
6420 maximized_width = result.size.width;
6421 maximized_height = result.size.height;
6422 [self setFSValue: FULLSCREEN_MAXIMIZED];
6423 #ifdef NS_IMPL_COCOA
6424 maximizing_resize = YES;
6430 result = ns_userRect.size.height ? ns_userRect : result;
6431 ns_userRect = NSMakeRect (0, 0, 0, 0);
6432 #ifdef NS_IMPL_COCOA
6433 maximizing_resize = fs_state != FULLSCREEN_NONE;
6435 [self setFSValue: FULLSCREEN_NONE];
6436 maximized_width = maximized_height = -1;
6439 if (fs_before_fs == -1) next_maximized = -1;
6440 [self windowWillResize: sender toSize: result.size];
6445 - (void)windowDidDeminiaturize: sender
6447 NSTRACE (windowDidDeminiaturize);
6448 if (!emacsframe->output_data.ns)
6451 SET_FRAME_ICONIFIED (emacsframe, 0);
6452 SET_FRAME_VISIBLE (emacsframe, 1);
6453 windows_or_buffers_changed = 63;
6457 emacs_event->kind = DEICONIFY_EVENT;
6458 EV_TRAILER ((id)nil);
6463 - (void)windowDidExpose: sender
6465 NSTRACE (windowDidExpose);
6466 if (!emacsframe->output_data.ns)
6469 SET_FRAME_VISIBLE (emacsframe, 1);
6470 SET_FRAME_GARBAGED (emacsframe);
6472 if (send_appdefined)
6473 ns_send_appdefined (-1);
6477 - (void)windowDidMiniaturize: sender
6479 NSTRACE (windowDidMiniaturize);
6480 if (!emacsframe->output_data.ns)
6483 SET_FRAME_ICONIFIED (emacsframe, 1);
6484 SET_FRAME_VISIBLE (emacsframe, 0);
6488 emacs_event->kind = ICONIFY_EVENT;
6489 EV_TRAILER ((id)nil);
6493 #ifdef HAVE_NATIVE_FS
6494 - (NSApplicationPresentationOptions)window:(NSWindow *)window
6495 willUseFullScreenPresentationOptions:
6496 (NSApplicationPresentationOptions)proposedOptions
6498 return proposedOptions|NSApplicationPresentationAutoHideToolbar;
6502 - (void)windowWillEnterFullScreen:(NSNotification *)notification
6504 fs_before_fs = fs_state;
6507 - (void)windowDidEnterFullScreen:(NSNotification *)notification
6509 [self setFSValue: FULLSCREEN_BOTH];
6510 if (! [self fsIsNative])
6512 [self windowDidBecomeKey:notification];
6513 [nonfs_window orderOut:self];
6517 BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (emacsframe) ? YES : NO;
6518 #ifdef NS_IMPL_COCOA
6519 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6520 unsigned val = (unsigned)[NSApp presentationOptions];
6522 // OSX 10.7 bug fix, the menu won't appear without this.
6523 // val is non-zero on other OSX versions.
6526 NSApplicationPresentationOptions options
6527 = NSApplicationPresentationAutoHideDock
6528 | NSApplicationPresentationAutoHideMenuBar
6529 | NSApplicationPresentationFullScreen
6530 | NSApplicationPresentationAutoHideToolbar;
6532 [NSApp setPresentationOptions: options];
6536 [toolbar setVisible:tbar_visible];
6540 - (void)windowWillExitFullScreen:(NSNotification *)notification
6542 if (next_maximized != -1)
6543 fs_before_fs = next_maximized;
6546 - (void)windowDidExitFullScreen:(NSNotification *)notification
6548 [self setFSValue: fs_before_fs];
6550 #ifdef HAVE_NATIVE_FS
6551 [self updateCollectionBehavior];
6553 if (FRAME_EXTERNAL_TOOL_BAR (emacsframe))
6555 [toolbar setVisible:YES];
6556 update_frame_tool_bar (emacsframe);
6557 [self updateFrameSize:YES];
6558 [[self window] display];
6561 [toolbar setVisible:NO];
6563 if (next_maximized != -1)
6564 [[self window] performZoom:self];
6569 return fs_is_native;
6572 - (BOOL)isFullscreen
6574 if (! fs_is_native) return nonfs_window != nil;
6575 #ifdef HAVE_NATIVE_FS
6576 return ([[self window] styleMask] & NSFullScreenWindowMask) != 0;
6582 #ifdef HAVE_NATIVE_FS
6583 - (void)updateCollectionBehavior
6585 if (! [self isFullscreen])
6587 NSWindow *win = [self window];
6588 NSWindowCollectionBehavior b = [win collectionBehavior];
6589 if (ns_use_native_fullscreen)
6590 b |= NSWindowCollectionBehaviorFullScreenPrimary;
6592 b &= ~NSWindowCollectionBehaviorFullScreenPrimary;
6594 [win setCollectionBehavior: b];
6595 fs_is_native = ns_use_native_fullscreen;
6600 - (void)toggleFullScreen: (id)sender
6611 #ifdef HAVE_NATIVE_FS
6612 [[self window] toggleFullScreen:sender];
6618 onFirstScreen = [[w screen] isEqual:[[NSScreen screens] objectAtIndex:0]];
6621 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6622 (FRAME_DEFAULT_FACE (f)),
6625 sz.width = frame_resize_pixelwise ? 1 : FRAME_COLUMN_WIDTH (f);
6626 sz.height = frame_resize_pixelwise ? 1 : FRAME_LINE_HEIGHT (f);
6628 if (fs_state != FULLSCREEN_BOTH)
6630 NSScreen *screen = [w screen];
6632 #if defined (NS_IMPL_COCOA) && \
6633 MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
6634 /* Hide ghost menu bar on secondary monitor? */
6635 if (! onFirstScreen)
6636 onFirstScreen = [NSScreen screensHaveSeparateSpaces];
6638 /* Hide dock and menubar if we are on the primary screen. */
6641 #ifdef NS_IMPL_COCOA
6642 NSApplicationPresentationOptions options
6643 = NSApplicationPresentationAutoHideDock
6644 | NSApplicationPresentationAutoHideMenuBar;
6646 [NSApp setPresentationOptions: options];
6648 [NSMenu setMenuBarVisible:NO];
6652 fw = [[EmacsFSWindow alloc]
6653 initWithContentRect:[w contentRectForFrameRect:wr]
6654 styleMask:NSBorderlessWindowMask
6655 backing:NSBackingStoreBuffered
6659 [fw setContentView:[w contentView]];
6660 [fw setTitle:[w title]];
6661 [fw setDelegate:self];
6662 [fw setAcceptsMouseMovedEvents: YES];
6663 #if !defined (NS_IMPL_COCOA) || \
6664 MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_9
6665 [fw useOptimizedDrawing: YES];
6667 [fw setResizeIncrements: sz];
6668 [fw setBackgroundColor: col];
6669 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6672 f->border_width = 0;
6673 FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
6674 tobar_height = FRAME_TOOLBAR_HEIGHT (f);
6675 FRAME_TOOLBAR_HEIGHT (f) = 0;
6679 [self windowWillEnterFullScreen:nil];
6680 [fw makeKeyAndOrderFront:NSApp];
6681 [fw makeFirstResponder:self];
6683 r = [fw frameRectForContentRect:[screen frame]];
6684 [fw setFrame: r display:YES animate:ns_use_fullscreen_animation];
6685 [self windowDidEnterFullScreen:nil];
6696 #ifdef NS_IMPL_COCOA
6697 [NSApp setPresentationOptions: NSApplicationPresentationDefault];
6699 [NSMenu setMenuBarVisible:YES];
6703 [w setContentView:[fw contentView]];
6704 [w setResizeIncrements: sz];
6705 [w setBackgroundColor: col];
6706 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6709 f->border_width = bwidth;
6710 FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
6711 if (FRAME_EXTERNAL_TOOL_BAR (f))
6712 FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
6714 [self windowWillExitFullScreen:nil];
6715 [fw setFrame: [w frame] display:YES animate:ns_use_fullscreen_animation];
6717 [w makeKeyAndOrderFront:NSApp];
6718 [self windowDidExitFullScreen:nil];
6719 [self updateFrameSize:YES];
6725 if (fs_state != emacsframe->want_fullscreen)
6727 if (fs_state == FULLSCREEN_BOTH)
6729 [self toggleFullScreen:self];
6732 switch (emacsframe->want_fullscreen)
6734 case FULLSCREEN_BOTH:
6735 [self toggleFullScreen:self];
6737 case FULLSCREEN_WIDTH:
6738 next_maximized = FULLSCREEN_WIDTH;
6739 if (fs_state != FULLSCREEN_BOTH)
6740 [[self window] performZoom:self];
6742 case FULLSCREEN_HEIGHT:
6743 next_maximized = FULLSCREEN_HEIGHT;
6744 if (fs_state != FULLSCREEN_BOTH)
6745 [[self window] performZoom:self];
6747 case FULLSCREEN_MAXIMIZED:
6748 next_maximized = FULLSCREEN_MAXIMIZED;
6749 if (fs_state != FULLSCREEN_BOTH)
6750 [[self window] performZoom:self];
6752 case FULLSCREEN_NONE:
6753 if (fs_state != FULLSCREEN_BOTH)
6755 next_maximized = FULLSCREEN_NONE;
6756 [[self window] performZoom:self];
6761 emacsframe->want_fullscreen = FULLSCREEN_NONE;
6766 - (void) setFSValue: (int)value
6768 Lisp_Object lval = Qnil;
6771 case FULLSCREEN_BOTH:
6774 case FULLSCREEN_WIDTH:
6777 case FULLSCREEN_HEIGHT:
6780 case FULLSCREEN_MAXIMIZED:
6784 store_frame_param (emacsframe, Qfullscreen, lval);
6788 - (void)mouseEntered: (NSEvent *)theEvent
6790 NSTRACE (mouseEntered);
6792 FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
6793 = EV_TIMESTAMP (theEvent);
6797 - (void)mouseExited: (NSEvent *)theEvent
6799 Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
6801 NSTRACE (mouseExited);
6806 FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
6807 = EV_TIMESTAMP (theEvent);
6809 if (emacsframe == hlinfo->mouse_face_mouse_frame)
6811 clear_mouse_face (hlinfo);
6812 hlinfo->mouse_face_mouse_frame = 0;
6820 if (context_menu_value == -1)
6821 context_menu_value = [sender tag];
6824 NSInteger tag = [sender tag];
6825 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
6826 emacsframe->menu_bar_vector,
6830 ns_send_appdefined (-1);
6835 - (EmacsToolbar *)toolbar
6841 /* this gets called on toolbar button click */
6842 - toolbarClicked: (id)item
6845 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
6847 NSTRACE (toolbarClicked);
6852 /* send first event (for some reason two needed) */
6853 theEvent = [[self window] currentEvent];
6854 emacs_event->kind = TOOL_BAR_EVENT;
6855 XSETFRAME (emacs_event->arg, emacsframe);
6856 EV_TRAILER (theEvent);
6858 emacs_event->kind = TOOL_BAR_EVENT;
6859 /* XSETINT (emacs_event->code, 0); */
6860 emacs_event->arg = AREF (emacsframe->tool_bar_items,
6861 idx + TOOL_BAR_ITEM_KEY);
6862 emacs_event->modifiers = EV_MODIFIERS (theEvent);
6863 EV_TRAILER (theEvent);
6868 - toggleToolbar: (id)sender
6873 emacs_event->kind = NS_NONKEY_EVENT;
6874 emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
6875 EV_TRAILER ((id)nil);
6880 - (void)drawRect: (NSRect)rect
6882 int x = NSMinX (rect), y = NSMinY (rect);
6883 int width = NSWidth (rect), height = NSHeight (rect);
6887 if (!emacsframe || !emacsframe->output_data.ns)
6890 ns_clear_frame_area (emacsframe, x, y, width, height);
6892 expose_frame (emacsframe, x, y, width, height);
6896 drawRect: may be called (at least in OS X 10.5) for invisible
6897 views as well for some reason. Thus, do not infer visibility
6900 emacsframe->async_visible = 1;
6901 emacsframe->async_iconified = 0;
6906 /* NSDraggingDestination protocol methods. Actually this is not really a
6907 protocol, but a category of Object. O well... */
6909 -(NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
6911 NSTRACE (draggingEntered);
6912 return NSDragOperationGeneric;
6916 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
6922 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
6927 NSEvent *theEvent = [[self window] currentEvent];
6929 NSDragOperation op = [sender draggingSourceOperationMask];
6932 NSTRACE (performDragOperation);
6937 position = [self convertPoint: [sender draggingLocation] fromView: nil];
6938 x = lrint (position.x); y = lrint (position.y);
6940 pb = [sender draggingPasteboard];
6941 type = [pb availableTypeFromArray: ns_drag_types];
6943 if (! (op & (NSDragOperationMove|NSDragOperationDelete)) &&
6944 // URL drags contain all operations (0xf), don't allow all to be set.
6947 if (op & NSDragOperationLink)
6948 modifiers |= NSControlKeyMask;
6949 if (op & NSDragOperationCopy)
6950 modifiers |= NSAlternateKeyMask;
6951 if (op & NSDragOperationGeneric)
6952 modifiers |= NSCommandKeyMask;
6955 modifiers = EV_MODIFIERS2 (modifiers);
6960 else if ([type isEqualToString: NSFilenamesPboardType])
6963 NSEnumerator *fenum;
6966 if (!(files = [pb propertyListForType: type]))
6969 fenum = [files objectEnumerator];
6970 while ( (file = [fenum nextObject]) )
6972 emacs_event->kind = DRAG_N_DROP_EVENT;
6973 XSETINT (emacs_event->x, x);
6974 XSETINT (emacs_event->y, y);
6975 ns_input_file = append2 (ns_input_file,
6976 build_string ([file UTF8String]));
6977 emacs_event->modifiers = modifiers;
6978 emacs_event->arg = list2 (Qfile, build_string ([file UTF8String]));
6979 EV_TRAILER (theEvent);
6983 else if ([type isEqualToString: NSURLPboardType])
6985 NSURL *url = [NSURL URLFromPasteboard: pb];
6986 if (url == nil) return NO;
6988 emacs_event->kind = DRAG_N_DROP_EVENT;
6989 XSETINT (emacs_event->x, x);
6990 XSETINT (emacs_event->y, y);
6991 emacs_event->modifiers = modifiers;
6992 emacs_event->arg = list2 (Qurl,
6993 build_string ([[url absoluteString]
6995 EV_TRAILER (theEvent);
6997 if ([url isFileURL] != NO)
6999 NSString *file = [url path];
7000 ns_input_file = append2 (ns_input_file,
7001 build_string ([file UTF8String]));
7005 else if ([type isEqualToString: NSStringPboardType]
7006 || [type isEqualToString: NSTabularTextPboardType])
7010 if (! (data = [pb stringForType: type]))
7013 emacs_event->kind = DRAG_N_DROP_EVENT;
7014 XSETINT (emacs_event->x, x);
7015 XSETINT (emacs_event->y, y);
7016 emacs_event->modifiers = modifiers;
7017 emacs_event->arg = list2 (Qnil, build_string ([data UTF8String]));
7018 EV_TRAILER (theEvent);
7023 fprintf (stderr, "Invalid data type in dragging pasteboard");
7029 - (id) validRequestorForSendType: (NSString *)typeSent
7030 returnType: (NSString *)typeReturned
7032 NSTRACE (validRequestorForSendType);
7033 if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
7034 && typeReturned == nil)
7036 if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
7040 return [super validRequestorForSendType: typeSent
7041 returnType: typeReturned];
7045 /* The next two methods are part of NSServicesRequests informal protocol,
7046 supposedly called when a services menu item is chosen from this app.
7047 But this should not happen because we override the services menu with our
7048 own entries which call ns-perform-service.
7049 Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
7050 So let's at least stub them out until further investigation can be done. */
7052 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
7054 /* we could call ns_string_from_pasteboard(pboard) here but then it should
7055 be written into the buffer in place of the existing selection..
7056 ordinary service calls go through functions defined in ns-win.el */
7060 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
7062 NSArray *typesDeclared;
7065 /* We only support NSStringPboardType */
7066 if ([types containsObject:NSStringPboardType] == NO) {
7070 val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7071 if (CONSP (val) && SYMBOLP (XCAR (val)))
7074 if (CONSP (val) && NILP (XCDR (val)))
7077 if (! STRINGP (val))
7080 typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
7081 [pb declareTypes:typesDeclared owner:nil];
7082 ns_string_to_pasteboard (pb, val);
7087 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
7088 (gives a miniaturized version of the window); currently we use the latter for
7089 frames whose active buffer doesn't correspond to any file
7090 (e.g., '*scratch*') */
7091 - setMiniwindowImage: (BOOL) setMini
7093 id image = [[self window] miniwindowImage];
7094 NSTRACE (setMiniwindowImage);
7096 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
7097 about "AppleDockIconEnabled" notwithstanding, however the set message
7098 below has its effect nonetheless. */
7099 if (image != emacsframe->output_data.ns->miniimage)
7101 if (image && [image isKindOfClass: [EmacsImage class]])
7103 [[self window] setMiniwindowImage:
7104 setMini ? emacsframe->output_data.ns->miniimage : nil];
7111 - (void) setRows: (int) r andColumns: (int) c
7117 @end /* EmacsView */
7121 /* ==========================================================================
7123 EmacsWindow implementation
7125 ========================================================================== */
7127 @implementation EmacsWindow
7129 #ifdef NS_IMPL_COCOA
7130 - (id)accessibilityAttributeValue:(NSString *)attribute
7132 Lisp_Object str = Qnil;
7133 struct frame *f = SELECTED_FRAME ();
7134 struct buffer *curbuf = XBUFFER (XWINDOW (f->selected_window)->contents);
7136 if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
7137 return NSAccessibilityTextFieldRole;
7139 if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]
7140 && curbuf && ! NILP (BVAR (curbuf, mark_active)))
7142 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7144 else if (curbuf && [attribute isEqualToString:NSAccessibilityValueAttribute])
7146 if (! NILP (BVAR (curbuf, mark_active)))
7147 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7151 ptrdiff_t start_byte = BUF_BEGV_BYTE (curbuf);
7152 ptrdiff_t byte_range = BUF_ZV_BYTE (curbuf) - start_byte;
7153 ptrdiff_t range = BUF_ZV (curbuf) - BUF_BEGV (curbuf);
7155 if (! NILP (BVAR (curbuf, enable_multibyte_characters)))
7156 str = make_uninit_multibyte_string (range, byte_range);
7158 str = make_uninit_string (range);
7159 /* To check: This returns emacs-utf-8, which is a superset of utf-8.
7160 Is this a problem? */
7161 memcpy (SDATA (str), BYTE_POS_ADDR (start_byte), byte_range);
7168 if (CONSP (str) && SYMBOLP (XCAR (str)))
7171 if (CONSP (str) && NILP (XCDR (str)))
7176 const char *utfStr = SSDATA (str);
7177 NSString *nsStr = [NSString stringWithUTF8String: utfStr];
7182 return [super accessibilityAttributeValue:attribute];
7184 #endif /* NS_IMPL_COCOA */
7186 /* If we have multiple monitors, one above the other, we don't want to
7187 restrict the height to just one monitor. So we override this. */
7188 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
7190 /* When making the frame visible for the first time or if there is just
7191 one screen, we want to constrain. Other times not. */
7192 NSArray *screens = [NSScreen screens];
7193 NSUInteger nr_screens = [screens count], nr_eff_screens = 0, i;
7194 NSTRACE (constrainFrameRect);
7195 NSTRACE_RECT ("input", frameRect);
7197 if (ns_menu_bar_should_be_hidden ())
7200 if (nr_screens == 1)
7201 return [super constrainFrameRect:frameRect toScreen:screen];
7203 #ifdef NS_IMPL_COCOA
7204 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7205 // If separate spaces is on, it is like each screen is independent. There is
7206 // no spanning of frames across screens.
7207 if ([NSScreen screensHaveSeparateSpaces])
7208 return [super constrainFrameRect:frameRect toScreen:screen];
7212 for (i = 0; i < nr_screens; ++i)
7214 NSScreen *s = [screens objectAtIndex: i];
7215 NSRect scrrect = [s frame];
7216 NSRect intersect = NSIntersectionRect (frameRect, scrrect);
7218 if (intersect.size.width > 0 || intersect.size.height > 0)
7222 if (nr_eff_screens == 1)
7223 return [super constrainFrameRect:frameRect toScreen:screen];
7225 /* The default implementation does two things 1) ensure that the top
7226 of the rectangle is below the menu bar (or below the top of the
7227 screen) and 2) resizes windows larger than the screen. As we
7228 don't want the latter, a smaller rectangle is used. */
7229 #define FAKE_HEIGHT 64
7230 float old_top = frameRect.origin.y + frameRect.size.height;
7232 r.size.height = FAKE_HEIGHT;
7233 r.size.width = frameRect.size.width;
7234 r.origin.x = frameRect.origin.x;
7235 r.origin.y = old_top - FAKE_HEIGHT;
7237 NSTRACE_RECT ("input to super", r);
7239 r = [super constrainFrameRect:r toScreen:screen];
7241 NSTRACE_RECT ("output from super", r);
7243 float new_top = r.origin.y + FAKE_HEIGHT;
7244 if (new_top < old_top)
7246 frameRect.origin.y = new_top - frameRect.size.height;
7249 NSTRACE_RECT ("output", frameRect);
7255 @end /* EmacsWindow */
7258 @implementation EmacsFSWindow
7260 - (BOOL)canBecomeKeyWindow
7265 - (BOOL)canBecomeMainWindow
7272 /* ==========================================================================
7274 EmacsScroller implementation
7276 ========================================================================== */
7279 @implementation EmacsScroller
7281 /* for repeat button push */
7282 #define SCROLL_BAR_FIRST_DELAY 0.5
7283 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
7285 + (CGFloat) scrollerWidth
7287 /* TODO: if we want to allow variable widths, this is the place to do it,
7288 however neither GNUstep nor Cocoa support it very well */
7290 #if !defined (NS_IMPL_COCOA) || \
7291 MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
7292 r = [NSScroller scrollerWidth];
7294 r = [NSScroller scrollerWidthForControlSize: NSRegularControlSize
7295 scrollerStyle: NSScrollerStyleLegacy];
7301 - initFrame: (NSRect )r window: (Lisp_Object)nwin
7303 NSTRACE (EmacsScroller_initFrame);
7305 r.size.width = [EmacsScroller scrollerWidth];
7306 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
7307 [self setContinuous: YES];
7308 [self setEnabled: YES];
7310 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
7311 locked against the top and bottom edges, and right edge on OS X, where
7312 scrollers are on right. */
7313 #ifdef NS_IMPL_GNUSTEP
7314 [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
7316 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
7319 window = XWINDOW (nwin);
7321 pixel_height = NSHeight (r);
7322 if (pixel_height == 0) pixel_height = 1;
7323 min_portion = 20 / pixel_height;
7325 frame = XFRAME (window->frame);
7326 if (FRAME_LIVE_P (frame))
7329 EmacsView *view = FRAME_NS_VIEW (frame);
7330 NSView *sview = [[view window] contentView];
7331 NSArray *subs = [sview subviews];
7333 /* disable optimization stopping redraw of other scrollbars */
7334 view->scrollbarsNeedingUpdate = 0;
7335 for (i =[subs count]-1; i >= 0; i--)
7336 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
7337 view->scrollbarsNeedingUpdate++;
7338 [sview addSubview: self];
7341 /* [self setFrame: r]; */
7347 - (void)setFrame: (NSRect)newRect
7349 NSTRACE (EmacsScroller_setFrame);
7350 /* block_input (); */
7351 pixel_height = NSHeight (newRect);
7352 if (pixel_height == 0) pixel_height = 1;
7353 min_portion = 20 / pixel_height;
7354 [super setFrame: newRect];
7355 /* unblock_input (); */
7361 NSTRACE (EmacsScroller_dealloc);
7363 wset_vertical_scroll_bar (window, Qnil);
7388 bool ret = condemned;
7393 /* ensure other scrollbar updates after deletion */
7394 view = (EmacsView *)FRAME_NS_VIEW (frame);
7396 view->scrollbarsNeedingUpdate++;
7398 wset_vertical_scroll_bar (window, Qnil);
7400 [self removeFromSuperview];
7408 - (void)resetCursorRects
7410 NSRect visible = [self visibleRect];
7411 NSTRACE (resetCursorRects);
7413 if (!NSIsEmptyRect (visible))
7414 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
7415 [[NSCursor arrowCursor] setOnMouseEntered: YES];
7419 - (int) checkSamePosition: (int) position portion: (int) portion
7422 return em_position ==position && em_portion ==portion && em_whole ==whole
7423 && portion != whole; /* needed for resize empty buf */
7427 - setPosition: (int)position portion: (int)portion whole: (int)whole
7429 NSTRACE (setPosition);
7431 em_position = position;
7432 em_portion = portion;
7435 if (portion >= whole)
7437 #ifdef NS_IMPL_COCOA
7438 [self setKnobProportion: 1.0];
7439 [self setDoubleValue: 1.0];
7441 [self setFloatValue: 0.0 knobProportion: 1.0];
7448 portion = max ((float)whole*min_portion/pixel_height, portion);
7449 pos = (float)position / (whole - portion);
7450 por = (CGFloat)portion/whole;
7451 #ifdef NS_IMPL_COCOA
7452 [self setKnobProportion: por];
7453 [self setDoubleValue: pos];
7455 [self setFloatValue: pos knobProportion: por];
7462 /* set up emacs_event */
7463 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
7469 emacs_event->part = last_hit_part;
7470 emacs_event->code = 0;
7471 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
7472 XSETWINDOW (win, window);
7473 emacs_event->frame_or_window = win;
7474 emacs_event->timestamp = EV_TIMESTAMP (e);
7475 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
7476 emacs_event->arg = Qnil;
7477 XSETINT (emacs_event->x, loc * pixel_height);
7478 XSETINT (emacs_event->y, pixel_height-20);
7482 n_emacs_events_pending++;
7483 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
7486 hold_event (emacs_event);
7487 EVENT_INIT (*emacs_event);
7488 ns_send_appdefined (-1);
7492 /* called manually thru timer to implement repeated button action w/hold-down */
7493 - repeatScroll: (NSTimer *)scrollEntry
7495 NSEvent *e = [[self window] currentEvent];
7496 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
7497 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
7499 /* clear timer if need be */
7500 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
7502 [scroll_repeat_entry invalidate];
7503 [scroll_repeat_entry release];
7504 scroll_repeat_entry = nil;
7510 = [[NSTimer scheduledTimerWithTimeInterval:
7511 SCROLL_BAR_CONTINUOUS_DELAY
7513 selector: @selector (repeatScroll:)
7519 [self sendScrollEventAtLoc: 0 fromEvent: e];
7524 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
7525 mouseDragged events without going into a modal loop. */
7526 - (void)mouseDown: (NSEvent *)e
7529 /* hitPart is only updated AFTER event is passed on */
7530 NSScrollerPart part = [self testPart: [e locationInWindow]];
7531 CGFloat inc = 0.0, loc, kloc, pos;
7534 NSTRACE (EmacsScroller_mouseDown);
7538 case NSScrollerDecrementPage:
7539 last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
7540 case NSScrollerIncrementPage:
7541 last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
7542 case NSScrollerDecrementLine:
7543 last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
7544 case NSScrollerIncrementLine:
7545 last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
7546 case NSScrollerKnob:
7547 last_hit_part = scroll_bar_handle; break;
7548 case NSScrollerKnobSlot: /* GNUstep-only */
7549 last_hit_part = scroll_bar_move_ratio; break;
7550 default: /* NSScrollerNoPart? */
7551 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
7558 pos = 0; /* ignored */
7560 /* set a timer to repeat, as we can't let superclass do this modally */
7562 = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
7564 selector: @selector (repeatScroll:)
7571 /* handle, or on GNUstep possibly slot */
7572 NSEvent *fake_event;
7574 /* compute float loc in slot and mouse offset on knob */
7575 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
7577 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
7583 else if (loc >= NSHeight (sr))
7585 loc = NSHeight (sr);
7593 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
7595 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
7597 last_mouse_offset = kloc;
7599 /* if knob, tell emacs a location offset by knob pos
7600 (to indicate top of handle) */
7601 if (part == NSScrollerKnob)
7602 pos = (loc - last_mouse_offset) / NSHeight (sr);
7604 /* else this is a slot click on GNUstep: go straight there */
7605 pos = loc / NSHeight (sr);
7607 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
7608 fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
7609 location: [e locationInWindow]
7610 modifierFlags: [e modifierFlags]
7611 timestamp: [e timestamp]
7612 windowNumber: [e windowNumber]
7613 context: [e context]
7614 eventNumber: [e eventNumber]
7615 clickCount: [e clickCount]
7616 pressure: [e pressure]];
7617 [super mouseUp: fake_event];
7620 if (part != NSScrollerKnob)
7621 [self sendScrollEventAtLoc: pos fromEvent: e];
7625 /* Called as we manually track scroller drags, rather than superclass. */
7626 - (void)mouseDragged: (NSEvent *)e
7631 NSTRACE (EmacsScroller_mouseDragged);
7633 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
7635 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
7641 else if (loc >= NSHeight (sr) + last_mouse_offset)
7643 loc = NSHeight (sr) + last_mouse_offset;
7646 pos = (loc - last_mouse_offset) / NSHeight (sr);
7647 [self sendScrollEventAtLoc: pos fromEvent: e];
7651 - (void)mouseUp: (NSEvent *)e
7653 if (scroll_repeat_entry)
7655 [scroll_repeat_entry invalidate];
7656 [scroll_repeat_entry release];
7657 scroll_repeat_entry = nil;
7659 last_hit_part = scroll_bar_above_handle;
7663 /* treat scrollwheel events in the bar as though they were in the main window */
7664 - (void) scrollWheel: (NSEvent *)theEvent
7666 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
7667 [view mouseDown: theEvent];
7670 @end /* EmacsScroller */
7673 #ifdef NS_IMPL_GNUSTEP
7674 /* Dummy class to get rid of startup warnings. */
7675 @implementation EmacsDocument
7681 /* ==========================================================================
7683 Font-related functions; these used to be in nsfaces.m
7685 ========================================================================== */
7689 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
7691 struct font *font = XFONT_OBJECT (font_object);
7692 EmacsView *view = FRAME_NS_VIEW (f);
7693 int font_ascent, font_descent;
7696 fontset = fontset_from_font (font_object);
7697 FRAME_FONTSET (f) = fontset;
7699 if (FRAME_FONT (f) == font)
7700 /* This font is already set in frame F. There's nothing more to
7704 FRAME_FONT (f) = font;
7706 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
7707 FRAME_COLUMN_WIDTH (f) = font->average_width;
7708 get_font_ascent_descent (font, &font_ascent, &font_descent);
7709 FRAME_LINE_HEIGHT (f) = font_ascent + font_descent;
7711 /* Compute the scroll bar width in character columns. */
7712 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
7714 int wid = FRAME_COLUMN_WIDTH (f);
7715 FRAME_CONFIG_SCROLL_BAR_COLS (f)
7716 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
7720 int wid = FRAME_COLUMN_WIDTH (f);
7721 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
7724 /* Compute the scroll bar height in character lines. */
7725 if (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) > 0)
7727 int height = FRAME_LINE_HEIGHT (f);
7728 FRAME_CONFIG_SCROLL_BAR_LINES (f)
7729 = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + height - 1) / height;
7733 int height = FRAME_LINE_HEIGHT (f);
7734 FRAME_CONFIG_SCROLL_BAR_LINES (f) = (14 + height - 1) / height;
7737 /* Now make the frame display the given font. */
7738 if (FRAME_NS_WINDOW (f) != 0 && ! [view isFullscreen])
7739 x_set_window_size (f, false, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
7740 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), true);
7746 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
7747 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
7751 ns_xlfd_to_fontname (const char *xlfd)
7752 /* --------------------------------------------------------------------------
7753 Convert an X font name (XLFD) to an NS font name.
7754 Only family is used.
7755 The string returned is temporarily allocated.
7756 -------------------------------------------------------------------------- */
7758 char *name = xmalloc (180);
7762 if (!strncmp (xlfd, "--", 2))
7763 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
7765 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
7767 /* stopgap for malformed XLFD input */
7768 if (strlen (name) == 0)
7769 strcpy (name, "Monaco");
7771 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
7772 also uppercase after '-' or ' ' */
7773 name[0] = c_toupper (name[0]);
7774 for (len =strlen (name), i =0; i<len; i++)
7780 name[i+1] = c_toupper (name[i+1]);
7782 else if (name[i] == '_')
7786 name[i+1] = c_toupper (name[i+1]);
7789 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
7790 ret = [[NSString stringWithUTF8String: name] UTF8String];
7797 syms_of_nsterm (void)
7799 NSTRACE (syms_of_nsterm);
7801 ns_antialias_threshold = 10.0;
7803 /* from 23+ we need to tell emacs what modifiers there are.. */
7804 DEFSYM (Qmodifier_value, "modifier-value");
7805 DEFSYM (Qalt, "alt");
7806 DEFSYM (Qhyper, "hyper");
7807 DEFSYM (Qmeta, "meta");
7808 DEFSYM (Qsuper, "super");
7809 DEFSYM (Qcontrol, "control");
7810 DEFSYM (QUTF8_STRING, "UTF8_STRING");
7812 DEFSYM (Qfile, "file");
7813 DEFSYM (Qurl, "url");
7815 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
7816 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
7817 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
7818 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
7819 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
7821 DEFVAR_LISP ("ns-input-file", ns_input_file,
7822 "The file specified in the last NS event.");
7823 ns_input_file =Qnil;
7825 DEFVAR_LISP ("ns-working-text", ns_working_text,
7826 "String for visualizing working composition sequence.");
7827 ns_working_text =Qnil;
7829 DEFVAR_LISP ("ns-input-font", ns_input_font,
7830 "The font specified in the last NS event.");
7831 ns_input_font =Qnil;
7833 DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
7834 "The fontsize specified in the last NS event.");
7835 ns_input_fontsize =Qnil;
7837 DEFVAR_LISP ("ns-input-line", ns_input_line,
7838 "The line specified in the last NS event.");
7839 ns_input_line =Qnil;
7841 DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
7842 "The service name specified in the last NS event.");
7843 ns_input_spi_name =Qnil;
7845 DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
7846 "The service argument specified in the last NS event.");
7847 ns_input_spi_arg =Qnil;
7849 DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
7850 "This variable describes the behavior of the alternate or option key.\n\
7851 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7852 Set to none means that the alternate / option key is not interpreted by Emacs\n\
7853 at all, allowing it to be used at a lower level for accented character entry.");
7854 ns_alternate_modifier = Qmeta;
7856 DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
7857 "This variable describes the behavior of the right alternate or option key.\n\
7858 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7859 Set to left means be the same key as `ns-alternate-modifier'.\n\
7860 Set to none means that the alternate / option key is not interpreted by Emacs\n\
7861 at all, allowing it to be used at a lower level for accented character entry.");
7862 ns_right_alternate_modifier = Qleft;
7864 DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
7865 "This variable describes the behavior of the command key.\n\
7866 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
7867 ns_command_modifier = Qsuper;
7869 DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
7870 "This variable describes the behavior of the right command key.\n\
7871 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7872 Set to left means be the same key as `ns-command-modifier'.\n\
7873 Set to none means that the command / option key is not interpreted by Emacs\n\
7874 at all, allowing it to be used at a lower level for accented character entry.");
7875 ns_right_command_modifier = Qleft;
7877 DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
7878 "This variable describes the behavior of the control key.\n\
7879 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
7880 ns_control_modifier = Qcontrol;
7882 DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
7883 "This variable describes the behavior of the right control key.\n\
7884 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7885 Set to left means be the same key as `ns-control-modifier'.\n\
7886 Set to none means that the control / option key is not interpreted by Emacs\n\
7887 at all, allowing it to be used at a lower level for accented character entry.");
7888 ns_right_control_modifier = Qleft;
7890 DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
7891 "This variable describes the behavior of the function key (on laptops).\n\
7892 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7893 Set to none means that the function key is not interpreted by Emacs at all,\n\
7894 allowing it to be used at a lower level for accented character entry.");
7895 ns_function_modifier = Qnone;
7897 DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
7898 "Non-nil (the default) means to render text antialiased.");
7899 ns_antialias_text = Qt;
7901 DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
7902 "Whether to confirm application quit using dialog.");
7903 ns_confirm_quit = Qnil;
7905 DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
7906 doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
7907 Only works on OSX 10.6 or later. */);
7908 ns_auto_hide_menu_bar = Qnil;
7910 DEFVAR_BOOL ("ns-use-native-fullscreen", ns_use_native_fullscreen,
7911 doc: /*Non-nil means to use native fullscreen on OSX >= 10.7.
7912 Nil means use fullscreen the old (< 10.7) way. The old way works better with
7913 multiple monitors, but lacks tool bar. This variable is ignored on OSX < 10.7.
7914 Default is t for OSX >= 10.7, nil otherwise. */);
7915 #ifdef HAVE_NATIVE_FS
7916 ns_use_native_fullscreen = YES;
7918 ns_use_native_fullscreen = NO;
7920 ns_last_use_native_fullscreen = ns_use_native_fullscreen;
7922 DEFVAR_BOOL ("ns-use-fullscreen-animation", ns_use_fullscreen_animation,
7923 doc: /*Non-nil means use animation on non-native fullscreen.
7924 For native fullscreen, this does nothing.
7925 Default is nil. */);
7926 ns_use_fullscreen_animation = NO;
7928 DEFVAR_BOOL ("ns-use-srgb-colorspace", ns_use_srgb_colorspace,
7929 doc: /*Non-nil means to use sRGB colorspace on OSX >= 10.7.
7930 Note that this does not apply to images.
7931 This variable is ignored on OSX < 10.7 and GNUstep. */);
7932 ns_use_srgb_colorspace = YES;
7934 /* TODO: move to common code */
7935 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
7936 doc: /* Which toolkit scroll bars Emacs uses, if any.
7937 A value of nil means Emacs doesn't use toolkit scroll bars.
7938 With the X Window system, the value is a symbol describing the
7939 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
7940 With MS Windows or Nextstep, the value is t. */);
7941 Vx_toolkit_scroll_bars = Qt;
7943 DEFVAR_BOOL ("x-use-underline-position-properties",
7944 x_use_underline_position_properties,
7945 doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
7946 A value of nil means ignore them. If you encounter fonts with bogus
7947 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
7948 to 4.1, set this to nil. */);
7949 x_use_underline_position_properties = 0;
7951 DEFVAR_BOOL ("x-underline-at-descent-line",
7952 x_underline_at_descent_line,
7953 doc: /* Non-nil means to draw the underline at the same place as the descent line.
7954 A value of nil means to draw the underline according to the value of the
7955 variable `x-use-underline-position-properties', which is usually at the
7956 baseline level. The default value is nil. */);
7957 x_underline_at_descent_line = 0;
7959 /* Tell Emacs about this window system. */
7960 Fprovide (Qns, Qnil);
7962 DEFSYM (Qcocoa, "cocoa");
7963 DEFSYM (Qgnustep, "gnustep");
7965 #ifdef NS_IMPL_COCOA
7966 Fprovide (Qcocoa, Qnil);
7969 Fprovide (Qgnustep, Qnil);